@buildonspark/spark-sdk 0.3.9 → 0.4.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 (65) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/android/build.gradle +1 -1
  3. package/android/src/main/java/uniffi/uniffi/spark_frost/spark_frost.kt +1361 -1367
  4. package/android/src/main/jniLibs/arm64-v8a/libuniffi_spark_frost.so +0 -0
  5. package/android/src/main/jniLibs/armeabi-v7a/libuniffi_spark_frost.so +0 -0
  6. package/android/src/main/jniLibs/x86/libuniffi_spark_frost.so +0 -0
  7. package/android/src/main/jniLibs/x86_64/libuniffi_spark_frost.so +0 -0
  8. package/dist/bare/index.cjs +322 -142
  9. package/dist/bare/index.d.cts +13 -3
  10. package/dist/bare/index.d.ts +13 -3
  11. package/dist/bare/index.js +321 -142
  12. package/dist/{chunk-S55NZT4P.js → chunk-27ILUWDJ.js} +1 -1
  13. package/dist/{chunk-O4C4HGQL.js → chunk-G3LHXHF3.js} +313 -133
  14. package/dist/{chunk-WRE2T22S.js → chunk-LOXWCMZL.js} +1 -1
  15. package/dist/{chunk-MFCM6GUD.js → chunk-WICAF6BS.js} +1 -1
  16. package/dist/debug.cjs +322 -143
  17. package/dist/debug.d.cts +5 -4
  18. package/dist/debug.d.ts +5 -4
  19. package/dist/debug.js +2 -2
  20. package/dist/index.cjs +323 -143
  21. package/dist/index.d.cts +4 -4
  22. package/dist/index.d.ts +4 -4
  23. package/dist/index.js +5 -3
  24. package/dist/index.node.cjs +323 -143
  25. package/dist/index.node.d.cts +4 -4
  26. package/dist/index.node.d.ts +4 -4
  27. package/dist/index.node.js +4 -2
  28. package/dist/{logging-DDeMLsVN.d.ts → logging-BNGm6dBp.d.ts} +3 -2
  29. package/dist/{logging-CXhvuqJJ.d.cts → logging-D3IfXfHG.d.cts} +3 -2
  30. package/dist/native/index.react-native.cjs +466 -145
  31. package/dist/native/index.react-native.d.cts +21 -3
  32. package/dist/native/index.react-native.d.ts +21 -3
  33. package/dist/native/index.react-native.js +462 -144
  34. package/dist/{spark-wallet.browser-Cz8c4kOW.d.ts → spark-wallet.browser-B2rGwjuM.d.ts} +1 -1
  35. package/dist/{spark-wallet.browser-CbYo8A_U.d.cts → spark-wallet.browser-Ck9No4Ks.d.cts} +1 -1
  36. package/dist/{spark-wallet.node-CmIvxtcC.d.ts → spark-wallet.node-BqmKsGPs.d.ts} +1 -1
  37. package/dist/{spark-wallet.node-4WQgWwB2.d.cts → spark-wallet.node-C2TIkyt4.d.cts} +1 -1
  38. package/dist/tests/test-utils.cjs +321 -143
  39. package/dist/tests/test-utils.d.cts +16 -2
  40. package/dist/tests/test-utils.d.ts +16 -2
  41. package/dist/tests/test-utils.js +4 -4
  42. package/dist/{token-transactions-CV8QD3I7.d.cts → token-transactions-Db8mkjnU.d.cts} +1 -1
  43. package/dist/{token-transactions-Bu023ztN.d.ts → token-transactions-DoMcrxXQ.d.ts} +1 -1
  44. package/dist/{wallet-config-Bmk2eAn8.d.ts → wallet-config-Bg3kWltL.d.ts} +11 -2
  45. package/dist/{wallet-config-DQw5llqA.d.cts → wallet-config-CuZKNo9S.d.cts} +11 -2
  46. package/ios/spark_frostFFI.xcframework/ios-arm64/SparkFrost +0 -0
  47. package/ios/spark_frostFFI.xcframework/ios-arm64/spark_frostFFI.framework/spark_frostFFI +0 -0
  48. package/ios/spark_frostFFI.xcframework/ios-arm64_x86_64-simulator/SparkFrost +0 -0
  49. package/ios/spark_frostFFI.xcframework/ios-arm64_x86_64-simulator/spark_frostFFI.framework/spark_frostFFI +0 -0
  50. package/ios/spark_frostFFI.xcframework/macos-arm64_x86_64/spark_frostFFI.framework/spark_frostFFI +0 -0
  51. package/package.json +1 -1
  52. package/src/index.react-native.ts +8 -2
  53. package/src/services/config.ts +5 -0
  54. package/src/services/wallet-config.ts +10 -0
  55. package/src/services/xhr-transport.ts +13 -3
  56. package/src/signer/signer.react-native.ts +73 -1
  57. package/src/spark-wallet/spark-wallet.ts +98 -76
  58. package/src/tests/integration/lightning.test.ts +0 -28
  59. package/src/tests/integration/static_deposit.test.ts +4 -8
  60. package/src/tests/integration/unilateral-exit.test.ts +117 -0
  61. package/src/tests/optimize.test.ts +31 -1
  62. package/src/tests/utils/signing.ts +33 -0
  63. package/src/tests/utils/test-faucet.ts +61 -0
  64. package/src/utils/optimize.ts +42 -0
  65. package/src/utils/unilateral-exit.ts +1 -40
package/dist/index.cjs CHANGED
@@ -1343,6 +1343,7 @@ __export(index_exports, {
1343
1343
  getTxFromRawTxHex: () => getTxFromRawTxHex,
1344
1344
  getTxId: () => getTxId,
1345
1345
  getTxIdNoReverse: () => getTxIdNoReverse,
1346
+ hash160: () => hash160,
1346
1347
  initializeTracerEnv: () => initializeTracerEnvBrowser,
1347
1348
  isEphemeralAnchorOutput: () => isEphemeralAnchorOutput,
1348
1349
  isLegacySparkAddress: () => isLegacySparkAddress,
@@ -18501,7 +18502,11 @@ var BASE_CONFIG = {
18501
18502
  console: {
18502
18503
  otel: false
18503
18504
  },
18504
- events: {}
18505
+ events: {},
18506
+ optimizationOptions: {
18507
+ auto: true,
18508
+ multiplicity: 0
18509
+ }
18505
18510
  };
18506
18511
  var LOCAL_WALLET_CONFIG = {
18507
18512
  ...BASE_CONFIG,
@@ -21038,7 +21043,7 @@ var isWebExtension = (
21038
21043
  "chrome" in globalThis && globalThis.chrome.runtime?.id
21039
21044
  );
21040
21045
  var userAgent = "navigator" in globalThis ? globalThis.navigator.userAgent || "unknown-user-agent" : void 0;
21041
- var packageVersion = true ? "0.3.9" : "unknown";
21046
+ var packageVersion = true ? "0.4.0" : "unknown";
21042
21047
  var baseEnvStr = "unknown";
21043
21048
  if (isBun) {
21044
21049
  const bunVersion = "version" in globalThis.Bun ? globalThis.Bun.version : "unknown-version";
@@ -22823,6 +22828,9 @@ var WalletConfigService = class {
22823
22828
  getEvents() {
22824
22829
  return this.config.events;
22825
22830
  }
22831
+ getOptimizationOptions() {
22832
+ return this.config.optimizationOptions;
22833
+ }
22826
22834
  };
22827
22835
 
22828
22836
  // src/services/coop-exit.ts
@@ -30693,6 +30701,14 @@ var BitcoinFaucet = class _BitcoinFaucet {
30693
30701
  async mineBlocks(numBlocks) {
30694
30702
  return await this.generateToAddress(numBlocks, this.miningAddress);
30695
30703
  }
30704
+ async mineBlocksAndWaitForMiningToComplete(numBlocks) {
30705
+ const startBlock = await this.getBlockCount();
30706
+ await this.mineBlocks(numBlocks);
30707
+ await this.waitForBlocksMined({
30708
+ startBlock,
30709
+ expectedIncrease: numBlocks
30710
+ });
30711
+ }
30696
30712
  async call(method, params) {
30697
30713
  try {
30698
30714
  const { fetch, Headers: Headers2 } = getFetch();
@@ -30745,15 +30761,50 @@ var BitcoinFaucet = class _BitcoinFaucet {
30745
30761
  async getBlock(blockHash) {
30746
30762
  return await this.call("getblock", [blockHash, 2]);
30747
30763
  }
30764
+ async getBlockCount() {
30765
+ return await this.call("getblockcount", []);
30766
+ }
30767
+ async waitForBlocksMined({
30768
+ startBlock,
30769
+ expectedIncrease,
30770
+ timeoutMs = 3e4,
30771
+ intervalMs = 5e3
30772
+ }) {
30773
+ const deadline = Date.now() + timeoutMs;
30774
+ await new Promise((r) => setTimeout(r, intervalMs));
30775
+ const start = startBlock;
30776
+ const target = start + expectedIncrease;
30777
+ while (Date.now() < deadline) {
30778
+ const currentBlock = await this.getBlockCount();
30779
+ if (currentBlock >= target) return currentBlock;
30780
+ await new Promise((r) => setTimeout(r, intervalMs));
30781
+ }
30782
+ throw new Error(
30783
+ `Timed out waiting for ${expectedIncrease} blocks (target height ${target})`
30784
+ );
30785
+ }
30748
30786
  async broadcastTx(txHex) {
30749
30787
  let response = await this.call("sendrawtransaction", [txHex, 0]);
30750
30788
  return response;
30751
30789
  }
30790
+ async submitPackage(txHexs) {
30791
+ let response = await this.call("submitpackage", [txHexs]);
30792
+ return response;
30793
+ }
30752
30794
  async getNewAddress() {
30753
30795
  const key = import_secp256k113.secp256k1.utils.randomPrivateKey();
30754
30796
  const pubKey = import_secp256k113.secp256k1.getPublicKey(key);
30755
30797
  return getP2TRAddressFromPublicKey(pubKey, 4 /* LOCAL */);
30756
30798
  }
30799
+ async getNewExternalWallet() {
30800
+ const key = import_secp256k113.secp256k1.utils.randomPrivateKey();
30801
+ const pubKey = import_secp256k113.secp256k1.getPublicKey(key);
30802
+ return {
30803
+ address: getP2TRAddressFromPublicKey(pubKey, 4 /* LOCAL */),
30804
+ key,
30805
+ pubKey
30806
+ };
30807
+ }
30757
30808
  async sendToAddress(address, amount, blocksToGenerate = 1) {
30758
30809
  const coin = await this.fund();
30759
30810
  if (!coin) {
@@ -30810,76 +30861,6 @@ function chunkArray(arr, size) {
30810
30861
  return chunks;
30811
30862
  }
30812
30863
 
30813
- // src/utils/optimize.ts
30814
- init_buffer();
30815
- var DENOMINATIONS = Array.from({ length: 28 }, (_, i) => 2 ** i);
30816
- function assert(condition, message) {
30817
- if (!condition) {
30818
- throw new InternalValidationError(message || "Assertion failed");
30819
- }
30820
- }
30821
- function sum(arr) {
30822
- return arr.reduce((a, b) => a + b, 0);
30823
- }
30824
- function sorted(arr) {
30825
- return [...arr].sort((a, b) => a - b);
30826
- }
30827
- function equals(a, b) {
30828
- return a.length === b.length && a.every((val, index) => val === b[index]);
30829
- }
30830
- function greedyLeaves(amount) {
30831
- const leaves = [];
30832
- let remaining = amount;
30833
- for (let i = DENOMINATIONS.length - 1; i >= 0; i--) {
30834
- const leaf = DENOMINATIONS[i];
30835
- if (typeof leaf === "number" && leaf > 0) {
30836
- while (remaining >= leaf) {
30837
- remaining -= leaf;
30838
- leaves.push(leaf);
30839
- }
30840
- }
30841
- }
30842
- assert(sum(leaves) === amount, "greedy_leaves: sum mismatch");
30843
- return sorted(leaves);
30844
- }
30845
- var Swap = class {
30846
- inLeaves;
30847
- outLeaves;
30848
- constructor(inLeaves, outLeaves) {
30849
- this.inLeaves = [...inLeaves];
30850
- this.outLeaves = [...outLeaves];
30851
- assert(
30852
- sum(this.inLeaves) === sum(this.outLeaves),
30853
- "Swap in/out leaves must sum to same value for swap: " + this.toString()
30854
- );
30855
- }
30856
- toString() {
30857
- return `Swap(in=${JSON.stringify(this.inLeaves)}, out=${JSON.stringify(this.outLeaves)})`;
30858
- }
30859
- };
30860
- function maximizeUnilateralExit(inputLeaves, maxLeavesPerSwap = 64) {
30861
- const swaps = [];
30862
- let batch = [];
30863
- let leaves = sorted(inputLeaves);
30864
- while (leaves.length > 0) {
30865
- batch.push(leaves.shift());
30866
- const target = greedyLeaves(sum(batch));
30867
- if (batch.length >= maxLeavesPerSwap || target.length >= maxLeavesPerSwap) {
30868
- if (!equals(target, batch)) {
30869
- swaps.push(new Swap([...batch], target));
30870
- }
30871
- batch = [];
30872
- }
30873
- }
30874
- if (batch.length > 0) {
30875
- const target = greedyLeaves(sum(batch));
30876
- if (!equals(target, batch)) {
30877
- swaps.push(new Swap([...batch], target));
30878
- }
30879
- }
30880
- return swaps;
30881
- }
30882
-
30883
30864
  // src/utils/retry.ts
30884
30865
  init_buffer();
30885
30866
  var DEFAULT_RETRY_CONFIG = {
@@ -30958,6 +30939,200 @@ var SparkWalletEvent = {
30958
30939
  StreamReconnecting: "stream:reconnecting"
30959
30940
  };
30960
30941
 
30942
+ // src/utils/optimize.ts
30943
+ init_buffer();
30944
+ var DENOMINATIONS = Array.from({ length: 28 }, (_, i) => 2 ** i);
30945
+ function assert(condition, message) {
30946
+ if (!condition) {
30947
+ throw new InternalValidationError(message || "Assertion failed");
30948
+ }
30949
+ }
30950
+ function sum(arr) {
30951
+ return arr.reduce((a, b) => a + b, 0);
30952
+ }
30953
+ function sorted(arr) {
30954
+ return [...arr].sort((a, b) => a - b);
30955
+ }
30956
+ function equals(a, b) {
30957
+ return a.length === b.length && a.every((val, index) => val === b[index]);
30958
+ }
30959
+ function countOccurrences(arr) {
30960
+ const map = /* @__PURE__ */ new Map();
30961
+ for (const x of arr) {
30962
+ map.set(x, (map.get(x) ?? 0) + 1);
30963
+ }
30964
+ return map;
30965
+ }
30966
+ function subtractCounters(a, b) {
30967
+ const result = /* @__PURE__ */ new Map();
30968
+ for (const [key, value] of a.entries()) {
30969
+ const diff = value - (b.get(key) ?? 0);
30970
+ if (diff > 0) {
30971
+ result.set(key, diff);
30972
+ }
30973
+ }
30974
+ return result;
30975
+ }
30976
+ function counterToFlatArray(counter) {
30977
+ const arr = [];
30978
+ for (const [k, v] of Array.from(counter.entries()).sort(
30979
+ (a, b) => a[0] - b[0]
30980
+ )) {
30981
+ for (let i = 0; i < v; i++) {
30982
+ arr.push(k);
30983
+ }
30984
+ }
30985
+ return arr;
30986
+ }
30987
+ function greedyLeaves(amount) {
30988
+ const leaves = [];
30989
+ let remaining = amount;
30990
+ for (let i = DENOMINATIONS.length - 1; i >= 0; i--) {
30991
+ const leaf = DENOMINATIONS[i];
30992
+ if (typeof leaf === "number" && leaf > 0) {
30993
+ while (remaining >= leaf) {
30994
+ remaining -= leaf;
30995
+ leaves.push(leaf);
30996
+ }
30997
+ }
30998
+ }
30999
+ assert(sum(leaves) === amount, "greedy_leaves: sum mismatch");
31000
+ return sorted(leaves);
31001
+ }
31002
+ function swapMinimizingLeaves(amount, multiplicity = 1) {
31003
+ const leaves = [];
31004
+ let remaining = amount;
31005
+ assert(multiplicity > 0, "multiplicity must be > 0");
31006
+ for (const leaf of DENOMINATIONS) {
31007
+ if (typeof leaf === "number" && leaf > 0) {
31008
+ for (let i = 0; i < multiplicity; i++) {
31009
+ if (remaining >= leaf) {
31010
+ remaining -= leaf;
31011
+ leaves.push(leaf);
31012
+ }
31013
+ }
31014
+ }
31015
+ }
31016
+ leaves.push(...greedyLeaves(remaining));
31017
+ assert(sum(leaves) === amount, "swap_minimizing_leaves: sum mismatch");
31018
+ return sorted(leaves);
31019
+ }
31020
+ var Swap = class {
31021
+ inLeaves;
31022
+ outLeaves;
31023
+ constructor(inLeaves, outLeaves) {
31024
+ this.inLeaves = [...inLeaves];
31025
+ this.outLeaves = [...outLeaves];
31026
+ assert(
31027
+ sum(this.inLeaves) === sum(this.outLeaves),
31028
+ "Swap in/out leaves must sum to same value for swap: " + this.toString()
31029
+ );
31030
+ }
31031
+ toString() {
31032
+ return `Swap(in=${JSON.stringify(this.inLeaves)}, out=${JSON.stringify(this.outLeaves)})`;
31033
+ }
31034
+ };
31035
+ function maximizeUnilateralExit(inputLeaves, maxLeavesPerSwap = 64) {
31036
+ const swaps = [];
31037
+ let batch = [];
31038
+ let leaves = sorted(inputLeaves);
31039
+ while (leaves.length > 0) {
31040
+ batch.push(leaves.shift());
31041
+ const target = greedyLeaves(sum(batch));
31042
+ if (batch.length >= maxLeavesPerSwap || target.length >= maxLeavesPerSwap) {
31043
+ if (!equals(target, batch)) {
31044
+ swaps.push(new Swap([...batch], target));
31045
+ }
31046
+ batch = [];
31047
+ }
31048
+ }
31049
+ if (batch.length > 0) {
31050
+ const target = greedyLeaves(sum(batch));
31051
+ if (!equals(target, batch)) {
31052
+ swaps.push(new Swap([...batch], target));
31053
+ }
31054
+ }
31055
+ return swaps;
31056
+ }
31057
+ function minimizeTransferSwap(inputLeaves, multiplicity = 1, maxLeavesPerSwap = 64) {
31058
+ const balance = sum(inputLeaves);
31059
+ const optimalLeaves = swapMinimizingLeaves(balance, multiplicity);
31060
+ const walletCounter = countOccurrences(inputLeaves);
31061
+ const optimalCounter = countOccurrences(optimalLeaves);
31062
+ const leavesToGive = subtractCounters(walletCounter, optimalCounter);
31063
+ const leavesToReceive = subtractCounters(optimalCounter, walletCounter);
31064
+ const leavesToGiveFlat = counterToFlatArray(leavesToGive);
31065
+ const leavesToReceiveFlat = counterToFlatArray(leavesToReceive);
31066
+ const swaps = [];
31067
+ let toGiveBatch = [];
31068
+ let toReceiveBatch = [];
31069
+ let give = [...leavesToGiveFlat];
31070
+ let receive = [...leavesToReceiveFlat];
31071
+ while (give.length > 0 || receive.length > 0) {
31072
+ if (sum(toGiveBatch) > sum(toReceiveBatch)) {
31073
+ if (receive.length === 0) break;
31074
+ toReceiveBatch.push(receive.shift());
31075
+ } else {
31076
+ if (give.length === 0) break;
31077
+ toGiveBatch.push(give.shift());
31078
+ }
31079
+ if (toGiveBatch.length > 0 && toReceiveBatch.length > 0 && sum(toGiveBatch) === sum(toReceiveBatch)) {
31080
+ if (toGiveBatch.length > maxLeavesPerSwap) {
31081
+ for (let i = 0; i < toGiveBatch.length; i += maxLeavesPerSwap) {
31082
+ const subset = toGiveBatch.slice(i, i + maxLeavesPerSwap);
31083
+ swaps.push(new Swap(subset, greedyLeaves(sum(subset))));
31084
+ }
31085
+ } else if (toReceiveBatch.length > maxLeavesPerSwap) {
31086
+ for (let cutoff = maxLeavesPerSwap; cutoff > 0; cutoff--) {
31087
+ const sumCut = sum(toReceiveBatch.slice(0, cutoff));
31088
+ const remainder = sum(toGiveBatch) - sumCut;
31089
+ const alternateBatch = [
31090
+ ...toReceiveBatch.slice(0, cutoff),
31091
+ ...greedyLeaves(remainder)
31092
+ ];
31093
+ if (alternateBatch.length <= maxLeavesPerSwap) {
31094
+ swaps.push(new Swap([...toGiveBatch], alternateBatch));
31095
+ break;
31096
+ }
31097
+ }
31098
+ } else {
31099
+ swaps.push(new Swap([...toGiveBatch], [...toReceiveBatch]));
31100
+ }
31101
+ toGiveBatch = [];
31102
+ toReceiveBatch = [];
31103
+ }
31104
+ }
31105
+ return swaps;
31106
+ }
31107
+ function shouldOptimize(inputLeaves, multiplicity = 1, maxLeavesPerSwap = 64) {
31108
+ if (multiplicity == 0) {
31109
+ const swaps = maximizeUnilateralExit(inputLeaves, maxLeavesPerSwap);
31110
+ const numInputs = sum(swaps.map((swap) => swap.inLeaves.length));
31111
+ const numOutputs = sum(swaps.map((swap) => swap.outLeaves.length));
31112
+ return numOutputs * 5 < numInputs;
31113
+ } else {
31114
+ const swaps = minimizeTransferSwap(
31115
+ inputLeaves,
31116
+ multiplicity,
31117
+ maxLeavesPerSwap
31118
+ );
31119
+ const inputCounter = countOccurrences(
31120
+ swaps.flatMap((swap) => swap.inLeaves)
31121
+ );
31122
+ const outputCounter = countOccurrences(
31123
+ swaps.flatMap((swap) => swap.outLeaves)
31124
+ );
31125
+ return Math.abs(inputCounter.size - outputCounter.size) > 1;
31126
+ }
31127
+ }
31128
+ function optimize(inputLeaves, multiplicity = 1, maxLeavesPerSwap = 64) {
31129
+ if (multiplicity == 0) {
31130
+ return maximizeUnilateralExit(inputLeaves, maxLeavesPerSwap);
31131
+ } else {
31132
+ return minimizeTransferSwap(inputLeaves, multiplicity, maxLeavesPerSwap);
31133
+ }
31134
+ }
31135
+
30961
31136
  // src/spark-wallet/spark-wallet.ts
30962
31137
  var SparkWallet = class extends import_eventemitter3.EventEmitter {
30963
31138
  config;
@@ -31062,8 +31237,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
31062
31237
  if (event.transfer.transfer && !(0, import_utils25.equalBytes)(senderIdentityPublicKey, receiverIdentityPublicKey)) {
31063
31238
  await this.claimTransfer({
31064
31239
  transfer: event.transfer.transfer,
31065
- emit: true,
31066
- optimize: true
31240
+ emit: true
31067
31241
  });
31068
31242
  }
31069
31243
  } else if (isDepositStreamEvent(event)) {
@@ -31354,73 +31528,84 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
31354
31528
  }
31355
31529
  return nodes;
31356
31530
  }
31357
- areLeavesInefficient() {
31358
- const totalAmount = this.getInternalBalance();
31359
- if (this.leaves.length <= 1) {
31360
- return false;
31531
+ async *optimizeLeaves(multiplicity = void 0) {
31532
+ const multiplicityValue = multiplicity ?? this.config.getOptimizationOptions().multiplicity ?? 0;
31533
+ if (multiplicityValue < 0) {
31534
+ throw new ValidationError("Multiplicity cannot be negative");
31535
+ } else if (multiplicityValue > 5) {
31536
+ throw new ValidationError("Multiplicity cannot be greater than 5");
31361
31537
  }
31362
- const nextLowerPowerOfTwo = 31 - Math.clz32(totalAmount);
31363
- let remainingAmount = totalAmount;
31364
- let optimalLeavesLength = 0;
31365
- for (let i = nextLowerPowerOfTwo; i >= 0; i--) {
31366
- const denomination = 2 ** i;
31367
- while (remainingAmount >= denomination) {
31368
- remainingAmount -= denomination;
31369
- optimalLeavesLength++;
31370
- }
31371
- }
31372
- return this.leaves.length > optimalLeavesLength * 5;
31373
- }
31374
- async optimizeLeaves() {
31375
- if (this.optimizationInProgress || !this.areLeavesInefficient()) {
31538
+ if (this.optimizationInProgress || !shouldOptimize(
31539
+ this.leaves.map((leaf) => leaf.value),
31540
+ multiplicityValue
31541
+ )) {
31376
31542
  return;
31377
31543
  }
31378
- await this.withLeaves(async () => {
31544
+ const controller = new AbortController();
31545
+ const release = await this.leavesMutex.acquire();
31546
+ try {
31379
31547
  this.optimizationInProgress = true;
31380
- try {
31381
- this.leaves = await this.getLeaves();
31382
- const swaps = maximizeUnilateralExit(
31383
- this.leaves.map((leaf) => leaf.value)
31384
- );
31385
- const valueToNodes = /* @__PURE__ */ new Map();
31386
- this.leaves.forEach((leaf) => {
31387
- if (!valueToNodes.has(leaf.value)) {
31388
- valueToNodes.set(leaf.value, []);
31389
- }
31390
- valueToNodes.get(leaf.value).push(leaf);
31391
- });
31392
- for (const swap of swaps) {
31393
- const leavesToSend = [];
31394
- for (const leafValue of swap.inLeaves) {
31395
- const nodes = valueToNodes.get(leafValue);
31396
- if (nodes && nodes.length > 0) {
31397
- const node = nodes.shift();
31398
- leavesToSend.push(node);
31399
- } else {
31400
- throw new InternalValidationError(
31401
- `No unused leaf with value ${leafValue} found in leaves`
31402
- );
31403
- }
31548
+ this.leaves = await this.getLeaves();
31549
+ const swaps = optimize(
31550
+ this.leaves.map((leaf) => leaf.value),
31551
+ multiplicityValue
31552
+ );
31553
+ if (swaps.length === 0) {
31554
+ return;
31555
+ }
31556
+ yield {
31557
+ step: 0,
31558
+ total: swaps.length,
31559
+ controller
31560
+ };
31561
+ const valueToNodes = /* @__PURE__ */ new Map();
31562
+ this.leaves.forEach((leaf) => {
31563
+ if (!valueToNodes.has(leaf.value)) {
31564
+ valueToNodes.set(leaf.value, []);
31565
+ }
31566
+ valueToNodes.get(leaf.value).push(leaf);
31567
+ });
31568
+ for (const swap of swaps) {
31569
+ if (controller.signal.aborted) {
31570
+ break;
31571
+ }
31572
+ const leavesToSend = [];
31573
+ for (const leafValue of swap.inLeaves) {
31574
+ const nodes = valueToNodes.get(leafValue);
31575
+ if (nodes && nodes.length > 0) {
31576
+ const node = nodes.shift();
31577
+ leavesToSend.push(node);
31578
+ } else {
31579
+ throw new InternalValidationError(
31580
+ `No unused leaf with value ${leafValue} found in leaves`
31581
+ );
31404
31582
  }
31405
- await this.requestLeavesSwap({
31406
- leaves: leavesToSend,
31407
- targetAmounts: swap.outLeaves
31408
- });
31409
31583
  }
31410
- this.leaves = await this.getLeaves();
31411
- } finally {
31412
- this.optimizationInProgress = false;
31584
+ await this.requestLeavesSwap({
31585
+ leaves: leavesToSend,
31586
+ targetAmounts: swap.outLeaves
31587
+ });
31588
+ yield {
31589
+ step: swaps.indexOf(swap) + 1,
31590
+ total: swaps.length,
31591
+ controller
31592
+ };
31413
31593
  }
31414
- });
31594
+ this.leaves = await this.getLeaves();
31595
+ } finally {
31596
+ this.optimizationInProgress = false;
31597
+ release();
31598
+ }
31415
31599
  }
31416
31600
  async syncWallet() {
31417
31601
  await this.syncTokenOutputs();
31418
31602
  let leaves = await this.getLeaves();
31419
31603
  leaves = await this.checkRenewLeaves(leaves);
31420
31604
  this.leaves = leaves;
31421
- this.optimizeLeaves().catch((e) => {
31422
- console.error("Failed to optimize leaves", e);
31423
- });
31605
+ if (this.config.getOptimizationOptions().auto) {
31606
+ for await (const _ of this.optimizeLeaves()) {
31607
+ }
31608
+ }
31424
31609
  }
31425
31610
  async withLeaves(operation) {
31426
31611
  const release = await this.leavesMutex.acquire();
@@ -32003,8 +32188,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
32003
32188
  }
32004
32189
  return await this.claimTransfer({
32005
32190
  transfer: incomingTransfer,
32006
- emit: false,
32007
- optimize: false
32191
+ emit: false
32008
32192
  });
32009
32193
  } catch (e) {
32010
32194
  console.error("[processSwapBatch] Error details:", {
@@ -33033,7 +33217,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
33033
33217
  transfer.id
33034
33218
  );
33035
33219
  if (pending) {
33036
- await this.claimTransfer({ transfer: pending, optimize: true });
33220
+ await this.claimTransfer({ transfer: pending });
33037
33221
  }
33038
33222
  }
33039
33223
  return {
@@ -33206,13 +33390,14 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
33206
33390
  return response.nodes;
33207
33391
  });
33208
33392
  }
33209
- async processClaimedTransferResults(result, transfer, emit, optimize) {
33393
+ async processClaimedTransferResults(result, transfer, emit) {
33210
33394
  result = await this.checkRenewLeaves(result);
33211
33395
  const existingIds = new Set(this.leaves.map((leaf) => leaf.id));
33212
33396
  const uniqueResults = result.filter((node) => !existingIds.has(node.id));
33213
33397
  this.leaves.push(...uniqueResults);
33214
- if (optimize && transfer.type !== 40 /* COUNTER_SWAP */) {
33215
- await this.optimizeLeaves();
33398
+ if (this.config.getOptimizationOptions().auto && transfer.type !== 40 /* COUNTER_SWAP */) {
33399
+ for await (const _ of this.optimizeLeaves()) {
33400
+ }
33216
33401
  }
33217
33402
  if (emit) {
33218
33403
  this.emit(
@@ -33231,8 +33416,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
33231
33416
  */
33232
33417
  async claimTransfer({
33233
33418
  transfer,
33234
- emit,
33235
- optimize
33419
+ emit
33236
33420
  }) {
33237
33421
  const onError = async (context) => {
33238
33422
  const error = context.error;
@@ -33277,12 +33461,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
33277
33461
  if (result.length === 0) {
33278
33462
  return [];
33279
33463
  }
33280
- return await this.processClaimedTransferResults(
33281
- result,
33282
- transfer,
33283
- emit,
33284
- optimize
33285
- );
33464
+ return await this.processClaimedTransferResults(result, transfer, emit);
33286
33465
  } catch (error) {
33287
33466
  console.warn(
33288
33467
  `Failed to claim transfer after all retries. Please try reinitializing your wallet in a few minutes. Transfer ID: ${transfer.id}`,
@@ -33315,7 +33494,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
33315
33494
  continue;
33316
33495
  }
33317
33496
  promises.push(
33318
- this.claimTransfer({ transfer, emit, optimize: true }).then(() => transfer.id).catch((error) => {
33497
+ this.claimTransfer({ transfer, emit }).then(() => transfer.id).catch((error) => {
33319
33498
  console.warn(`Failed to claim transfer ${transfer.id}:`, error);
33320
33499
  return null;
33321
33500
  })
@@ -35779,6 +35958,7 @@ setCrypto(cryptoImpl2);
35779
35958
  getTxFromRawTxHex,
35780
35959
  getTxId,
35781
35960
  getTxIdNoReverse,
35961
+ hash160,
35782
35962
  initializeTracerEnv,
35783
35963
  isEphemeralAnchorOutput,
35784
35964
  isLegacySparkAddress,
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- export { A as AuthenticationError, C as ConfigurationError, I as InternalValidationError, N as NetworkError, a as NotImplementedError, R as RPCError, S as SparkSDKError, T as TokenTransactionService, V as ValidationError } from './token-transactions-CV8QD3I7.cjs';
2
- export { C as BaseConnectionManager, B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, b as ConfigOptions, A as CreateLightningInvoiceParams, D as DecodedSparkAddressData, K as DepositParams, G as FulfillSparkInvoiceResponse, J as GroupSparkInvoicesResult, V as InitWalletResponse, I as InvalidInvoice, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, P as PayLightningInvoiceParams, R as RawTokenIdentifierHex, c as SparkAddressData, S as SparkAddressFormat, Y as SparkWalletEvent, Z as SparkWalletEventType, _ as SparkWalletEvents, X as SparkWalletProps, M as TokenBalanceMap, H as TokenInvoice, Q as TokenMetadataMap, O as TokenOutputsMap, T as TransferParams, F as TransferWithInvoiceOutcome, E as TransferWithInvoiceParams, U as UserTokenMetadata, a as WalletConfig, W as WalletConfigService, 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 } from './wallet-config-DQw5llqA.cjs';
3
- export { ah as BroadcastConfig, ai as BroadcastResult, R as DEFAULT_FEE_SATS, O as DIRECT_HTLC_TIMELOCK_OFFSET, M as DIRECT_TIMELOCK_OFFSET, af as FeeBumpTxChain, ae as FeeBumpTxPackage, ad as FeeRate, N as HTLC_TIMELOCK_OFFSET, P as INITIAL_SEQUENCE, ao as LOGGER_NAMES, ab as LeafInfo, ap as LoggerName, aq as SparkSdkLogger, Q as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, ag as TxChain, ac as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a5 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, am as constructFeeBumpTx, al as constructUnilateralExitFeeBumpPackages, ak as constructUnilateralExitTxs, a2 as createConnectorRefundTxs, a0 as createCurrentTimelockRefundTxs, X as createDecrementedTimelockNodeTx, $ as createDecrementedTimelockRefundTxs, W as createInitialTimelockNodeTx, _ as createInitialTimelockRefundTxs, U as createRootNodeTx, F as createSigningCommitment, B as createSigningNonce, a1 as createTestUnilateralRefundTxs, Y as createTestUnilateralTimelockNodeTx, V as createZeroTimelockNodeTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a8 as doesLeafNeedRefresh, a7 as doesTxnNeedRenewed, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, a3 as getCurrentTimelock, aa as getEphemeralAnchorOutput, w as getLatestDepositTxId, Z as getNextHTLCTransactionSequence, a9 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, an as getSparkAddressFromTaproot, a4 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, aj as isEphemeralAnchorOutput, x as isTxBroadcast, a6 as isZeroTimelock, u as lastKeyWithTarget, S as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-CXhvuqJJ.cjs';
1
+ export { A as AuthenticationError, C as ConfigurationError, I as InternalValidationError, N as NetworkError, a as NotImplementedError, R as RPCError, S as SparkSDKError, T as TokenTransactionService, V as ValidationError } from './token-transactions-Db8mkjnU.cjs';
2
+ export { C as BaseConnectionManager, B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, b as ConfigOptions, A as CreateLightningInvoiceParams, D as DecodedSparkAddressData, K as DepositParams, G as FulfillSparkInvoiceResponse, J as GroupSparkInvoicesResult, V as InitWalletResponse, I as InvalidInvoice, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, P as PayLightningInvoiceParams, R as RawTokenIdentifierHex, c as SparkAddressData, S as SparkAddressFormat, Y as SparkWalletEvent, Z as SparkWalletEventType, _ as SparkWalletEvents, X as SparkWalletProps, M as TokenBalanceMap, H as TokenInvoice, Q as TokenMetadataMap, O as TokenOutputsMap, T as TransferParams, F as TransferWithInvoiceOutcome, E as TransferWithInvoiceParams, U as UserTokenMetadata, a as WalletConfig, W as WalletConfigService, 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 } from './wallet-config-CuZKNo9S.cjs';
3
+ export { ah as BroadcastConfig, ai as BroadcastResult, R as DEFAULT_FEE_SATS, O as DIRECT_HTLC_TIMELOCK_OFFSET, M as DIRECT_TIMELOCK_OFFSET, af as FeeBumpTxChain, ae as FeeBumpTxPackage, ad as FeeRate, N as HTLC_TIMELOCK_OFFSET, P as INITIAL_SEQUENCE, ap as LOGGER_NAMES, ab as LeafInfo, aq as LoggerName, ar as SparkSdkLogger, Q as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, ag as TxChain, ac as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a5 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, an as constructFeeBumpTx, al as constructUnilateralExitFeeBumpPackages, ak as constructUnilateralExitTxs, a2 as createConnectorRefundTxs, a0 as createCurrentTimelockRefundTxs, X as createDecrementedTimelockNodeTx, $ as createDecrementedTimelockRefundTxs, W as createInitialTimelockNodeTx, _ as createInitialTimelockRefundTxs, U as createRootNodeTx, F as createSigningCommitment, B as createSigningNonce, a1 as createTestUnilateralRefundTxs, Y as createTestUnilateralTimelockNodeTx, V as createZeroTimelockNodeTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a8 as doesLeafNeedRefresh, a7 as doesTxnNeedRenewed, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, a3 as getCurrentTimelock, aa as getEphemeralAnchorOutput, w as getLatestDepositTxId, Z as getNextHTLCTransactionSequence, a9 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, ao as getSparkAddressFromTaproot, a4 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, am as hash160, aj as isEphemeralAnchorOutput, x as isTxBroadcast, a6 as isZeroTimelock, u as lastKeyWithTarget, S as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-D3IfXfHG.cjs';
4
4
  export { A as AggregateFrostParams, D as DefaultSparkSigner, p as DerivedHDKey, l as KeyDerivation, K as KeyDerivationType, q as KeyPair, n as SignFrostParams, k as SigningCommitment, i as SigningCommitmentWithOptionalNonce, j as SigningNonce, S as SparkSigner, o as SplitSecretWithProofsParams, T as TaprootOutputKeysGenerator, a as TaprootSparkSigner, U as UnsafeStatelessSparkSigner, 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-BIqiUNy4.cjs';
5
5
  export { I as IKeyPackage } from './types-B3hMoTYO.cjs';
6
- export { C as ConnectionManager, S as SparkWallet, i as initializeTracerEnv } from './spark-wallet.browser-CbYo8A_U.cjs';
6
+ export { C as ConnectionManager, S as SparkWallet, i as initializeTracerEnv } from './spark-wallet.browser-Ck9No4Ks.cjs';
7
7
  import './spark-DOpheE8_.cjs';
8
8
  import '@bufbuild/protobuf/wire';
9
9
  import 'nice-grpc-common';
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- export { A as AuthenticationError, C as ConfigurationError, I as InternalValidationError, N as NetworkError, a as NotImplementedError, R as RPCError, S as SparkSDKError, T as TokenTransactionService, V as ValidationError } from './token-transactions-Bu023ztN.js';
2
- export { C as BaseConnectionManager, B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, b as ConfigOptions, A as CreateLightningInvoiceParams, D as DecodedSparkAddressData, K as DepositParams, G as FulfillSparkInvoiceResponse, J as GroupSparkInvoicesResult, V as InitWalletResponse, I as InvalidInvoice, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, P as PayLightningInvoiceParams, R as RawTokenIdentifierHex, c as SparkAddressData, S as SparkAddressFormat, Y as SparkWalletEvent, Z as SparkWalletEventType, _ as SparkWalletEvents, X as SparkWalletProps, M as TokenBalanceMap, H as TokenInvoice, Q as TokenMetadataMap, O as TokenOutputsMap, T as TransferParams, F as TransferWithInvoiceOutcome, E as TransferWithInvoiceParams, U as UserTokenMetadata, a as WalletConfig, W as WalletConfigService, 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 } from './wallet-config-Bmk2eAn8.js';
3
- export { ah as BroadcastConfig, ai as BroadcastResult, R as DEFAULT_FEE_SATS, O as DIRECT_HTLC_TIMELOCK_OFFSET, M as DIRECT_TIMELOCK_OFFSET, af as FeeBumpTxChain, ae as FeeBumpTxPackage, ad as FeeRate, N as HTLC_TIMELOCK_OFFSET, P as INITIAL_SEQUENCE, ao as LOGGER_NAMES, ab as LeafInfo, ap as LoggerName, aq as SparkSdkLogger, Q as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, ag as TxChain, ac as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a5 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, am as constructFeeBumpTx, al as constructUnilateralExitFeeBumpPackages, ak as constructUnilateralExitTxs, a2 as createConnectorRefundTxs, a0 as createCurrentTimelockRefundTxs, X as createDecrementedTimelockNodeTx, $ as createDecrementedTimelockRefundTxs, W as createInitialTimelockNodeTx, _ as createInitialTimelockRefundTxs, U as createRootNodeTx, F as createSigningCommitment, B as createSigningNonce, a1 as createTestUnilateralRefundTxs, Y as createTestUnilateralTimelockNodeTx, V as createZeroTimelockNodeTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a8 as doesLeafNeedRefresh, a7 as doesTxnNeedRenewed, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, a3 as getCurrentTimelock, aa as getEphemeralAnchorOutput, w as getLatestDepositTxId, Z as getNextHTLCTransactionSequence, a9 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, an as getSparkAddressFromTaproot, a4 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, aj as isEphemeralAnchorOutput, x as isTxBroadcast, a6 as isZeroTimelock, u as lastKeyWithTarget, S as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-DDeMLsVN.js';
1
+ export { A as AuthenticationError, C as ConfigurationError, I as InternalValidationError, N as NetworkError, a as NotImplementedError, R as RPCError, S as SparkSDKError, T as TokenTransactionService, V as ValidationError } from './token-transactions-DoMcrxXQ.js';
2
+ export { C as BaseConnectionManager, B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, b as ConfigOptions, A as CreateLightningInvoiceParams, D as DecodedSparkAddressData, K as DepositParams, G as FulfillSparkInvoiceResponse, J as GroupSparkInvoicesResult, V as InitWalletResponse, I as InvalidInvoice, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, P as PayLightningInvoiceParams, R as RawTokenIdentifierHex, c as SparkAddressData, S as SparkAddressFormat, Y as SparkWalletEvent, Z as SparkWalletEventType, _ as SparkWalletEvents, X as SparkWalletProps, M as TokenBalanceMap, H as TokenInvoice, Q as TokenMetadataMap, O as TokenOutputsMap, T as TransferParams, F as TransferWithInvoiceOutcome, E as TransferWithInvoiceParams, U as UserTokenMetadata, a as WalletConfig, W as WalletConfigService, 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 } from './wallet-config-Bg3kWltL.js';
3
+ export { ah as BroadcastConfig, ai as BroadcastResult, R as DEFAULT_FEE_SATS, O as DIRECT_HTLC_TIMELOCK_OFFSET, M as DIRECT_TIMELOCK_OFFSET, af as FeeBumpTxChain, ae as FeeBumpTxPackage, ad as FeeRate, N as HTLC_TIMELOCK_OFFSET, P as INITIAL_SEQUENCE, ap as LOGGER_NAMES, ab as LeafInfo, aq as LoggerName, ar as SparkSdkLogger, Q as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, ag as TxChain, ac as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a5 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, an as constructFeeBumpTx, al as constructUnilateralExitFeeBumpPackages, ak as constructUnilateralExitTxs, a2 as createConnectorRefundTxs, a0 as createCurrentTimelockRefundTxs, X as createDecrementedTimelockNodeTx, $ as createDecrementedTimelockRefundTxs, W as createInitialTimelockNodeTx, _ as createInitialTimelockRefundTxs, U as createRootNodeTx, F as createSigningCommitment, B as createSigningNonce, a1 as createTestUnilateralRefundTxs, Y as createTestUnilateralTimelockNodeTx, V as createZeroTimelockNodeTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a8 as doesLeafNeedRefresh, a7 as doesTxnNeedRenewed, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, a3 as getCurrentTimelock, aa as getEphemeralAnchorOutput, w as getLatestDepositTxId, Z as getNextHTLCTransactionSequence, a9 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, ao as getSparkAddressFromTaproot, a4 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, am as hash160, aj as isEphemeralAnchorOutput, x as isTxBroadcast, a6 as isZeroTimelock, u as lastKeyWithTarget, S as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-BNGm6dBp.js';
4
4
  export { A as AggregateFrostParams, D as DefaultSparkSigner, p as DerivedHDKey, l as KeyDerivation, K as KeyDerivationType, q as KeyPair, n as SignFrostParams, k as SigningCommitment, i as SigningCommitmentWithOptionalNonce, j as SigningNonce, S as SparkSigner, o as SplitSecretWithProofsParams, T as TaprootOutputKeysGenerator, a as TaprootSparkSigner, U as UnsafeStatelessSparkSigner, 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-BaQf-5gD.js';
5
5
  export { I as IKeyPackage } from './types-B3hMoTYO.js';
6
- export { C as ConnectionManager, S as SparkWallet, i as initializeTracerEnv } from './spark-wallet.browser-Cz8c4kOW.js';
6
+ export { C as ConnectionManager, S as SparkWallet, i as initializeTracerEnv } from './spark-wallet.browser-B2rGwjuM.js';
7
7
  import './spark-DOpheE8_.js';
8
8
  import '@bufbuild/protobuf/wire';
9
9
  import 'nice-grpc-common';