@buildonspark/spark-sdk 0.1.41 → 0.1.43

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 (156) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/android/src/main/jniLibs/arm64-v8a/libuniffi_spark_frost.so +0 -0
  3. package/android/src/main/jniLibs/armeabi-v7a/libuniffi_spark_frost.so +0 -0
  4. package/android/src/main/jniLibs/x86/libuniffi_spark_frost.so +0 -0
  5. package/android/src/main/jniLibs/x86_64/libuniffi_spark_frost.so +0 -0
  6. package/dist/LightningSendFeeEstimateInput-BgOhEAI-.d.cts +10 -0
  7. package/dist/LightningSendFeeEstimateInput-BgOhEAI-.d.ts +10 -0
  8. package/dist/{RequestLightningSendInput-mXUWn_cp.d.ts → RequestLightningSendInput-D7fZdT4A.d.ts} +35 -16
  9. package/dist/{RequestLightningSendInput-DXcLoiCe.d.cts → RequestLightningSendInput-Na1mHdWg.d.cts} +35 -16
  10. package/dist/address/index.cjs +38 -7
  11. package/dist/address/index.d.cts +2 -2
  12. package/dist/address/index.d.ts +2 -2
  13. package/dist/address/index.js +3 -3
  14. package/dist/{chunk-ATEHMLKP.js → chunk-6AFUC5M2.js} +1 -1
  15. package/dist/{chunk-ZXDE2XMU.js → chunk-BUTZWYBW.js} +9 -6
  16. package/dist/{chunk-7EFSUADA.js → chunk-DOA6QXYQ.js} +1 -0
  17. package/dist/{chunk-J5W5Q2ZP.js → chunk-DQYKQJRZ.js} +291 -7
  18. package/dist/{chunk-TWF35O6M.js → chunk-GSI4OLXZ.js} +32 -1
  19. package/dist/{chunk-2ZXXLPG2.js → chunk-GYQR4B4P.js} +5 -4
  20. package/dist/{chunk-ROKY5KS4.js → chunk-HRQRRDSS.js} +53 -15
  21. package/dist/{chunk-YEZDPUFY.js → chunk-IRW5TWMH.js} +8 -8
  22. package/dist/{chunk-7VMYMQLF.js → chunk-NSJF5F5O.js} +1 -1
  23. package/dist/{chunk-TM4TOEOX.js → chunk-O4RYNJNB.js} +3 -3
  24. package/dist/{chunk-MGPRLH6Q.js → chunk-QNNSEJ4P.js} +1 -1
  25. package/dist/{chunk-UKT6OFLO.js → chunk-TIUBYNN5.js} +13 -7
  26. package/dist/{chunk-6YVPOQ2A.js → chunk-TOSP3INR.js} +235 -143
  27. package/dist/chunk-VFJQNBFX.js +21 -0
  28. package/dist/{chunk-KKSU7OZO.js → chunk-WWOTVNPP.js} +195 -67
  29. package/dist/{chunk-HK6LPV6Z.js → chunk-Z5HIAYFT.js} +1 -1
  30. package/dist/graphql/objects/index.cjs +229 -135
  31. package/dist/graphql/objects/index.d.cts +54 -9
  32. package/dist/graphql/objects/index.d.ts +54 -9
  33. package/dist/graphql/objects/index.js +3 -3
  34. package/dist/{index-OSDtPMmC.d.ts → index-7RYRH5wc.d.ts} +10 -8
  35. package/dist/{index-CFh4uWzi.d.cts → index-BJOc8Ur-.d.cts} +10 -8
  36. package/dist/index.cjs +790 -315
  37. package/dist/index.d.cts +8 -7
  38. package/dist/index.d.ts +8 -7
  39. package/dist/index.js +26 -26
  40. package/dist/index.node.cjs +790 -315
  41. package/dist/index.node.d.cts +9 -8
  42. package/dist/index.node.d.ts +9 -8
  43. package/dist/index.node.js +26 -26
  44. package/dist/native/index.cjs +812 -332
  45. package/dist/native/index.d.cts +53 -18
  46. package/dist/native/index.d.ts +53 -18
  47. package/dist/native/index.js +659 -181
  48. package/dist/{network-BiwBmoOg.d.cts → network-D5lKssVl.d.cts} +1 -1
  49. package/dist/{network-BF2GYPye.d.ts → network-xkBSpaTn.d.ts} +1 -1
  50. package/dist/proto/lrc20.d.cts +1 -1
  51. package/dist/proto/lrc20.d.ts +1 -1
  52. package/dist/proto/spark.d.cts +1 -1
  53. package/dist/proto/spark.d.ts +1 -1
  54. package/dist/proto/spark_token.d.cts +1 -1
  55. package/dist/proto/spark_token.d.ts +1 -1
  56. package/dist/{sdk-types-CfhdFnsA.d.cts → sdk-types-B-q9py_P.d.cts} +1 -1
  57. package/dist/{sdk-types-MnQrHolg.d.ts → sdk-types-BPoPgzda.d.ts} +1 -1
  58. package/dist/services/config.cjs +118 -69
  59. package/dist/services/config.d.cts +6 -4
  60. package/dist/services/config.d.ts +6 -4
  61. package/dist/services/config.js +9 -9
  62. package/dist/services/connection.cjs +95 -15
  63. package/dist/services/connection.d.cts +6 -4
  64. package/dist/services/connection.d.ts +6 -4
  65. package/dist/services/connection.js +3 -3
  66. package/dist/services/index.cjs +487 -117
  67. package/dist/services/index.d.cts +5 -4
  68. package/dist/services/index.d.ts +5 -4
  69. package/dist/services/index.js +19 -19
  70. package/dist/services/lrc-connection.cjs +50 -7
  71. package/dist/services/lrc-connection.d.cts +5 -4
  72. package/dist/services/lrc-connection.d.ts +5 -4
  73. package/dist/services/lrc-connection.js +3 -3
  74. package/dist/services/token-transactions.cjs +351 -36
  75. package/dist/services/token-transactions.d.cts +5 -4
  76. package/dist/services/token-transactions.d.ts +5 -4
  77. package/dist/services/token-transactions.js +6 -6
  78. package/dist/services/wallet-config.cjs +1 -0
  79. package/dist/services/wallet-config.d.cts +6 -4
  80. package/dist/services/wallet-config.d.ts +6 -4
  81. package/dist/services/wallet-config.js +1 -1
  82. package/dist/signer/signer.cjs +117 -64
  83. package/dist/signer/signer.d.cts +4 -3
  84. package/dist/signer/signer.d.ts +4 -3
  85. package/dist/signer/signer.js +15 -7
  86. package/dist/{signer-CylxIujU.d.ts → signer-IO3oMRNj.d.cts} +2 -1
  87. package/dist/{signer-BhLS7SYR.d.cts → signer-wqesWifN.d.ts} +2 -1
  88. package/dist/{spark-DjR1b3TC.d.cts → spark-CDm4gqS6.d.cts} +1 -1
  89. package/dist/{spark-DjR1b3TC.d.ts → spark-CDm4gqS6.d.ts} +1 -1
  90. package/dist/types/index.cjs +282 -188
  91. package/dist/types/index.d.cts +7 -6
  92. package/dist/types/index.d.ts +7 -6
  93. package/dist/types/index.js +3 -3
  94. package/dist/utils/index.cjs +90 -58
  95. package/dist/utils/index.d.cts +6 -5
  96. package/dist/utils/index.d.ts +6 -5
  97. package/dist/utils/index.js +16 -16
  98. package/ios/spark_frostFFI.xcframework/ios-arm64/SparkFrost +0 -0
  99. package/ios/spark_frostFFI.xcframework/ios-arm64/spark_frostFFI.framework/spark_frostFFI +0 -0
  100. package/ios/spark_frostFFI.xcframework/ios-arm64_x86_64-simulator/SparkFrost +0 -0
  101. package/ios/spark_frostFFI.xcframework/ios-arm64_x86_64-simulator/spark_frostFFI.framework/spark_frostFFI +0 -0
  102. package/ios/spark_frostFFI.xcframework/macos-arm64_x86_64/spark_frostFFI.framework/spark_frostFFI +0 -0
  103. package/package.json +4 -4
  104. package/src/constants.ts +21 -0
  105. package/src/errors/base.ts +43 -1
  106. package/src/graphql/client.ts +4 -0
  107. package/src/graphql/mutations/RequestLightningSend.ts +2 -0
  108. package/src/graphql/objects/ClaimStaticDepositInput.ts +1 -1
  109. package/src/graphql/objects/ClaimStaticDepositStatus.ts +4 -2
  110. package/src/graphql/objects/Connection.ts +7 -7
  111. package/src/graphql/objects/CoopExitFeeEstimate.ts +1 -1
  112. package/src/graphql/objects/CoopExitFeeQuote.ts +202 -0
  113. package/src/graphql/objects/CoopExitFeeQuoteInput.ts +41 -0
  114. package/src/graphql/objects/CoopExitFeeQuoteOutput.ts +45 -0
  115. package/src/graphql/objects/CoopExitRequest.ts +21 -0
  116. package/src/graphql/objects/CurrencyUnit.ts +26 -28
  117. package/src/graphql/objects/Entity.ts +84 -0
  118. package/src/graphql/objects/Invoice.ts +2 -2
  119. package/src/graphql/objects/Leaf.ts +1 -1
  120. package/src/graphql/objects/LeavesSwapFeeEstimateOutput.ts +1 -1
  121. package/src/graphql/objects/LeavesSwapRequest.ts +6 -0
  122. package/src/graphql/objects/LightningReceiveRequest.ts +11 -0
  123. package/src/graphql/objects/LightningSendFeeEstimateInput.ts +8 -0
  124. package/src/graphql/objects/LightningSendFeeEstimateOutput.ts +1 -1
  125. package/src/graphql/objects/LightningSendRequest.ts +3 -0
  126. package/src/graphql/objects/RequestCoopExitInput.ts +8 -0
  127. package/src/graphql/objects/RequestLeavesSwapInput.ts +5 -1
  128. package/src/graphql/objects/RequestLightningReceiveInput.ts +9 -2
  129. package/src/graphql/objects/RequestLightningSendInput.ts +8 -0
  130. package/src/graphql/objects/SparkCoopExitRequestStatus.ts +2 -0
  131. package/src/graphql/objects/SparkUserRequestType.ts +2 -0
  132. package/src/graphql/objects/SparkWalletUser.ts +20 -0
  133. package/src/graphql/objects/UserRequest.ts +32 -0
  134. package/src/graphql/objects/VerifyChallengeInput.ts +1 -1
  135. package/src/graphql/objects/index.ts +12 -3
  136. package/src/graphql/queries/LightningSendFeeEstimate.ts +2 -0
  137. package/src/logger.ts +3 -0
  138. package/src/native/index.ts +1 -0
  139. package/src/services/config.ts +4 -0
  140. package/src/services/connection.ts +68 -29
  141. package/src/services/coop-exit.ts +1 -1
  142. package/src/services/lightning.ts +25 -1
  143. package/src/services/lrc-connection.ts +3 -3
  144. package/src/services/token-transactions.ts +6 -2
  145. package/src/services/wallet-config.ts +2 -0
  146. package/src/signer/signer.ts +4 -1
  147. package/src/spark-wallet/spark-wallet.ts +51 -15
  148. package/src/spark-wallet/types.ts +1 -0
  149. package/src/tests/errors.test.ts +58 -0
  150. package/src/tests/integration/lightning.test.ts +184 -0
  151. package/src/tests/integration/ssp/static_deposit.test.ts +1 -2
  152. package/src/tests/tokens.test.ts +52 -3
  153. package/src/utils/token-hashing.ts +335 -1
  154. package/dist/LightningSendFeeEstimateInput-CJvPnCSB.d.cts +0 -5
  155. package/dist/LightningSendFeeEstimateInput-CJvPnCSB.d.ts +0 -5
  156. package/dist/chunk-HKAKEKCE.js +0 -8
package/dist/index.cjs CHANGED
@@ -1374,6 +1374,7 @@ init_buffer();
1374
1374
 
1375
1375
  // src/errors/base.ts
1376
1376
  init_buffer();
1377
+ var import_utils = require("@noble/hashes/utils");
1377
1378
  var SparkSDKError = class extends Error {
1378
1379
  context;
1379
1380
  originalError;
@@ -1405,12 +1406,42 @@ var SparkSDKError = class extends Error {
1405
1406
  }
1406
1407
  };
1407
1408
  function getMessage(message, context = {}, originalError) {
1408
- const contextStr = Object.entries(context).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ");
1409
+ const contextStr = Object.entries(context).map(([key, value]) => `${key}: ${safeStringify(value)}`).join(", ");
1409
1410
  const originalErrorStr = originalError ? `
1410
1411
  Original Error: ${originalError.message}` : "";
1411
1412
  return `SparkSDKError: ${message}${contextStr ? `
1412
1413
  Context: ${contextStr}` : ""}${originalErrorStr}`;
1413
1414
  }
1415
+ function safeStringify(value) {
1416
+ const replacer = (_, v) => {
1417
+ if (typeof v === "bigint") {
1418
+ return v.toString();
1419
+ }
1420
+ if (v instanceof Uint8Array) {
1421
+ return formatUint8Array(v);
1422
+ }
1423
+ return v;
1424
+ };
1425
+ if (typeof value === "bigint") {
1426
+ return `"${value.toString()}"`;
1427
+ }
1428
+ if (value instanceof Uint8Array) {
1429
+ return `"${formatUint8Array(value)}"`;
1430
+ }
1431
+ try {
1432
+ const result = JSON.stringify(value, replacer);
1433
+ return result === void 0 ? String(value) : result;
1434
+ } catch {
1435
+ try {
1436
+ return String(value);
1437
+ } catch {
1438
+ return "[Unserializable]";
1439
+ }
1440
+ }
1441
+ }
1442
+ function formatUint8Array(arr) {
1443
+ return `Uint8Array(0x${(0, import_utils.bytesToHex)(arr)})`;
1444
+ }
1414
1445
 
1415
1446
  // src/errors/types.ts
1416
1447
  init_buffer();
@@ -1452,8 +1483,8 @@ var NotImplementedError = class extends SparkSDKError {
1452
1483
 
1453
1484
  // src/spark-wallet/spark-wallet.ts
1454
1485
  init_buffer();
1455
- var import_core12 = require("@lightsparkdev/core");
1456
- var import_utils22 = require("@noble/curves/abstract/utils");
1486
+ var import_core14 = require("@lightsparkdev/core");
1487
+ var import_utils23 = require("@noble/curves/abstract/utils");
1457
1488
  var import_secp256k116 = require("@noble/curves/secp256k1");
1458
1489
  var import_bip392 = require("@scure/bip39");
1459
1490
  var import_english2 = require("@scure/bip39/wordlists/english");
@@ -1572,11 +1603,23 @@ var CurrencyAmountToJson = (obj) => {
1572
1603
  };
1573
1604
  };
1574
1605
 
1606
+ // src/graphql/objects/ExitSpeed.ts
1607
+ init_buffer();
1608
+ var ExitSpeed = /* @__PURE__ */ ((ExitSpeed2) => {
1609
+ ExitSpeed2["FUTURE_VALUE"] = "FUTURE_VALUE";
1610
+ ExitSpeed2["FAST"] = "FAST";
1611
+ ExitSpeed2["MEDIUM"] = "MEDIUM";
1612
+ ExitSpeed2["SLOW"] = "SLOW";
1613
+ return ExitSpeed2;
1614
+ })(ExitSpeed || {});
1615
+ var ExitSpeed_default = ExitSpeed;
1616
+
1575
1617
  // src/graphql/objects/SparkCoopExitRequestStatus.ts
1576
1618
  init_buffer();
1577
1619
  var SparkCoopExitRequestStatus = /* @__PURE__ */ ((SparkCoopExitRequestStatus2) => {
1578
1620
  SparkCoopExitRequestStatus2["FUTURE_VALUE"] = "FUTURE_VALUE";
1579
1621
  SparkCoopExitRequestStatus2["INITIATED"] = "INITIATED";
1622
+ SparkCoopExitRequestStatus2["INBOUND_TRANSFER_CHECKED"] = "INBOUND_TRANSFER_CHECKED";
1580
1623
  SparkCoopExitRequestStatus2["TX_SIGNED"] = "TX_SIGNED";
1581
1624
  SparkCoopExitRequestStatus2["TX_BROADCASTED"] = "TX_BROADCASTED";
1582
1625
  SparkCoopExitRequestStatus2["WAITING_ON_TX_CONFIRMATIONS"] = "WAITING_ON_TX_CONFIRMATIONS";
@@ -1761,6 +1804,8 @@ var CoopExitRequestFromJson = (obj) => {
1761
1804
  rawCoopExitTransaction: obj["coop_exit_request_raw_coop_exit_transaction"],
1762
1805
  coopExitTxid: obj["coop_exit_request_coop_exit_txid"],
1763
1806
  typename: "CoopExitRequest",
1807
+ feeQuoteId: obj["coop_exit_request_fee_quote"]?.id ?? void 0,
1808
+ exitSpeed: !!obj["coop_exit_request_exit_speed"] ? ExitSpeed_default[obj["coop_exit_request_exit_speed"]] ?? ExitSpeed_default.FUTURE_VALUE : null,
1764
1809
  transfer: !!obj["coop_exit_request_transfer"] ? TransferFromJson(obj["coop_exit_request_transfer"]) : void 0
1765
1810
  };
1766
1811
  };
@@ -1787,6 +1832,10 @@ fragment CoopExitRequestFragment on CoopExitRequest {
1787
1832
  currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
1788
1833
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1789
1834
  }
1835
+ coop_exit_request_fee_quote: fee_quote {
1836
+ id
1837
+ }
1838
+ coop_exit_request_exit_speed: exit_speed
1790
1839
  coop_exit_request_status: status
1791
1840
  coop_exit_request_expires_at: expires_at
1792
1841
  coop_exit_request_raw_connector_transaction: raw_connector_transaction
@@ -1803,6 +1852,9 @@ fragment CoopExitRequestFragment on CoopExitRequest {
1803
1852
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1804
1853
  }
1805
1854
  transfer_spark_id: spark_id
1855
+ transfer_user_request: user_request {
1856
+ id
1857
+ }
1806
1858
  }
1807
1859
  }`;
1808
1860
 
@@ -1927,6 +1979,9 @@ fragment LeavesSwapRequestFragment on LeavesSwapRequest {
1927
1979
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1928
1980
  }
1929
1981
  transfer_spark_id: spark_id
1982
+ transfer_user_request: user_request {
1983
+ id
1984
+ }
1930
1985
  }
1931
1986
  leaves_swap_request_outbound_transfer: outbound_transfer {
1932
1987
  __typename
@@ -1939,6 +1994,9 @@ fragment LeavesSwapRequestFragment on LeavesSwapRequest {
1939
1994
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1940
1995
  }
1941
1996
  transfer_spark_id: spark_id
1997
+ transfer_user_request: user_request {
1998
+ id
1999
+ }
1942
2000
  }
1943
2001
  leaves_swap_request_expires_at: expires_at
1944
2002
  leaves_swap_request_swap_leaves: swap_leaves {
@@ -2072,7 +2130,8 @@ var LightningReceiveRequestFromJson = (obj) => {
2072
2130
  status: LightningReceiveRequestStatus_default[obj["lightning_receive_request_status"]] ?? LightningReceiveRequestStatus_default.FUTURE_VALUE,
2073
2131
  typename: "LightningReceiveRequest",
2074
2132
  transfer: !!obj["lightning_receive_request_transfer"] ? TransferFromJson(obj["lightning_receive_request_transfer"]) : void 0,
2075
- paymentPreimage: obj["lightning_receive_request_payment_preimage"]
2133
+ paymentPreimage: obj["lightning_receive_request_payment_preimage"],
2134
+ receiverIdentityPublicKey: obj["lightning_receive_request_receiver_identity_public_key"]
2076
2135
  };
2077
2136
  };
2078
2137
  var FRAGMENT6 = `
@@ -2111,8 +2170,12 @@ fragment LightningReceiveRequestFragment on LightningReceiveRequest {
2111
2170
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2112
2171
  }
2113
2172
  transfer_spark_id: spark_id
2173
+ transfer_user_request: user_request {
2174
+ id
2175
+ }
2114
2176
  }
2115
2177
  lightning_receive_request_payment_preimage: payment_preimage
2178
+ lightning_receive_request_receiver_identity_public_key: receiver_identity_public_key
2116
2179
  }`;
2117
2180
 
2118
2181
  // src/graphql/mutations/RequestLightningReceive.ts
@@ -2214,6 +2277,9 @@ fragment LightningSendRequestFragment on LightningSendRequest {
2214
2277
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2215
2278
  }
2216
2279
  transfer_spark_id: spark_id
2280
+ transfer_user_request: user_request {
2281
+ id
2282
+ }
2217
2283
  }
2218
2284
  lightning_send_request_payment_preimage: payment_preimage
2219
2285
  }`;
@@ -2223,10 +2289,12 @@ var RequestLightningSend = `
2223
2289
  mutation RequestLightningSend(
2224
2290
  $encoded_invoice: String!
2225
2291
  $idempotency_key: String!
2292
+ $amount_sats: Long
2226
2293
  ) {
2227
2294
  request_lightning_send(input: {
2228
2295
  encoded_invoice: $encoded_invoice
2229
2296
  idempotency_key: $idempotency_key
2297
+ amount_sats: $amount_sats
2230
2298
  }) {
2231
2299
  request {
2232
2300
  ...LightningSendRequestFragment
@@ -2517,10 +2585,12 @@ init_buffer();
2517
2585
  var LightningSendFeeEstimate = `
2518
2586
  query LightningSendFeeEstimate(
2519
2587
  $encoded_invoice: String!
2588
+ $amount_sats: Long
2520
2589
  ) {
2521
2590
  lightning_send_fee_estimate(
2522
2591
  input: {
2523
2592
  encoded_invoice: $encoded_invoice
2593
+ amount_sats: $amount_sats
2524
2594
  }
2525
2595
  ) {
2526
2596
  ...LightningSendFeeEstimateOutputFragment
@@ -2604,6 +2674,10 @@ fragment UserRequestFragment on UserRequest {
2604
2674
  currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
2605
2675
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2606
2676
  }
2677
+ coop_exit_request_fee_quote: fee_quote {
2678
+ id
2679
+ }
2680
+ coop_exit_request_exit_speed: exit_speed
2607
2681
  coop_exit_request_status: status
2608
2682
  coop_exit_request_expires_at: expires_at
2609
2683
  coop_exit_request_raw_connector_transaction: raw_connector_transaction
@@ -2620,6 +2694,9 @@ fragment UserRequestFragment on UserRequest {
2620
2694
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2621
2695
  }
2622
2696
  transfer_spark_id: spark_id
2697
+ transfer_user_request: user_request {
2698
+ id
2699
+ }
2623
2700
  }
2624
2701
  }
2625
2702
  ... on LeavesSwapRequest {
@@ -2664,6 +2741,9 @@ fragment UserRequestFragment on UserRequest {
2664
2741
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2665
2742
  }
2666
2743
  transfer_spark_id: spark_id
2744
+ transfer_user_request: user_request {
2745
+ id
2746
+ }
2667
2747
  }
2668
2748
  leaves_swap_request_outbound_transfer: outbound_transfer {
2669
2749
  __typename
@@ -2676,6 +2756,9 @@ fragment UserRequestFragment on UserRequest {
2676
2756
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2677
2757
  }
2678
2758
  transfer_spark_id: spark_id
2759
+ transfer_user_request: user_request {
2760
+ id
2761
+ }
2679
2762
  }
2680
2763
  leaves_swap_request_expires_at: expires_at
2681
2764
  leaves_swap_request_swap_leaves: swap_leaves {
@@ -2720,8 +2803,12 @@ fragment UserRequestFragment on UserRequest {
2720
2803
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2721
2804
  }
2722
2805
  transfer_spark_id: spark_id
2806
+ transfer_user_request: user_request {
2807
+ id
2808
+ }
2723
2809
  }
2724
2810
  lightning_receive_request_payment_preimage: payment_preimage
2811
+ lightning_receive_request_receiver_identity_public_key: receiver_identity_public_key
2725
2812
  }
2726
2813
  ... on LightningSendRequest {
2727
2814
  __typename
@@ -2751,6 +2838,9 @@ fragment UserRequestFragment on UserRequest {
2751
2838
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2752
2839
  }
2753
2840
  transfer_spark_id: spark_id
2841
+ transfer_user_request: user_request {
2842
+ id
2843
+ }
2754
2844
  }
2755
2845
  lightning_send_request_payment_preimage: payment_preimage
2756
2846
  }
@@ -2831,11 +2921,12 @@ var SspClient = class {
2831
2921
  }
2832
2922
  });
2833
2923
  }
2834
- async getLightningSendFeeEstimate(encodedInvoice) {
2924
+ async getLightningSendFeeEstimate(encodedInvoice, amountSats) {
2835
2925
  return await this.executeRawQuery({
2836
2926
  queryPayload: LightningSendFeeEstimate,
2837
2927
  variables: {
2838
- encoded_invoice: encodedInvoice
2928
+ encoded_invoice: encodedInvoice,
2929
+ amount_sats: amountSats
2839
2930
  },
2840
2931
  constructObject: (response) => {
2841
2932
  return LightningSendFeeEstimateOutputFromJson(
@@ -2931,13 +3022,15 @@ var SspClient = class {
2931
3022
  }
2932
3023
  async requestLightningSend({
2933
3024
  encodedInvoice,
2934
- idempotencyKey
3025
+ idempotencyKey,
3026
+ amountSats
2935
3027
  }) {
2936
3028
  return await this.executeRawQuery({
2937
3029
  queryPayload: RequestLightningSend,
2938
3030
  variables: {
2939
3031
  encoded_invoice: encodedInvoice,
2940
- idempotency_key: idempotencyKey
3032
+ idempotency_key: idempotencyKey,
3033
+ amount_sats: amountSats
2941
3034
  },
2942
3035
  constructObject: (response) => {
2943
3036
  return LightningSendRequestFromJson(
@@ -3197,16 +3290,9 @@ init_buffer();
3197
3290
  init_buffer();
3198
3291
  var import_core7 = require("@lightsparkdev/core");
3199
3292
 
3200
- // src/graphql/objects/ExitSpeed.ts
3293
+ // src/graphql/objects/CoopExitFeeQuote.ts
3201
3294
  init_buffer();
3202
- var ExitSpeed = /* @__PURE__ */ ((ExitSpeed2) => {
3203
- ExitSpeed2["FUTURE_VALUE"] = "FUTURE_VALUE";
3204
- ExitSpeed2["FAST"] = "FAST";
3205
- ExitSpeed2["MEDIUM"] = "MEDIUM";
3206
- ExitSpeed2["SLOW"] = "SLOW";
3207
- return ExitSpeed2;
3208
- })(ExitSpeed || {});
3209
- var ExitSpeed_default = ExitSpeed;
3295
+ var import_core8 = require("@lightsparkdev/core");
3210
3296
 
3211
3297
  // src/graphql/objects/SparkUserRequestStatus.ts
3212
3298
  init_buffer();
@@ -3216,7 +3302,7 @@ init_buffer();
3216
3302
 
3217
3303
  // src/graphql/objects/SparkWalletUser.ts
3218
3304
  init_buffer();
3219
- var import_core8 = require("@lightsparkdev/core");
3305
+ var import_core9 = require("@lightsparkdev/core");
3220
3306
 
3221
3307
  // src/graphql/objects/SparkWalletUserToUserRequestsConnection.ts
3222
3308
  init_buffer();
@@ -4121,7 +4207,7 @@ var DepositAddressProof = {
4121
4207
  },
4122
4208
  fromJSON(object) {
4123
4209
  return {
4124
- addressSignatures: isObject8(object.addressSignatures) ? Object.entries(object.addressSignatures).reduce((acc, [key, value]) => {
4210
+ addressSignatures: isObject9(object.addressSignatures) ? Object.entries(object.addressSignatures).reduce((acc, [key, value]) => {
4125
4211
  acc[key] = bytesFromBase642(value);
4126
4212
  return acc;
4127
4213
  }, {}) : {},
@@ -4903,18 +4989,18 @@ var SigningResult = {
4903
4989
  },
4904
4990
  fromJSON(object) {
4905
4991
  return {
4906
- publicKeys: isObject8(object.publicKeys) ? Object.entries(object.publicKeys).reduce((acc, [key, value]) => {
4992
+ publicKeys: isObject9(object.publicKeys) ? Object.entries(object.publicKeys).reduce((acc, [key, value]) => {
4907
4993
  acc[key] = bytesFromBase642(value);
4908
4994
  return acc;
4909
4995
  }, {}) : {},
4910
- signingNonceCommitments: isObject8(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
4996
+ signingNonceCommitments: isObject9(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
4911
4997
  (acc, [key, value]) => {
4912
4998
  acc[key] = SigningCommitment.fromJSON(value);
4913
4999
  return acc;
4914
5000
  },
4915
5001
  {}
4916
5002
  ) : {},
4917
- signatureShares: isObject8(object.signatureShares) ? Object.entries(object.signatureShares).reduce((acc, [key, value]) => {
5003
+ signatureShares: isObject9(object.signatureShares) ? Object.entries(object.signatureShares).reduce((acc, [key, value]) => {
4918
5004
  acc[key] = bytesFromBase642(value);
4919
5005
  return acc;
4920
5006
  }, {}) : {},
@@ -8942,7 +9028,7 @@ var TransferPackage = {
8942
9028
  fromJSON(object) {
8943
9029
  return {
8944
9030
  leavesToSend: globalThis.Array.isArray(object?.leavesToSend) ? object.leavesToSend.map((e) => UserSignedTxSigningJob.fromJSON(e)) : [],
8945
- keyTweakPackage: isObject8(object.keyTweakPackage) ? Object.entries(object.keyTweakPackage).reduce((acc, [key, value]) => {
9031
+ keyTweakPackage: isObject9(object.keyTweakPackage) ? Object.entries(object.keyTweakPackage).reduce((acc, [key, value]) => {
8946
9032
  acc[key] = bytesFromBase642(value);
8947
9033
  return acc;
8948
9034
  }, {}) : {},
@@ -9204,7 +9290,7 @@ var SendLeafKeyTweak = {
9204
9290
  return {
9205
9291
  leafId: isSet3(object.leafId) ? globalThis.String(object.leafId) : "",
9206
9292
  secretShareTweak: isSet3(object.secretShareTweak) ? SecretShare.fromJSON(object.secretShareTweak) : void 0,
9207
- pubkeySharesTweak: isObject8(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
9293
+ pubkeySharesTweak: isObject9(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
9208
9294
  acc[key] = bytesFromBase642(value);
9209
9295
  return acc;
9210
9296
  }, {}) : {},
@@ -10177,7 +10263,7 @@ var ClaimLeafKeyTweak = {
10177
10263
  return {
10178
10264
  leafId: isSet3(object.leafId) ? globalThis.String(object.leafId) : "",
10179
10265
  secretShareTweak: isSet3(object.secretShareTweak) ? SecretShare.fromJSON(object.secretShareTweak) : void 0,
10180
- pubkeySharesTweak: isObject8(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
10266
+ pubkeySharesTweak: isObject9(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
10181
10267
  acc[key] = bytesFromBase642(value);
10182
10268
  return acc;
10183
10269
  }, {}) : {}
@@ -10853,7 +10939,7 @@ var RequestedSigningCommitments = {
10853
10939
  },
10854
10940
  fromJSON(object) {
10855
10941
  return {
10856
- signingNonceCommitments: isObject8(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
10942
+ signingNonceCommitments: isObject9(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
10857
10943
  (acc, [key, value]) => {
10858
10944
  acc[key] = SigningCommitment.fromJSON(value);
10859
10945
  return acc;
@@ -11100,7 +11186,7 @@ var SigningCommitments = {
11100
11186
  },
11101
11187
  fromJSON(object) {
11102
11188
  return {
11103
- signingCommitments: isObject8(object.signingCommitments) ? Object.entries(object.signingCommitments).reduce(
11189
+ signingCommitments: isObject9(object.signingCommitments) ? Object.entries(object.signingCommitments).reduce(
11104
11190
  (acc, [key, value]) => {
11105
11191
  acc[key] = SigningCommitment.fromJSON(value);
11106
11192
  return acc;
@@ -13201,7 +13287,7 @@ var GetSigningOperatorListResponse = {
13201
13287
  },
13202
13288
  fromJSON(object) {
13203
13289
  return {
13204
- signingOperators: isObject8(object.signingOperators) ? Object.entries(object.signingOperators).reduce(
13290
+ signingOperators: isObject9(object.signingOperators) ? Object.entries(object.signingOperators).reduce(
13205
13291
  (acc, [key, value]) => {
13206
13292
  acc[key] = SigningOperatorInfo.fromJSON(value);
13207
13293
  return acc;
@@ -13868,7 +13954,7 @@ var QueryNodesResponse = {
13868
13954
  },
13869
13955
  fromJSON(object) {
13870
13956
  return {
13871
- nodes: isObject8(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
13957
+ nodes: isObject9(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
13872
13958
  acc[key] = TreeNode.fromJSON(value);
13873
13959
  return acc;
13874
13960
  }, {}) : {},
@@ -14584,7 +14670,7 @@ var QueryBalanceResponse = {
14584
14670
  fromJSON(object) {
14585
14671
  return {
14586
14672
  balance: isSet3(object.balance) ? globalThis.Number(object.balance) : 0,
14587
- nodeBalances: isObject8(object.nodeBalances) ? Object.entries(object.nodeBalances).reduce((acc, [key, value]) => {
14673
+ nodeBalances: isObject9(object.nodeBalances) ? Object.entries(object.nodeBalances).reduce((acc, [key, value]) => {
14588
14674
  acc[key] = Number(value);
14589
14675
  return acc;
14590
14676
  }, {}) : {}
@@ -15594,7 +15680,7 @@ var QueryNodesDistributionResponse = {
15594
15680
  },
15595
15681
  fromJSON(object) {
15596
15682
  return {
15597
- nodeDistribution: isObject8(object.nodeDistribution) ? Object.entries(object.nodeDistribution).reduce((acc, [key, value]) => {
15683
+ nodeDistribution: isObject9(object.nodeDistribution) ? Object.entries(object.nodeDistribution).reduce((acc, [key, value]) => {
15598
15684
  acc[globalThis.Number(key)] = Number(value);
15599
15685
  return acc;
15600
15686
  }, {}) : {}
@@ -15843,7 +15929,7 @@ var QueryNodesByValueResponse = {
15843
15929
  },
15844
15930
  fromJSON(object) {
15845
15931
  return {
15846
- nodes: isObject8(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
15932
+ nodes: isObject9(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
15847
15933
  acc[key] = TreeNode.fromJSON(value);
15848
15934
  return acc;
15849
15935
  }, {}) : {},
@@ -16371,7 +16457,7 @@ function longToNumber2(int64) {
16371
16457
  }
16372
16458
  return num;
16373
16459
  }
16374
- function isObject8(value) {
16460
+ function isObject9(value) {
16375
16461
  return typeof value === "object" && value !== null;
16376
16462
  }
16377
16463
  function isSet3(value) {
@@ -16383,7 +16469,7 @@ init_buffer();
16383
16469
 
16384
16470
  // src/signer/signer.ts
16385
16471
  init_buffer();
16386
- var import_utils4 = require("@noble/curves/abstract/utils");
16472
+ var import_utils5 = require("@noble/curves/abstract/utils");
16387
16473
  var import_secp256k15 = require("@noble/curves/secp256k1");
16388
16474
  var import_bip32 = require("@scure/bip32");
16389
16475
  var import_bip39 = require("@scure/bip39");
@@ -16392,29 +16478,41 @@ var ecies = __toESM(require("eciesjs"), 1);
16392
16478
 
16393
16479
  // src/constants.ts
16394
16480
  init_buffer();
16481
+ var import_core10 = require("@lightsparkdev/core");
16395
16482
  var isReactNative = typeof navigator !== "undefined" && navigator.product === "ReactNative";
16396
16483
  var isBun = globalThis.Bun !== void 0;
16484
+ var packageVersion = true ? "0.1.43" : "unknown";
16485
+ var baseEnvStr = "unknown";
16486
+ if (import_core10.isNode) {
16487
+ baseEnvStr = `node/${process.version}`;
16488
+ } else if (isReactNative) {
16489
+ baseEnvStr = "react-native";
16490
+ } else {
16491
+ const userAgent = typeof navigator !== "undefined" && navigator.userAgent || "unknown-user-agent";
16492
+ baseEnvStr = `browser/${userAgent}`;
16493
+ }
16494
+ var clientEnv = `js-spark-sdk/${packageVersion} ${baseEnvStr}`;
16397
16495
 
16398
16496
  // src/utils/adaptor-signature.ts
16399
16497
  init_buffer();
16400
16498
  var import_modular = require("@noble/curves/abstract/modular");
16401
- var import_utils = require("@noble/curves/abstract/utils");
16499
+ var import_utils2 = require("@noble/curves/abstract/utils");
16402
16500
  var import_secp256k1 = require("@noble/curves/secp256k1");
16403
16501
  function generateSignatureFromExistingAdaptor(signature, adaptorPrivateKeyBytes) {
16404
16502
  const { r, s } = parseSignature(signature);
16405
- const sBigInt = (0, import_utils.bytesToNumberBE)(s);
16406
- const tBigInt = (0, import_utils.bytesToNumberBE)(adaptorPrivateKeyBytes);
16503
+ const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
16504
+ const tBigInt = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKeyBytes);
16407
16505
  const newS = (0, import_modular.mod)(sBigInt - tBigInt, import_secp256k1.secp256k1.CURVE.n);
16408
- const newSignature = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(newS, 32)]);
16506
+ const newSignature = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
16409
16507
  return newSignature;
16410
16508
  }
16411
16509
  function generateAdaptorFromSignature(signature) {
16412
16510
  const adaptorPrivateKey = import_secp256k1.secp256k1.utils.randomPrivateKey();
16413
16511
  const { r, s } = parseSignature(signature);
16414
- const sBigInt = (0, import_utils.bytesToNumberBE)(s);
16415
- const tBigInt = (0, import_utils.bytesToNumberBE)(adaptorPrivateKey);
16512
+ const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
16513
+ const tBigInt = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKey);
16416
16514
  const newS = (0, import_modular.mod)(sBigInt - tBigInt, import_secp256k1.secp256k1.CURVE.n);
16417
- const newSignature = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(newS, 32)]);
16515
+ const newSignature = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
16418
16516
  return {
16419
16517
  adaptorSignature: newSignature,
16420
16518
  adaptorPrivateKey
@@ -16431,15 +16529,15 @@ function validateOutboundAdaptorSignature(pubkey, hash, signature, adaptorPubkey
16431
16529
  }
16432
16530
  function applyAdaptorToSignature(pubkey, hash, signature, adaptorPrivateKeyBytes) {
16433
16531
  const { r, s } = parseSignature(signature);
16434
- const sBigInt = (0, import_utils.bytesToNumberBE)(s);
16435
- const adaptorPrivateKey = (0, import_utils.bytesToNumberBE)(adaptorPrivateKeyBytes);
16532
+ const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
16533
+ const adaptorPrivateKey = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKeyBytes);
16436
16534
  const newS = (0, import_modular.mod)(sBigInt + adaptorPrivateKey, import_secp256k1.secp256k1.CURVE.n);
16437
- const newSig = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(newS, 32)]);
16535
+ const newSig = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
16438
16536
  if (import_secp256k1.schnorr.verify(newSig, hash, pubkey)) {
16439
16537
  return newSig;
16440
16538
  }
16441
16539
  const altS = (0, import_modular.mod)(sBigInt - adaptorPrivateKey, import_secp256k1.secp256k1.CURVE.n);
16442
- const altSig = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(altS, 32)]);
16540
+ const altSig = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(altS, 32)]);
16443
16541
  if (import_secp256k1.schnorr.verify(altSig, hash, pubkey)) {
16444
16542
  return altSig;
16445
16543
  }
@@ -16449,7 +16547,7 @@ function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, i
16449
16547
  if (hash.length !== 32) {
16450
16548
  throw new Error(`wrong size for message (got ${hash.length}, want 32)`);
16451
16549
  }
16452
- const pubKey = import_secp256k1.schnorr.utils.lift_x((0, import_utils.bytesToNumberBE)(pubKeyBytes));
16550
+ const pubKey = import_secp256k1.schnorr.utils.lift_x((0, import_utils2.bytesToNumberBE)(pubKeyBytes));
16453
16551
  pubKey.assertValidity();
16454
16552
  const { r, s } = parseSignature(signature);
16455
16553
  const commitmenet = import_secp256k1.schnorr.utils.taggedHash(
@@ -16461,11 +16559,11 @@ function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, i
16461
16559
  if (commitmenet.length > 32) {
16462
16560
  throw new Error("hash of (r || P || m) too big");
16463
16561
  }
16464
- const e = (0, import_modular.mod)((0, import_utils.bytesToNumberBE)(commitmenet), import_secp256k1.secp256k1.CURVE.n);
16562
+ const e = (0, import_modular.mod)((0, import_utils2.bytesToNumberBE)(commitmenet), import_secp256k1.secp256k1.CURVE.n);
16465
16563
  const negE = (0, import_modular.mod)(-e, import_secp256k1.secp256k1.CURVE.n);
16466
16564
  const R = import_secp256k1.secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(
16467
16565
  pubKey,
16468
- (0, import_utils.bytesToNumberBE)(s),
16566
+ (0, import_utils2.bytesToNumberBE)(s),
16469
16567
  negE
16470
16568
  );
16471
16569
  if (!R) {
@@ -16481,7 +16579,7 @@ function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, i
16481
16579
  if (!newR.hasEvenY()) {
16482
16580
  throw new Error("calculated R y-value is odd");
16483
16581
  }
16484
- const rNum = (0, import_utils.bytesToNumberBE)(r);
16582
+ const rNum = (0, import_utils2.bytesToNumberBE)(r);
16485
16583
  if (newR.toAffine().x !== rNum) {
16486
16584
  throw new Error("calculated R point was not given R");
16487
16585
  }
@@ -16502,15 +16600,15 @@ function parseSignature(signature) {
16502
16600
  }
16503
16601
  const r = signature.slice(0, 32);
16504
16602
  const s = signature.slice(32, 64);
16505
- if ((0, import_utils.bytesToNumberBE)(r) >= import_secp256k1.secp256k1.CURVE.Fp.ORDER) {
16603
+ if ((0, import_utils2.bytesToNumberBE)(r) >= import_secp256k1.secp256k1.CURVE.Fp.ORDER) {
16506
16604
  throw new ValidationError("Invalid signature: r >= field prime", {
16507
- rValue: (0, import_utils.bytesToNumberBE)(r),
16605
+ rValue: (0, import_utils2.bytesToNumberBE)(r),
16508
16606
  fieldPrime: import_secp256k1.secp256k1.CURVE.Fp.ORDER
16509
16607
  });
16510
16608
  }
16511
- if ((0, import_utils.bytesToNumberBE)(s) >= import_secp256k1.secp256k1.CURVE.n) {
16609
+ if ((0, import_utils2.bytesToNumberBE)(s) >= import_secp256k1.secp256k1.CURVE.n) {
16512
16610
  throw new ValidationError("Invalid signature: s >= group order", {
16513
- sValue: (0, import_utils.bytesToNumberBE)(s),
16611
+ sValue: (0, import_utils2.bytesToNumberBE)(s),
16514
16612
  groupOrder: import_secp256k1.secp256k1.CURVE.n
16515
16613
  });
16516
16614
  }
@@ -16519,7 +16617,7 @@ function parseSignature(signature) {
16519
16617
 
16520
16618
  // src/utils/keys.ts
16521
16619
  init_buffer();
16522
- var import_utils2 = require("@noble/curves/abstract/utils");
16620
+ var import_utils3 = require("@noble/curves/abstract/utils");
16523
16621
  var import_secp256k12 = require("@noble/curves/secp256k1");
16524
16622
  function addPublicKeys(a, b) {
16525
16623
  if (a.length !== 33 || b.length !== 33) {
@@ -16577,7 +16675,7 @@ function addPrivateKeys(a, b) {
16577
16675
  const privA = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(a);
16578
16676
  const privB = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(b);
16579
16677
  const sum = (privA + privB) % import_secp256k12.secp256k1.CURVE.n;
16580
- return (0, import_utils2.numberToBytesBE)(sum, 32);
16678
+ return (0, import_utils3.numberToBytesBE)(sum, 32);
16581
16679
  }
16582
16680
  function subtractPrivateKeys(a, b) {
16583
16681
  if (a.length !== 32 || b.length !== 32) {
@@ -16590,7 +16688,7 @@ function subtractPrivateKeys(a, b) {
16590
16688
  const privA = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(a);
16591
16689
  const privB = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(b);
16592
16690
  const sum = (import_secp256k12.secp256k1.CURVE.n - privB + privA) % import_secp256k12.secp256k1.CURVE.n;
16593
- return (0, import_utils2.numberToBytesBE)(sum, 32);
16691
+ return (0, import_utils3.numberToBytesBE)(sum, 32);
16594
16692
  }
16595
16693
  function sumOfPrivateKeys(keys) {
16596
16694
  return keys.reduce((sum, key) => {
@@ -16618,7 +16716,7 @@ function lastKeyWithTarget(target, keys) {
16618
16716
 
16619
16717
  // src/utils/secret-sharing.ts
16620
16718
  init_buffer();
16621
- var import_utils3 = require("@noble/curves/abstract/utils");
16719
+ var import_utils4 = require("@noble/curves/abstract/utils");
16622
16720
  var import_secp256k13 = require("@noble/curves/secp256k1");
16623
16721
 
16624
16722
  // src/utils/crypto.ts
@@ -16637,7 +16735,7 @@ function getRandomBigInt(max) {
16637
16735
  const mask = (1n << BigInt(max.toString(2).length)) - 1n;
16638
16736
  while (true) {
16639
16737
  const randBytes = crypto.getRandomValues(new Uint8Array(byteLength + 1));
16640
- const randValue = BigInt("0x" + (0, import_utils3.bytesToHex)(randBytes)) & mask;
16738
+ const randValue = BigInt("0x" + (0, import_utils4.bytesToHex)(randBytes)) & mask;
16641
16739
  if (randValue < maxBigInt) {
16642
16740
  return randValue;
16643
16741
  }
@@ -16815,7 +16913,7 @@ function validateShare(share) {
16815
16913
  const scaledPoint = import_secp256k13.secp256k1.ProjectivePoint.fromHex(pubkey).multiply(value);
16816
16914
  resultPubkey = import_secp256k13.secp256k1.ProjectivePoint.fromHex(resultPubkey).add(scaledPoint).toRawBytes(true);
16817
16915
  }
16818
- if (!(0, import_utils3.equalBytes)(resultPubkey, targetPubkey)) {
16916
+ if (!(0, import_utils4.equalBytes)(resultPubkey, targetPubkey)) {
16819
16917
  throw new ValidationError("Share is not valid", {
16820
16918
  field: "share",
16821
16919
  value: "Invalid proof",
@@ -16918,7 +17016,9 @@ function decodeBytesToSigningCommitment(bytes2) {
16918
17016
  var import_secp256k16 = require("@bitcoinerlab/secp256k1");
16919
17017
  var import_lrc20_sdk = require("@buildonspark/lrc20-sdk");
16920
17018
  var import_sha22 = require("@noble/hashes/sha2");
16921
- var import_utils5 = require("@scure/btc-signer/utils");
17019
+ var import_utils6 = require("@scure/btc-signer/utils");
17020
+ var import_lrc20_sdk2 = require("@buildonspark/lrc20-sdk");
17021
+ var import_types2 = require("@buildonspark/lrc20-sdk/lrc/types");
16922
17022
  var sparkFrostModule = void 0;
16923
17023
  var getSparkFrostModule = async () => {
16924
17024
  if (isReactNative) {
@@ -17017,28 +17117,28 @@ var DefaultSparkSigner = class {
17017
17117
  const privateKey = this.deriveSigningKey(hash);
17018
17118
  const publicKey = import_secp256k15.secp256k1.getPublicKey(privateKey);
17019
17119
  this.publicKeyToPrivateKeyMap.set(
17020
- (0, import_utils4.bytesToHex)(publicKey),
17021
- (0, import_utils4.bytesToHex)(privateKey)
17120
+ (0, import_utils5.bytesToHex)(publicKey),
17121
+ (0, import_utils5.bytesToHex)(privateKey)
17022
17122
  );
17023
17123
  }
17024
17124
  }
17025
17125
  async getSchnorrPublicKey(publicKey) {
17026
- const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey));
17126
+ const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey));
17027
17127
  if (!privateKey) {
17028
17128
  throw new ValidationError("Private key is not set", {
17029
17129
  field: "privateKey"
17030
17130
  });
17031
17131
  }
17032
- return import_secp256k15.schnorr.getPublicKey((0, import_utils4.hexToBytes)(privateKey));
17132
+ return import_secp256k15.schnorr.getPublicKey((0, import_utils5.hexToBytes)(privateKey));
17033
17133
  }
17034
17134
  async signSchnorr(message, publicKey) {
17035
- const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey));
17135
+ const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey));
17036
17136
  if (!privateKey) {
17037
17137
  throw new ValidationError("Private key is not set", {
17038
17138
  field: "privateKey"
17039
17139
  });
17040
17140
  }
17041
- return import_secp256k15.schnorr.sign(message, (0, import_utils4.hexToBytes)(privateKey));
17141
+ return import_secp256k15.schnorr.sign(message, (0, import_utils5.hexToBytes)(privateKey));
17042
17142
  }
17043
17143
  async signSchnorrWithIdentityKey(message) {
17044
17144
  if (!this.identityKey?.privateKey) {
@@ -17080,8 +17180,8 @@ var DefaultSparkSigner = class {
17080
17180
  );
17081
17181
  this.staticDepositKeyMap.set(idx, staticDepositKey);
17082
17182
  this.publicKeyToPrivateKeyMap.set(
17083
- (0, import_utils4.bytesToHex)(staticDepositKey.publicKey),
17084
- (0, import_utils4.bytesToHex)(staticDepositKey.privateKey)
17183
+ (0, import_utils5.bytesToHex)(staticDepositKey.publicKey),
17184
+ (0, import_utils5.bytesToHex)(staticDepositKey.privateKey)
17085
17185
  );
17086
17186
  return staticDepositKey.publicKey;
17087
17187
  }
@@ -17126,7 +17226,7 @@ var DefaultSparkSigner = class {
17126
17226
  return await (0, import_bip39.mnemonicToSeed)(mnemonic);
17127
17227
  }
17128
17228
  async getTrackedPublicKeys() {
17129
- return Array.from(this.publicKeyToPrivateKeyMap.keys()).map(import_utils4.hexToBytes);
17229
+ return Array.from(this.publicKeyToPrivateKeyMap.keys()).map(import_utils5.hexToBytes);
17130
17230
  }
17131
17231
  async generatePublicKey(hash) {
17132
17232
  if (!this.signingKey) {
@@ -17146,31 +17246,31 @@ var DefaultSparkSigner = class {
17146
17246
  });
17147
17247
  }
17148
17248
  const publicKey = import_secp256k15.secp256k1.getPublicKey(newPrivateKey);
17149
- const pubKeyHex = (0, import_utils4.bytesToHex)(publicKey);
17150
- const privKeyHex = (0, import_utils4.bytesToHex)(newPrivateKey);
17249
+ const pubKeyHex = (0, import_utils5.bytesToHex)(publicKey);
17250
+ const privKeyHex = (0, import_utils5.bytesToHex)(newPrivateKey);
17151
17251
  this.publicKeyToPrivateKeyMap.set(pubKeyHex, privKeyHex);
17152
17252
  return publicKey;
17153
17253
  }
17154
17254
  async removePublicKey(publicKey) {
17155
- this.publicKeyToPrivateKeyMap.delete((0, import_utils4.bytesToHex)(publicKey));
17255
+ this.publicKeyToPrivateKeyMap.delete((0, import_utils5.bytesToHex)(publicKey));
17156
17256
  }
17157
17257
  async subtractPrivateKeysGivenPublicKeys(first, second) {
17158
- const firstPubKeyHex = (0, import_utils4.bytesToHex)(first);
17159
- const secondPubKeyHex = (0, import_utils4.bytesToHex)(second);
17258
+ const firstPubKeyHex = (0, import_utils5.bytesToHex)(first);
17259
+ const secondPubKeyHex = (0, import_utils5.bytesToHex)(second);
17160
17260
  const firstPrivateKeyHex = this.publicKeyToPrivateKeyMap.get(firstPubKeyHex);
17161
17261
  const secondPrivateKeyHex = this.publicKeyToPrivateKeyMap.get(secondPubKeyHex);
17162
17262
  if (!firstPrivateKeyHex || !secondPrivateKeyHex) {
17163
17263
  throw new Error("Private key is not set");
17164
17264
  }
17165
- const firstPrivateKey = (0, import_utils4.hexToBytes)(firstPrivateKeyHex);
17166
- const secondPrivateKey = (0, import_utils4.hexToBytes)(secondPrivateKeyHex);
17265
+ const firstPrivateKey = (0, import_utils5.hexToBytes)(firstPrivateKeyHex);
17266
+ const secondPrivateKey = (0, import_utils5.hexToBytes)(secondPrivateKeyHex);
17167
17267
  const resultPrivKey = subtractPrivateKeys(
17168
17268
  firstPrivateKey,
17169
17269
  secondPrivateKey
17170
17270
  );
17171
17271
  const resultPubKey = import_secp256k15.secp256k1.getPublicKey(resultPrivKey);
17172
- const resultPrivKeyHex = (0, import_utils4.bytesToHex)(resultPrivKey);
17173
- const resultPubKeyHex = (0, import_utils4.bytesToHex)(resultPubKey);
17272
+ const resultPrivKeyHex = (0, import_utils5.bytesToHex)(resultPrivKey);
17273
+ const resultPubKeyHex = (0, import_utils5.bytesToHex)(resultPubKey);
17174
17274
  this.publicKeyToPrivateKeyMap.set(resultPubKeyHex, resultPrivKeyHex);
17175
17275
  return resultPubKey;
17176
17276
  }
@@ -17182,14 +17282,14 @@ var DefaultSparkSigner = class {
17182
17282
  isSecretPubkey = false
17183
17283
  }) {
17184
17284
  if (isSecretPubkey) {
17185
- const pubKeyHex = (0, import_utils4.bytesToHex)(secret);
17285
+ const pubKeyHex = (0, import_utils5.bytesToHex)(secret);
17186
17286
  const privateKey = this.publicKeyToPrivateKeyMap.get(pubKeyHex);
17187
17287
  if (!privateKey) {
17188
17288
  throw new Error("Private key is not set");
17189
17289
  }
17190
- secret = (0, import_utils4.hexToBytes)(privateKey);
17290
+ secret = (0, import_utils5.hexToBytes)(privateKey);
17191
17291
  }
17192
- const secretAsInt = (0, import_utils4.bytesToNumberBE)(secret);
17292
+ const secretAsInt = (0, import_utils5.bytesToNumberBE)(secret);
17193
17293
  return splitSecretWithProofs(secretAsInt, curveOrder, threshold, numShares);
17194
17294
  }
17195
17295
  async signFrost({
@@ -17207,7 +17307,7 @@ var DefaultSparkSigner = class {
17207
17307
  field: "SparkFrost"
17208
17308
  });
17209
17309
  }
17210
- const privateAsPubKeyHex = (0, import_utils4.bytesToHex)(privateAsPubKey);
17310
+ const privateAsPubKeyHex = (0, import_utils5.bytesToHex)(privateAsPubKey);
17211
17311
  const signingPrivateKey = this.publicKeyToPrivateKeyMap.get(privateAsPubKeyHex);
17212
17312
  if (!signingPrivateKey) {
17213
17313
  throw new ValidationError("Private key not found for public key", {
@@ -17221,7 +17321,7 @@ var DefaultSparkSigner = class {
17221
17321
  });
17222
17322
  }
17223
17323
  const keyPackage = {
17224
- secretKey: (0, import_utils4.hexToBytes)(signingPrivateKey),
17324
+ secretKey: (0, import_utils5.hexToBytes)(signingPrivateKey),
17225
17325
  publicKey,
17226
17326
  verifyingKey
17227
17327
  };
@@ -17265,7 +17365,7 @@ var DefaultSparkSigner = class {
17265
17365
  }
17266
17366
  async createSparkWalletFromSeed(seed, accountNumber) {
17267
17367
  if (typeof seed === "string") {
17268
- seed = (0, import_utils4.hexToBytes)(seed);
17368
+ seed = (0, import_utils5.hexToBytes)(seed);
17269
17369
  }
17270
17370
  const {
17271
17371
  masterPublicKey,
@@ -17280,28 +17380,28 @@ var DefaultSparkSigner = class {
17280
17380
  this.signingKey = signingKey.hdKey;
17281
17381
  this.staticDepositKey = staticDepositKey.hdKey;
17282
17382
  this.publicKeyToPrivateKeyMap.set(
17283
- (0, import_utils4.bytesToHex)(identityKey.publicKey),
17284
- (0, import_utils4.bytesToHex)(identityKey.privateKey)
17383
+ (0, import_utils5.bytesToHex)(identityKey.publicKey),
17384
+ (0, import_utils5.bytesToHex)(identityKey.privateKey)
17285
17385
  );
17286
17386
  this.publicKeyToPrivateKeyMap.set(
17287
- (0, import_utils4.bytesToHex)(depositKey.publicKey),
17288
- (0, import_utils4.bytesToHex)(depositKey.privateKey)
17387
+ (0, import_utils5.bytesToHex)(depositKey.publicKey),
17388
+ (0, import_utils5.bytesToHex)(depositKey.privateKey)
17289
17389
  );
17290
17390
  this.publicKeyToPrivateKeyMap.set(
17291
- (0, import_utils4.bytesToHex)(staticDepositKey.publicKey),
17292
- (0, import_utils4.bytesToHex)(staticDepositKey.privateKey)
17391
+ (0, import_utils5.bytesToHex)(staticDepositKey.publicKey),
17392
+ (0, import_utils5.bytesToHex)(staticDepositKey.privateKey)
17293
17393
  );
17294
- return (0, import_utils4.bytesToHex)(identityKey.publicKey);
17394
+ return (0, import_utils5.bytesToHex)(identityKey.publicKey);
17295
17395
  }
17296
17396
  async signMessageWithPublicKey(message, publicKey, compact) {
17297
- const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey));
17397
+ const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey));
17298
17398
  if (!privateKey) {
17299
17399
  throw new ValidationError("Private key not found for public key", {
17300
17400
  field: "privateKey",
17301
- value: (0, import_utils4.bytesToHex)(publicKey)
17401
+ value: (0, import_utils5.bytesToHex)(publicKey)
17302
17402
  });
17303
17403
  }
17304
- const signature = import_secp256k15.secp256k1.sign(message, (0, import_utils4.hexToBytes)(privateKey));
17404
+ const signature = import_secp256k15.secp256k1.sign(message, (0, import_utils5.hexToBytes)(privateKey));
17305
17405
  if (compact) {
17306
17406
  return signature.toCompactRawBytes();
17307
17407
  }
@@ -17320,12 +17420,12 @@ var DefaultSparkSigner = class {
17320
17420
  return signature.toDERRawBytes();
17321
17421
  }
17322
17422
  async encryptLeafPrivateKeyEcies(receiverPublicKey, publicKey) {
17323
- const publicKeyHex = (0, import_utils4.bytesToHex)(publicKey);
17423
+ const publicKeyHex = (0, import_utils5.bytesToHex)(publicKey);
17324
17424
  const privateKey = this.publicKeyToPrivateKeyMap.get(publicKeyHex);
17325
17425
  if (!privateKey) {
17326
17426
  throw new Error("Private key is not set");
17327
17427
  }
17328
- return ecies.encrypt(receiverPublicKey, (0, import_utils4.hexToBytes)(privateKey));
17428
+ return ecies.encrypt(receiverPublicKey, (0, import_utils5.hexToBytes)(privateKey));
17329
17429
  }
17330
17430
  async decryptEcies(ciphertext) {
17331
17431
  if (!this.identityKey?.privateKey) {
@@ -17334,12 +17434,12 @@ var DefaultSparkSigner = class {
17334
17434
  });
17335
17435
  }
17336
17436
  const receiverEciesPrivKey = ecies.PrivateKey.fromHex(
17337
- (0, import_utils4.bytesToHex)(this.identityKey.privateKey)
17437
+ (0, import_utils5.bytesToHex)(this.identityKey.privateKey)
17338
17438
  );
17339
17439
  const privateKey = ecies.decrypt(receiverEciesPrivKey.toHex(), ciphertext);
17340
17440
  const publicKey = import_secp256k15.secp256k1.getPublicKey(privateKey);
17341
- const publicKeyHex = (0, import_utils4.bytesToHex)(publicKey);
17342
- const privateKeyHex = (0, import_utils4.bytesToHex)(privateKey);
17441
+ const publicKeyHex = (0, import_utils5.bytesToHex)(publicKey);
17442
+ const privateKeyHex = (0, import_utils5.bytesToHex)(privateKey);
17343
17443
  this.publicKeyToPrivateKeyMap.set(publicKeyHex, privateKeyHex);
17344
17444
  return publicKey;
17345
17445
  }
@@ -17356,8 +17456,8 @@ var DefaultSparkSigner = class {
17356
17456
  const adaptor = generateAdaptorFromSignature(signature);
17357
17457
  const adaptorPublicKey = import_secp256k15.secp256k1.getPublicKey(adaptor.adaptorPrivateKey);
17358
17458
  this.publicKeyToPrivateKeyMap.set(
17359
- (0, import_utils4.bytesToHex)(adaptorPublicKey),
17360
- (0, import_utils4.bytesToHex)(adaptor.adaptorPrivateKey)
17459
+ (0, import_utils5.bytesToHex)(adaptorPublicKey),
17460
+ (0, import_utils5.bytesToHex)(adaptor.adaptorPrivateKey)
17361
17461
  );
17362
17462
  return {
17363
17463
  adaptorSignature: signature,
@@ -17408,19 +17508,19 @@ var DefaultSparkSigner = class {
17408
17508
  }
17409
17509
  signTransactionIndex(tx, index, publicKey) {
17410
17510
  let privateKey;
17411
- if ((0, import_utils4.equalBytes)(publicKey, this.identityKey?.publicKey ?? new Uint8Array())) {
17511
+ if ((0, import_utils5.equalBytes)(publicKey, this.identityKey?.publicKey ?? new Uint8Array())) {
17412
17512
  privateKey = this.identityKey?.privateKey;
17413
- } else if ((0, import_utils4.equalBytes)(publicKey, this.depositKey?.publicKey ?? new Uint8Array())) {
17513
+ } else if ((0, import_utils5.equalBytes)(publicKey, this.depositKey?.publicKey ?? new Uint8Array())) {
17414
17514
  privateKey = this.depositKey?.privateKey;
17415
17515
  } else {
17416
- privateKey = (0, import_utils4.hexToBytes)(
17417
- this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey)) ?? ""
17516
+ privateKey = (0, import_utils5.hexToBytes)(
17517
+ this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey)) ?? ""
17418
17518
  );
17419
17519
  }
17420
17520
  if (!privateKey) {
17421
17521
  throw new ValidationError("Private key not found for public key", {
17422
17522
  field: "privateKey",
17423
- value: (0, import_utils4.bytesToHex)(publicKey)
17523
+ value: (0, import_utils5.bytesToHex)(publicKey)
17424
17524
  });
17425
17525
  }
17426
17526
  tx.signIdx(privateKey, index);
@@ -17429,7 +17529,7 @@ var DefaultSparkSigner = class {
17429
17529
 
17430
17530
  // src/utils/network.ts
17431
17531
  init_buffer();
17432
- var import_lrc20_sdk2 = require("@buildonspark/lrc20-sdk");
17532
+ var import_lrc20_sdk3 = require("@buildonspark/lrc20-sdk");
17433
17533
  var btc = __toESM(require("@scure/btc-signer"), 1);
17434
17534
  var bitcoin = __toESM(require("bitcoinjs-lib"), 1);
17435
17535
  var Network2 = /* @__PURE__ */ ((Network6) => {
@@ -17463,11 +17563,11 @@ var LRC_WALLET_NETWORK = Object.freeze({
17463
17563
  [4 /* LOCAL */]: bitcoin.networks.regtest
17464
17564
  });
17465
17565
  var LRC_WALLET_NETWORK_TYPE = Object.freeze({
17466
- [0 /* MAINNET */]: import_lrc20_sdk2.NetworkType.MAINNET,
17467
- [1 /* TESTNET */]: import_lrc20_sdk2.NetworkType.TESTNET,
17468
- [2 /* SIGNET */]: import_lrc20_sdk2.NetworkType.TESTNET,
17469
- [3 /* REGTEST */]: import_lrc20_sdk2.NetworkType.REGTEST,
17470
- [4 /* LOCAL */]: import_lrc20_sdk2.NetworkType.LOCAL
17566
+ [0 /* MAINNET */]: import_lrc20_sdk3.NetworkType.MAINNET,
17567
+ [1 /* TESTNET */]: import_lrc20_sdk3.NetworkType.TESTNET,
17568
+ [2 /* SIGNET */]: import_lrc20_sdk3.NetworkType.TESTNET,
17569
+ [3 /* REGTEST */]: import_lrc20_sdk3.NetworkType.REGTEST,
17570
+ [4 /* LOCAL */]: import_lrc20_sdk3.NetworkType.LOCAL
17471
17571
  });
17472
17572
  function getNetworkFromAddress(address2) {
17473
17573
  try {
@@ -17504,10 +17604,10 @@ init_buffer();
17504
17604
 
17505
17605
  // src/tests/isHermeticTest.ts
17506
17606
  init_buffer();
17507
- var import_core9 = require("@lightsparkdev/core");
17607
+ var import_core11 = require("@lightsparkdev/core");
17508
17608
  var import_fs = __toESM(require("fs"), 1);
17509
17609
  function isHermeticTest() {
17510
- if (import_core9.isNode) {
17610
+ if (import_core11.isNode) {
17511
17611
  return (import_fs.default?.existsSync?.("/tmp/spark_hermetic") ?? false) || process.env.HERMETIC_TEST === "true";
17512
17612
  }
17513
17613
  return typeof process !== "undefined" && process.env?.HERMETIC_TEST === "true" || false;
@@ -17635,6 +17735,7 @@ var BASE_CONFIG = {
17635
17735
  signingOperators: getLocalSigningOperators(),
17636
17736
  tokenSignatures: "SCHNORR",
17637
17737
  tokenTransactionVersion: "V0",
17738
+ tokenValidityDurationSeconds: 180,
17638
17739
  electrsUrl: getElectrsUrl("LOCAL"),
17639
17740
  expectedWithdrawBondSats: 1e4,
17640
17741
  expectedWithdrawRelativeBlockLocktime: 1e3,
@@ -17845,6 +17946,9 @@ var WalletConfigService = class {
17845
17946
  getTokenTransactionVersion() {
17846
17947
  return this.config.tokenTransactionVersion;
17847
17948
  }
17949
+ getTokenValidityDurationSeconds() {
17950
+ return this.config.tokenValidityDurationSeconds;
17951
+ }
17848
17952
  getElectrsUrl() {
17849
17953
  return this.config.electrsUrl;
17850
17954
  }
@@ -17855,7 +17959,7 @@ var WalletConfigService = class {
17855
17959
 
17856
17960
  // src/services/connection.ts
17857
17961
  init_buffer();
17858
- var import_core10 = require("@lightsparkdev/core");
17962
+ var import_core12 = require("@lightsparkdev/core");
17859
17963
  var import_sha23 = require("@noble/hashes/sha2");
17860
17964
  var import_nice_grpc_client_middleware_retry = require("nice-grpc-client-middleware-retry");
17861
17965
  var import_nice_grpc_common2 = require("nice-grpc-common");
@@ -19704,7 +19808,7 @@ var ConnectionManager = class {
19704
19808
  async createMockClient(address2) {
19705
19809
  const channel = await this.createChannelWithTLS(address2);
19706
19810
  const isNodeChannel = "close" in channel;
19707
- if (import_core10.isNode && isNodeChannel && !isBun) {
19811
+ if (import_core12.isNode && isNodeChannel && !isBun) {
19708
19812
  const grpcModule = await import("nice-grpc");
19709
19813
  const { createClient } = "default" in grpcModule ? grpcModule.default : grpcModule;
19710
19814
  const client = createClient(MockServiceDefinition, channel);
@@ -19721,7 +19825,7 @@ var ConnectionManager = class {
19721
19825
  }
19722
19826
  async createChannelWithTLS(address2, certPath) {
19723
19827
  try {
19724
- if (import_core10.isNode && !isBun) {
19828
+ if (import_core12.isNode && !isBun) {
19725
19829
  const grpcModule = await import("nice-grpc");
19726
19830
  const { ChannelCredentials, createChannel } = "default" in grpcModule ? grpcModule.default : grpcModule;
19727
19831
  if (certPath) {
@@ -19862,14 +19966,38 @@ var ConnectionManager = class {
19862
19966
  }
19863
19967
  async createSparkAuthnGrpcConnection(address2, certPath) {
19864
19968
  const channel = await this.createChannelWithTLS(address2, certPath);
19969
+ const authnMiddleware = this.createAuthnMiddleware();
19865
19970
  return this.createGrpcClient(
19866
19971
  SparkAuthnServiceDefinition,
19867
19972
  channel,
19868
- false
19973
+ false,
19974
+ authnMiddleware
19869
19975
  );
19870
19976
  }
19977
+ createAuthnMiddleware() {
19978
+ if (import_core12.isNode) {
19979
+ return async function* (call, options) {
19980
+ const metadata = (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
19981
+ "X-Client-Env",
19982
+ clientEnv
19983
+ );
19984
+ return yield* call.next(call.request, {
19985
+ ...options,
19986
+ metadata
19987
+ });
19988
+ }.bind(this);
19989
+ } else {
19990
+ return async function* (call, options) {
19991
+ const metadata = (0, import_nice_grpc_common2.Metadata)(options.metadata).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("X-Client-Env", clientEnv).set("Content-Type", "application/grpc-web+proto");
19992
+ return yield* call.next(call.request, {
19993
+ ...options,
19994
+ metadata
19995
+ });
19996
+ }.bind(this);
19997
+ }
19998
+ }
19871
19999
  createMiddleware(address2, authToken) {
19872
- if (import_core10.isNode) {
20000
+ if (import_core12.isNode) {
19873
20001
  return this.createNodeMiddleware(address2, authToken);
19874
20002
  } else {
19875
20003
  return this.createBrowserMiddleware(address2, authToken);
@@ -19877,21 +20005,29 @@ var ConnectionManager = class {
19877
20005
  }
19878
20006
  createNodeMiddleware(address2, initialAuthToken) {
19879
20007
  return async function* (call, options) {
20008
+ const metadata = (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
20009
+ "X-Client-Env",
20010
+ clientEnv
20011
+ );
19880
20012
  try {
19881
20013
  return yield* call.next(call.request, {
19882
20014
  ...options,
19883
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
20015
+ metadata: metadata.set(
19884
20016
  "Authorization",
19885
20017
  `Bearer ${this.clients.get(address2)?.authToken || initialAuthToken}`
19886
- ).set("User-Agent", "spark-js-sdk")
20018
+ )
19887
20019
  });
19888
20020
  } catch (error) {
19889
20021
  if (error.message?.includes("token has expired")) {
19890
20022
  const newAuthToken = await this.authenticate(address2);
19891
- this.clients.get(address2).authToken = newAuthToken;
20023
+ const clientData = this.clients.get(address2);
20024
+ if (!clientData) {
20025
+ throw new Error(`No client found for address: ${address2}`);
20026
+ }
20027
+ clientData.authToken = newAuthToken;
19892
20028
  return yield* call.next(call.request, {
19893
20029
  ...options,
19894
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set("Authorization", `Bearer ${newAuthToken}`).set("User-Agent", "spark-js-sdk")
20030
+ metadata: metadata.set("Authorization", `Bearer ${newAuthToken}`)
19895
20031
  });
19896
20032
  }
19897
20033
  throw error;
@@ -19900,21 +20036,26 @@ var ConnectionManager = class {
19900
20036
  }
19901
20037
  createBrowserMiddleware(address2, initialAuthToken) {
19902
20038
  return async function* (call, options) {
20039
+ const metadata = (0, import_nice_grpc_common2.Metadata)(options.metadata).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("X-Client-Env", clientEnv).set("Content-Type", "application/grpc-web+proto");
19903
20040
  try {
19904
20041
  return yield* call.next(call.request, {
19905
20042
  ...options,
19906
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
20043
+ metadata: metadata.set(
19907
20044
  "Authorization",
19908
20045
  `Bearer ${this.clients.get(address2)?.authToken || initialAuthToken}`
19909
- ).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("Content-Type", "application/grpc-web+proto").set("User-Agent", "spark-js-sdk")
20046
+ )
19910
20047
  });
19911
20048
  } catch (error) {
19912
20049
  if (error.message?.includes("token has expired")) {
19913
20050
  const newAuthToken = await this.authenticate(address2);
19914
- this.clients.get(address2).authToken = newAuthToken;
20051
+ const clientData = this.clients.get(address2);
20052
+ if (!clientData) {
20053
+ throw new Error(`No client found for address: ${address2}`);
20054
+ }
20055
+ clientData.authToken = newAuthToken;
19915
20056
  return yield* call.next(call.request, {
19916
20057
  ...options,
19917
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set("Authorization", `Bearer ${newAuthToken}`).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("Content-Type", "application/grpc-web+proto").set("User-Agent", "spark-js-sdk")
20058
+ metadata: metadata.set("Authorization", `Bearer ${newAuthToken}`)
19918
20059
  });
19919
20060
  }
19920
20061
  throw error;
@@ -19929,7 +20070,7 @@ var ConnectionManager = class {
19929
20070
  };
19930
20071
  let options = {};
19931
20072
  const isNodeChannel = "close" in channel;
19932
- if (import_core10.isNode && isNodeChannel && !isBun) {
20073
+ if (import_core12.isNode && isNodeChannel && !isBun) {
19933
20074
  const grpcModule = await import("nice-grpc");
19934
20075
  const { openTelemetryClientMiddleware } = await import("nice-grpc-opentelemetry");
19935
20076
  const { createClientFactory } = "default" in grpcModule ? grpcModule.default : grpcModule;
@@ -19979,7 +20120,7 @@ var import_uuidv72 = require("uuidv7");
19979
20120
 
19980
20121
  // src/utils/bitcoin.ts
19981
20122
  init_buffer();
19982
- var import_utils6 = require("@noble/curves/abstract/utils");
20123
+ var import_utils7 = require("@noble/curves/abstract/utils");
19983
20124
  var import_secp256k17 = require("@noble/curves/secp256k1");
19984
20125
  var import_sha24 = require("@noble/hashes/sha2");
19985
20126
  var btc2 = __toESM(require("@scure/btc-signer"), 1);
@@ -19992,7 +20133,7 @@ function computeTaprootKeyNoScript(pubkey) {
19992
20133
  });
19993
20134
  }
19994
20135
  const taggedHash = import_secp256k17.schnorr.utils.taggedHash("TapTweak", pubkey);
19995
- const tweak = (0, import_utils6.bytesToNumberBE)(taggedHash);
20136
+ const tweak = (0, import_utils7.bytesToNumberBE)(taggedHash);
19996
20137
  const P = import_secp256k17.schnorr.utils.lift_x(import_secp256k17.schnorr.utils.bytesToNumberBE(pubkey));
19997
20138
  const Q = P.add(import_secp256k17.secp256k1.ProjectivePoint.fromPrivateKey(tweak));
19998
20139
  return Q.toRawBytes();
@@ -20045,7 +20186,7 @@ function getP2TRAddressFromPkScript(pkScript, network) {
20045
20186
  if (pkScript.length !== 34 || pkScript[0] !== 81 || pkScript[1] !== 32) {
20046
20187
  throw new ValidationError("Invalid pkscript", {
20047
20188
  field: "pkScript",
20048
- value: (0, import_utils6.bytesToHex)(pkScript),
20189
+ value: (0, import_utils7.bytesToHex)(pkScript),
20049
20190
  expected: "34 bytes starting with 0x51 0x20"
20050
20191
  });
20051
20192
  }
@@ -20070,7 +20211,7 @@ function getP2WPKHAddressFromPublicKey(pubKey, network) {
20070
20211
  return address2;
20071
20212
  }
20072
20213
  function getTxFromRawTxHex(rawTxHex) {
20073
- const txBytes = (0, import_utils6.hexToBytes)(rawTxHex);
20214
+ const txBytes = (0, import_utils7.hexToBytes)(rawTxHex);
20074
20215
  const tx = btc2.Transaction.fromRaw(txBytes, {
20075
20216
  allowUnknownOutputs: true
20076
20217
  });
@@ -20117,10 +20258,10 @@ function getSigHashFromTx(tx, inputIndex, prevOutput) {
20117
20258
  );
20118
20259
  }
20119
20260
  function getTxId(tx) {
20120
- return (0, import_utils6.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))).reverse());
20261
+ return (0, import_utils7.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))).reverse());
20121
20262
  }
20122
20263
  function getTxIdNoReverse(tx) {
20123
- return (0, import_utils6.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))));
20264
+ return (0, import_utils7.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))));
20124
20265
  }
20125
20266
 
20126
20267
  // src/utils/transaction.ts
@@ -20208,7 +20349,7 @@ function getEphemeralAnchorOutput() {
20208
20349
 
20209
20350
  // src/services/transfer.ts
20210
20351
  init_buffer();
20211
- var import_utils8 = require("@noble/curves/abstract/utils");
20352
+ var import_utils9 = require("@noble/curves/abstract/utils");
20212
20353
  var import_secp256k18 = require("@noble/curves/secp256k1");
20213
20354
  var import_sha26 = require("@noble/hashes/sha2");
20214
20355
  var import_btc_signer2 = require("@scure/btc-signer");
@@ -20217,7 +20358,7 @@ var import_uuidv7 = require("uuidv7");
20217
20358
 
20218
20359
  // src/utils/transfer_package.ts
20219
20360
  init_buffer();
20220
- var import_utils7 = require("@noble/curves/abstract/utils");
20361
+ var import_utils8 = require("@noble/curves/abstract/utils");
20221
20362
  var import_sha25 = require("@noble/hashes/sha2");
20222
20363
  function getTransferPackageSigningPayload(transferID, transferPackage) {
20223
20364
  const encryptedPayload = transferPackage.keyTweakPackage;
@@ -20226,7 +20367,7 @@ function getTransferPackageSigningPayload(transferID, transferPackage) {
20226
20367
  ).map(([key, value]) => ({ key, value }));
20227
20368
  pairs.sort((a, b) => a.key.localeCompare(b.key));
20228
20369
  const encoder = new TextEncoder();
20229
- let message = (0, import_utils7.hexToBytes)(transferID.replaceAll("-", ""));
20370
+ let message = (0, import_utils8.hexToBytes)(transferID.replaceAll("-", ""));
20230
20371
  for (const pair of pairs) {
20231
20372
  const keyPart = encoder.encode(pair.key + ":");
20232
20373
  const separator = encoder.encode(";");
@@ -20505,7 +20646,7 @@ var BaseTransferService = class {
20505
20646
  }
20506
20647
  async prepareSendTransferKeyTweaks(transferID, receiverIdentityPubkey, leaves, refundSignatureMap) {
20507
20648
  const receiverEciesPubKey = ecies2.PublicKey.fromHex(
20508
- (0, import_utils8.bytesToHex)(receiverIdentityPubkey)
20649
+ (0, import_utils9.bytesToHex)(receiverIdentityPubkey)
20509
20650
  );
20510
20651
  const leavesTweaksMap = /* @__PURE__ */ new Map();
20511
20652
  for (const leaf of leaves) {
@@ -20545,7 +20686,7 @@ var BaseTransferService = class {
20545
20686
  throw new Error(`Share not found for operator ${operator.id}`);
20546
20687
  }
20547
20688
  const pubkeyTweak = import_secp256k18.secp256k1.getPublicKey(
20548
- (0, import_utils8.numberToBytesBE)(share.share, 32),
20689
+ (0, import_utils9.numberToBytesBE)(share.share, 32),
20549
20690
  true
20550
20691
  );
20551
20692
  pubkeySharesTweak.set(identifier, pubkeyTweak);
@@ -20574,7 +20715,7 @@ var BaseTransferService = class {
20574
20715
  leafTweaksMap.set(identifier, {
20575
20716
  leafId: leaf.leaf.id,
20576
20717
  secretShareTweak: {
20577
- secretShare: (0, import_utils8.numberToBytesBE)(share.share, 32),
20718
+ secretShare: (0, import_utils9.numberToBytesBE)(share.share, 32),
20578
20719
  proofs: share.proofs
20579
20720
  },
20580
20721
  pubkeySharesTweak: Object.fromEntries(pubkeySharesTweak),
@@ -20595,7 +20736,7 @@ var BaseTransferService = class {
20595
20736
  return void 0;
20596
20737
  }
20597
20738
  compareTransfers(transfer1, transfer2) {
20598
- return transfer1.id === transfer2.id && (0, import_utils8.equalBytes)(
20739
+ return transfer1.id === transfer2.id && (0, import_utils9.equalBytes)(
20599
20740
  transfer1.senderIdentityPublicKey,
20600
20741
  transfer2.senderIdentityPublicKey
20601
20742
  ) && transfer1.status === transfer2.status && transfer1.totalValue === transfer2.totalValue && transfer1.expiryTime?.getTime() === transfer2.expiryTime?.getTime() && transfer1.leaves.length === transfer2.leaves.length;
@@ -20838,7 +20979,7 @@ var TransferService = class extends BaseTransferService {
20838
20979
  }
20839
20980
  const nodeTx = getTxFromRawTxBytes(leaf.leaf.nodeTx);
20840
20981
  const nodeOutPoint = {
20841
- txid: (0, import_utils8.hexToBytes)(getTxId(nodeTx)),
20982
+ txid: (0, import_utils9.hexToBytes)(getTxId(nodeTx)),
20842
20983
  index: 0
20843
20984
  };
20844
20985
  const currRefundTx = getTxFromRawTxBytes(leaf.leaf.refundTx);
@@ -20954,7 +21095,7 @@ var TransferService = class extends BaseTransferService {
20954
21095
  throw new Error(`Share not found for operator ${operator.id}`);
20955
21096
  }
20956
21097
  const pubkeyTweak = import_secp256k18.secp256k1.getPublicKey(
20957
- (0, import_utils8.numberToBytesBE)(share.share, 32)
21098
+ (0, import_utils9.numberToBytesBE)(share.share, 32)
20958
21099
  );
20959
21100
  pubkeySharesTweak.set(identifier, pubkeyTweak);
20960
21101
  }
@@ -20967,7 +21108,7 @@ var TransferService = class extends BaseTransferService {
20967
21108
  leafTweaksMap.set(identifier, {
20968
21109
  leafId: leaf.leaf.id,
20969
21110
  secretShareTweak: {
20970
- secretShare: (0, import_utils8.numberToBytesBE)(share.share, 32),
21111
+ secretShare: (0, import_utils9.numberToBytesBE)(share.share, 32),
20971
21112
  proofs: share.proofs
20972
21113
  },
20973
21114
  pubkeySharesTweak: Object.fromEntries(pubkeySharesTweak)
@@ -21257,7 +21398,7 @@ var TransferService = class extends BaseTransferService {
21257
21398
  const refundTx = getTxFromRawTxBytes(node.refundTx);
21258
21399
  const refundSequence = refundTx.getInput(0).sequence || 0;
21259
21400
  const newNodeOutPoint = {
21260
- txid: (0, import_utils8.hexToBytes)(getTxId(nodeTx)),
21401
+ txid: (0, import_utils9.hexToBytes)(getTxId(nodeTx)),
21261
21402
  index: 0
21262
21403
  };
21263
21404
  const { nextSequence: newNodeSequence } = getNextTransactionSequence(refundSequence);
@@ -21277,7 +21418,7 @@ var TransferService = class extends BaseTransferService {
21277
21418
  });
21278
21419
  newNodeTx.addOutput(getEphemeralAnchorOutput());
21279
21420
  const newRefundOutPoint = {
21280
- txid: (0, import_utils8.hexToBytes)(getTxId(newNodeTx)),
21421
+ txid: (0, import_utils9.hexToBytes)(getTxId(newNodeTx)),
21281
21422
  index: 0
21282
21423
  };
21283
21424
  const amountSats = refundTx.getOutput(0).amount;
@@ -21478,7 +21619,7 @@ var CoopExitService = class extends BaseTransferService {
21478
21619
  connectorOutputs,
21479
21620
  receiverPubKey
21480
21621
  );
21481
- const transferTweak = await this.sendTransferTweakKey(
21622
+ const transferTweak = await this.deliverTransferPackage(
21482
21623
  transfer,
21483
21624
  leaves,
21484
21625
  signaturesMap
@@ -21624,10 +21765,10 @@ var CoopExitService = class extends BaseTransferService {
21624
21765
  init_buffer();
21625
21766
  var import_secp256k19 = require("@noble/curves/secp256k1");
21626
21767
  var import_sha28 = require("@noble/hashes/sha2");
21627
- var import_utils9 = require("@noble/hashes/utils");
21768
+ var import_utils10 = require("@noble/hashes/utils");
21628
21769
  var btc3 = __toESM(require("@scure/btc-signer"), 1);
21629
21770
  var import_btc_signer4 = require("@scure/btc-signer");
21630
- var import_utils10 = require("@scure/btc-signer/utils");
21771
+ var import_utils11 = require("@scure/btc-signer/utils");
21631
21772
 
21632
21773
  // src/utils/proof.ts
21633
21774
  init_buffer();
@@ -21695,7 +21836,7 @@ var DepositService = class {
21695
21836
  if (operator.identifier === this.config.getCoordinatorIdentifier()) {
21696
21837
  continue;
21697
21838
  }
21698
- const operatorPubkey2 = (0, import_utils9.hexToBytes)(operator.identityPublicKey);
21839
+ const operatorPubkey2 = (0, import_utils10.hexToBytes)(operator.identityPublicKey);
21699
21840
  const operatorSig = address2.depositAddressProof.addressSignatures[operator.identifier];
21700
21841
  if (!operatorSig) {
21701
21842
  throw new ValidationError("Operator signature not found", {
@@ -21871,7 +22012,7 @@ var DepositService = class {
21871
22012
  }
21872
22013
  );
21873
22014
  }
21874
- if (!(0, import_utils10.equalBytes)(treeResp.rootNodeSignatureShares.verifyingKey, verifyingKey)) {
22015
+ if (!(0, import_utils11.equalBytes)(treeResp.rootNodeSignatureShares.verifyingKey, verifyingKey)) {
21875
22016
  throw new ValidationError("Verifying key mismatch", {
21876
22017
  field: "verifyingKey",
21877
22018
  value: treeResp.rootNodeSignatureShares.verifyingKey,
@@ -21947,7 +22088,7 @@ var DepositService = class {
21947
22088
 
21948
22089
  // src/services/lightning.ts
21949
22090
  init_buffer();
21950
- var import_utils11 = require("@noble/curves/abstract/utils");
22091
+ var import_utils12 = require("@noble/curves/abstract/utils");
21951
22092
  var import_secp256k111 = require("@noble/curves/secp256k1");
21952
22093
  var import_sha210 = require("@noble/hashes/sha2");
21953
22094
  var import_uuidv73 = require("uuidv7");
@@ -22148,8 +22289,8 @@ var LightningService = class {
22148
22289
  descriptionHash
22149
22290
  }) {
22150
22291
  const randBytes = crypto2.getRandomValues(new Uint8Array(32));
22151
- const preimage = (0, import_utils11.numberToBytesBE)(
22152
- (0, import_utils11.bytesToNumberBE)(randBytes) % import_secp256k111.secp256k1.CURVE.n,
22292
+ const preimage = (0, import_utils12.numberToBytesBE)(
22293
+ (0, import_utils12.bytesToNumberBE)(randBytes) % import_secp256k111.secp256k1.CURVE.n,
22153
22294
  32
22154
22295
  );
22155
22296
  return await this.createLightningInvoiceWithPreImage({
@@ -22204,12 +22345,12 @@ var LightningService = class {
22204
22345
  const sparkClient = await this.connectionManager.createSparkClient(
22205
22346
  operator.address
22206
22347
  );
22207
- const userIdentityPublicKey = receiverIdentityPubkey ? (0, import_utils11.hexToBytes)(receiverIdentityPubkey) : await this.config.signer.getIdentityPublicKey();
22348
+ const userIdentityPublicKey = receiverIdentityPubkey ? (0, import_utils12.hexToBytes)(receiverIdentityPubkey) : await this.config.signer.getIdentityPublicKey();
22208
22349
  try {
22209
22350
  await sparkClient.store_preimage_share({
22210
22351
  paymentHash,
22211
22352
  preimageShare: {
22212
- secretShare: (0, import_utils11.numberToBytesBE)(share.share, 32),
22353
+ secretShare: (0, import_utils12.numberToBytesBE)(share.share, 32),
22213
22354
  proofs: share.proofs
22214
22355
  },
22215
22356
  threshold: this.config.getThreshold(),
@@ -22241,7 +22382,8 @@ var LightningService = class {
22241
22382
  paymentHash,
22242
22383
  invoiceString,
22243
22384
  isInboundPayment,
22244
- feeSats = 0
22385
+ feeSats = 0,
22386
+ amountSatsToSend
22245
22387
  }) {
22246
22388
  const sparkClient = await this.connectionManager.createSparkClient(
22247
22389
  this.config.getCoordinatorAddress()
@@ -22278,7 +22420,25 @@ var LightningService = class {
22278
22420
  } catch (error) {
22279
22421
  console.error("Error decoding invoice", error);
22280
22422
  }
22281
- amountSats = amountMsats / 1e3;
22423
+ const isZeroAmountInvoice = !amountMsats;
22424
+ if (isZeroAmountInvoice && amountSatsToSend === void 0) {
22425
+ throw new ValidationError(
22426
+ "Invalid amount. User must specify amountSatsToSend for 0 amount lightning invoice",
22427
+ {
22428
+ field: "amountSatsToSend",
22429
+ value: amountSatsToSend,
22430
+ expected: "positive number"
22431
+ }
22432
+ );
22433
+ }
22434
+ amountSats = isZeroAmountInvoice ? amountSatsToSend : amountMsats / 1e3;
22435
+ if (isNaN(amountSats) || amountSats <= 0) {
22436
+ throw new ValidationError("Invalid amount", {
22437
+ field: "amountSats",
22438
+ value: amountSats,
22439
+ expected: "greater than 0"
22440
+ });
22441
+ }
22282
22442
  bolt11String = invoiceString;
22283
22443
  }
22284
22444
  const reason = isInboundPayment ? 1 /* REASON_RECEIVE */ : 0 /* REASON_SEND */;
@@ -22379,7 +22539,7 @@ var LightningService = class {
22379
22539
 
22380
22540
  // src/services/lrc-connection.ts
22381
22541
  init_buffer();
22382
- var import_core11 = require("@lightsparkdev/core");
22542
+ var import_core13 = require("@lightsparkdev/core");
22383
22543
  var import_nice_grpc_client_middleware_retry2 = require("nice-grpc-client-middleware-retry");
22384
22544
  var import_nice_grpc_common3 = require("nice-grpc-common");
22385
22545
 
@@ -25452,7 +25612,7 @@ var Lrc20ConnectionManager = class {
25452
25612
  }
25453
25613
  async createChannelWithTLS(address2, certPath) {
25454
25614
  try {
25455
- if (import_core11.isNode && !isBun) {
25615
+ if (import_core13.isNode && !isBun) {
25456
25616
  const grpcModule = await import("nice-grpc");
25457
25617
  const { ChannelCredentials, createChannel } = "default" in grpcModule ? grpcModule.default : grpcModule;
25458
25618
  if (certPath) {
@@ -25519,7 +25679,7 @@ var Lrc20ConnectionManager = class {
25519
25679
  return client;
25520
25680
  }
25521
25681
  createMiddleware() {
25522
- if (import_core11.isNode) {
25682
+ if (import_core13.isNode) {
25523
25683
  return this.createNodeMiddleware();
25524
25684
  } else {
25525
25685
  return this.createBrowserMiddleware();
@@ -25529,7 +25689,7 @@ var Lrc20ConnectionManager = class {
25529
25689
  return async function* (call, options) {
25530
25690
  return yield* call.next(call.request, {
25531
25691
  ...options,
25532
- metadata: (0, import_nice_grpc_common3.Metadata)(options.metadata).set("User-Agent", "spark-js-sdk")
25692
+ metadata: (0, import_nice_grpc_common3.Metadata)(options.metadata).set("X-Client-Env", clientEnv)
25533
25693
  });
25534
25694
  }.bind(this);
25535
25695
  }
@@ -25537,7 +25697,7 @@ var Lrc20ConnectionManager = class {
25537
25697
  return async function* (call, options) {
25538
25698
  return yield* call.next(call.request, {
25539
25699
  ...options,
25540
- metadata: (0, import_nice_grpc_common3.Metadata)(options.metadata).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("Content-Type", "application/grpc-web+proto").set("User-Agent", "spark-js-sdk")
25700
+ metadata: (0, import_nice_grpc_common3.Metadata)(options.metadata).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("Content-Type", "application/grpc-web+proto").set("X-Client-Env", clientEnv)
25541
25701
  });
25542
25702
  }.bind(this);
25543
25703
  }
@@ -25549,7 +25709,7 @@ var Lrc20ConnectionManager = class {
25549
25709
  };
25550
25710
  let options = {};
25551
25711
  const isNodeChannel = "close" in channel;
25552
- if (import_core11.isNode && isNodeChannel && !isBun) {
25712
+ if (import_core13.isNode && isNodeChannel && !isBun) {
25553
25713
  const grpcModule = await import("nice-grpc");
25554
25714
  const { openTelemetryClientMiddleware } = await import("nice-grpc-opentelemetry");
25555
25715
  const { createClientFactory } = "default" in grpcModule ? grpcModule.default : grpcModule;
@@ -25594,13 +25754,26 @@ var Lrc20ConnectionManager = class {
25594
25754
 
25595
25755
  // src/services/token-transactions.ts
25596
25756
  init_buffer();
25597
- var import_utils15 = require("@noble/curves/abstract/utils");
25757
+ var import_utils16 = require("@noble/curves/abstract/utils");
25598
25758
  var import_secp256k114 = require("@noble/curves/secp256k1");
25599
25759
 
25600
25760
  // src/utils/token-hashing.ts
25601
25761
  init_buffer();
25602
25762
  var import_sha211 = require("@noble/hashes/sha2");
25603
25763
  function hashTokenTransaction(tokenTransaction, partialHash = false) {
25764
+ switch (tokenTransaction.version) {
25765
+ case 0:
25766
+ return hashTokenTransactionV0(tokenTransaction, partialHash);
25767
+ case 1:
25768
+ return hashTokenTransactionV1(tokenTransaction, partialHash);
25769
+ default:
25770
+ throw new ValidationError("invalid token transaction version", {
25771
+ field: "tokenTransaction.version",
25772
+ value: tokenTransaction.version
25773
+ });
25774
+ }
25775
+ }
25776
+ function hashTokenTransactionV0(tokenTransaction, partialHash = false) {
25604
25777
  if (!tokenTransaction) {
25605
25778
  throw new ValidationError("token transaction cannot be nil", {
25606
25779
  field: "tokenTransaction"
@@ -25848,6 +26021,275 @@ function hashTokenTransaction(tokenTransaction, partialHash = false) {
25848
26021
  finalHashObj.update(concatenatedHashes);
25849
26022
  return finalHashObj.digest();
25850
26023
  }
26024
+ function hashTokenTransactionV1(tokenTransaction, partialHash = false) {
26025
+ if (!tokenTransaction) {
26026
+ throw new ValidationError("token transaction cannot be nil", {
26027
+ field: "tokenTransaction"
26028
+ });
26029
+ }
26030
+ let allHashes = [];
26031
+ const versionHashObj = import_sha211.sha256.create();
26032
+ const versionBytes = new Uint8Array(4);
26033
+ new DataView(versionBytes.buffer).setUint32(
26034
+ 0,
26035
+ tokenTransaction.version,
26036
+ false
26037
+ // false for big-endian
26038
+ );
26039
+ versionHashObj.update(versionBytes);
26040
+ allHashes.push(versionHashObj.digest());
26041
+ if (tokenTransaction.tokenInputs?.$case === "transferInput") {
26042
+ if (!tokenTransaction.tokenInputs.transferInput.outputsToSpend) {
26043
+ throw new ValidationError("outputs to spend cannot be null", {
26044
+ field: "tokenInputs.transferInput.outputsToSpend"
26045
+ });
26046
+ }
26047
+ if (tokenTransaction.tokenInputs.transferInput.outputsToSpend.length === 0) {
26048
+ throw new ValidationError("outputs to spend cannot be empty", {
26049
+ field: "tokenInputs.transferInput.outputsToSpend"
26050
+ });
26051
+ }
26052
+ for (const [
26053
+ i,
26054
+ output
26055
+ ] of tokenTransaction.tokenInputs.transferInput.outputsToSpend.entries()) {
26056
+ if (!output) {
26057
+ throw new ValidationError(`output cannot be null at index ${i}`, {
26058
+ field: `tokenInputs.transferInput.outputsToSpend[${i}]`,
26059
+ index: i
26060
+ });
26061
+ }
26062
+ const hashObj2 = import_sha211.sha256.create();
26063
+ if (output.prevTokenTransactionHash) {
26064
+ const prevHash = output.prevTokenTransactionHash;
26065
+ if (output.prevTokenTransactionHash.length !== 32) {
26066
+ throw new ValidationError(
26067
+ `invalid previous transaction hash length at index ${i}`,
26068
+ {
26069
+ field: `tokenInputs.transferInput.outputsToSpend[${i}].prevTokenTransactionHash`,
26070
+ value: prevHash,
26071
+ expectedLength: 32,
26072
+ actualLength: prevHash.length,
26073
+ index: i
26074
+ }
26075
+ );
26076
+ }
26077
+ hashObj2.update(output.prevTokenTransactionHash);
26078
+ }
26079
+ const voutBytes = new Uint8Array(4);
26080
+ new DataView(voutBytes.buffer).setUint32(
26081
+ 0,
26082
+ output.prevTokenTransactionVout,
26083
+ false
26084
+ );
26085
+ hashObj2.update(voutBytes);
26086
+ allHashes.push(hashObj2.digest());
26087
+ }
26088
+ }
26089
+ if (tokenTransaction.tokenInputs?.$case === "mintInput") {
26090
+ const hashObj2 = import_sha211.sha256.create();
26091
+ if (tokenTransaction.tokenInputs.mintInput.issuerPublicKey) {
26092
+ const issuerPubKey = tokenTransaction.tokenInputs.mintInput.issuerPublicKey;
26093
+ if (issuerPubKey.length === 0) {
26094
+ throw new ValidationError("issuer public key cannot be empty", {
26095
+ field: "tokenInputs.mintInput.issuerPublicKey",
26096
+ value: issuerPubKey,
26097
+ expectedLength: 1,
26098
+ actualLength: 0
26099
+ });
26100
+ }
26101
+ hashObj2.update(issuerPubKey);
26102
+ if (tokenTransaction.tokenInputs.mintInput.issuerProvidedTimestamp != 0) {
26103
+ const timestampBytes = new Uint8Array(8);
26104
+ new DataView(timestampBytes.buffer).setBigUint64(
26105
+ 0,
26106
+ BigInt(
26107
+ tokenTransaction.tokenInputs.mintInput.issuerProvidedTimestamp
26108
+ ),
26109
+ true
26110
+ // true for little-endian to match Go implementation
26111
+ );
26112
+ hashObj2.update(timestampBytes);
26113
+ }
26114
+ allHashes.push(hashObj2.digest());
26115
+ }
26116
+ }
26117
+ if (!tokenTransaction.tokenOutputs) {
26118
+ throw new ValidationError("token outputs cannot be null", {
26119
+ field: "tokenOutputs"
26120
+ });
26121
+ }
26122
+ if (tokenTransaction.tokenOutputs.length === 0) {
26123
+ throw new ValidationError("token outputs cannot be empty", {
26124
+ field: "tokenOutputs"
26125
+ });
26126
+ }
26127
+ for (const [i, output] of tokenTransaction.tokenOutputs.entries()) {
26128
+ if (!output) {
26129
+ throw new ValidationError(`output cannot be null at index ${i}`, {
26130
+ field: `tokenOutputs[${i}]`,
26131
+ index: i
26132
+ });
26133
+ }
26134
+ const hashObj2 = import_sha211.sha256.create();
26135
+ if (output.id && !partialHash) {
26136
+ if (output.id.length === 0) {
26137
+ throw new ValidationError(`output ID at index ${i} cannot be empty`, {
26138
+ field: `tokenOutputs[${i}].id`,
26139
+ index: i
26140
+ });
26141
+ }
26142
+ hashObj2.update(new TextEncoder().encode(output.id));
26143
+ }
26144
+ if (output.ownerPublicKey) {
26145
+ if (output.ownerPublicKey.length === 0) {
26146
+ throw new ValidationError(
26147
+ `owner public key at index ${i} cannot be empty`,
26148
+ {
26149
+ field: `tokenOutputs[${i}].ownerPublicKey`,
26150
+ index: i
26151
+ }
26152
+ );
26153
+ }
26154
+ hashObj2.update(output.ownerPublicKey);
26155
+ }
26156
+ if (!partialHash) {
26157
+ const revPubKey = output.revocationCommitment;
26158
+ if (revPubKey) {
26159
+ if (revPubKey.length === 0) {
26160
+ throw new ValidationError(
26161
+ `revocation commitment at index ${i} cannot be empty`,
26162
+ {
26163
+ field: `tokenOutputs[${i}].revocationCommitment`,
26164
+ index: i
26165
+ }
26166
+ );
26167
+ }
26168
+ hashObj2.update(revPubKey);
26169
+ }
26170
+ const bondBytes = new Uint8Array(8);
26171
+ new DataView(bondBytes.buffer).setBigUint64(
26172
+ 0,
26173
+ BigInt(output.withdrawBondSats),
26174
+ false
26175
+ );
26176
+ hashObj2.update(bondBytes);
26177
+ const locktimeBytes = new Uint8Array(8);
26178
+ new DataView(locktimeBytes.buffer).setBigUint64(
26179
+ 0,
26180
+ BigInt(output.withdrawRelativeBlockLocktime),
26181
+ false
26182
+ );
26183
+ hashObj2.update(locktimeBytes);
26184
+ }
26185
+ if (output.tokenPublicKey) {
26186
+ if (output.tokenPublicKey.length === 0) {
26187
+ throw new ValidationError(
26188
+ `token public key at index ${i} cannot be empty`,
26189
+ {
26190
+ field: `tokenOutputs[${i}].tokenPublicKey`,
26191
+ index: i
26192
+ }
26193
+ );
26194
+ }
26195
+ hashObj2.update(output.tokenPublicKey);
26196
+ }
26197
+ if (output.tokenAmount) {
26198
+ if (output.tokenAmount.length === 0) {
26199
+ throw new ValidationError(
26200
+ `token amount at index ${i} cannot be empty`,
26201
+ {
26202
+ field: `tokenOutputs[${i}].tokenAmount`,
26203
+ index: i
26204
+ }
26205
+ );
26206
+ }
26207
+ if (output.tokenAmount.length > 16) {
26208
+ throw new ValidationError(
26209
+ `token amount at index ${i} exceeds maximum length`,
26210
+ {
26211
+ field: `tokenOutputs[${i}].tokenAmount`,
26212
+ value: output.tokenAmount,
26213
+ expectedLength: 16,
26214
+ actualLength: output.tokenAmount.length,
26215
+ index: i
26216
+ }
26217
+ );
26218
+ }
26219
+ hashObj2.update(output.tokenAmount);
26220
+ }
26221
+ allHashes.push(hashObj2.digest());
26222
+ }
26223
+ if (!tokenTransaction.sparkOperatorIdentityPublicKeys) {
26224
+ throw new ValidationError(
26225
+ "spark operator identity public keys cannot be null",
26226
+ {}
26227
+ );
26228
+ }
26229
+ const sortedPubKeys = [
26230
+ ...tokenTransaction.sparkOperatorIdentityPublicKeys || []
26231
+ ].sort((a, b) => {
26232
+ for (let i = 0; i < a.length && i < b.length; i++) {
26233
+ if (a[i] !== b[i]) return a[i] - b[i];
26234
+ }
26235
+ return a.length - b.length;
26236
+ });
26237
+ for (const [i, pubKey] of sortedPubKeys.entries()) {
26238
+ if (!pubKey) {
26239
+ throw new ValidationError(
26240
+ `operator public key at index ${i} cannot be null`,
26241
+ {
26242
+ field: `sparkOperatorIdentityPublicKeys[${i}]`,
26243
+ index: i
26244
+ }
26245
+ );
26246
+ }
26247
+ if (pubKey.length === 0) {
26248
+ throw new ValidationError(
26249
+ `operator public key at index ${i} cannot be empty`,
26250
+ {
26251
+ field: `sparkOperatorIdentityPublicKeys[${i}]`,
26252
+ index: i
26253
+ }
26254
+ );
26255
+ }
26256
+ const hashObj2 = import_sha211.sha256.create();
26257
+ hashObj2.update(pubKey);
26258
+ allHashes.push(hashObj2.digest());
26259
+ }
26260
+ const hashObj = import_sha211.sha256.create();
26261
+ let networkBytes = new Uint8Array(4);
26262
+ new DataView(networkBytes.buffer).setUint32(
26263
+ 0,
26264
+ tokenTransaction.network.valueOf(),
26265
+ false
26266
+ // false for big-endian
26267
+ );
26268
+ hashObj.update(networkBytes);
26269
+ allHashes.push(hashObj.digest());
26270
+ const expiryHashObj = import_sha211.sha256.create();
26271
+ const validityDurationBytes = new Uint8Array(8);
26272
+ const expiryUnixTime = tokenTransaction.expiryTime ? Math.floor(tokenTransaction.expiryTime.getTime() / 1e3) : 0;
26273
+ new DataView(validityDurationBytes.buffer).setBigUint64(
26274
+ 0,
26275
+ BigInt(expiryUnixTime),
26276
+ false
26277
+ // false for big-endian
26278
+ );
26279
+ expiryHashObj.update(validityDurationBytes);
26280
+ allHashes.push(expiryHashObj.digest());
26281
+ const finalHashObj = import_sha211.sha256.create();
26282
+ const concatenatedHashes = new Uint8Array(
26283
+ allHashes.reduce((sum, hash) => sum + hash.length, 0)
26284
+ );
26285
+ let offset = 0;
26286
+ for (const hash of allHashes) {
26287
+ concatenatedHashes.set(hash, offset);
26288
+ offset += hash.length;
26289
+ }
26290
+ finalHashObj.update(concatenatedHashes);
26291
+ return finalHashObj.digest();
26292
+ }
25851
26293
  function hashOperatorSpecificTokenTransactionSignablePayload(payload) {
25852
26294
  if (!payload) {
25853
26295
  throw new ValidationError(
@@ -25899,15 +26341,15 @@ function hashOperatorSpecificTokenTransactionSignablePayload(payload) {
25899
26341
 
25900
26342
  // src/utils/token-transactions.ts
25901
26343
  init_buffer();
25902
- var import_utils12 = require("@noble/curves/abstract/utils");
26344
+ var import_utils13 = require("@noble/curves/abstract/utils");
25903
26345
  function calculateAvailableTokenAmount(outputLeaves) {
25904
26346
  return outputLeaves.reduce(
25905
- (sum, output) => sum + BigInt((0, import_utils12.bytesToNumberBE)(output.output.tokenAmount)),
26347
+ (sum, output) => sum + BigInt((0, import_utils13.bytesToNumberBE)(output.output.tokenAmount)),
25906
26348
  BigInt(0)
25907
26349
  );
25908
26350
  }
25909
26351
  function checkIfSelectedOutputsAreAvailable(selectedOutputs, tokenOutputs, tokenPublicKey) {
25910
- const tokenPubKeyHex = (0, import_utils12.bytesToHex)(tokenPublicKey);
26352
+ const tokenPubKeyHex = (0, import_utils13.bytesToHex)(tokenPublicKey);
25911
26353
  const tokenOutputsAvailable = tokenOutputs.get(tokenPubKeyHex);
25912
26354
  if (!tokenOutputsAvailable) {
25913
26355
  return false;
@@ -26193,7 +26635,7 @@ function validateTokenTransaction(finalTokenTransaction, partialTokenTransaction
26193
26635
  }
26194
26636
 
26195
26637
  // src/services/token-transactions.ts
26196
- var import_utils16 = require("@noble/hashes/utils");
26638
+ var import_utils17 = require("@noble/hashes/utils");
26197
26639
 
26198
26640
  // src/address/index.ts
26199
26641
  init_buffer();
@@ -26201,10 +26643,10 @@ init_buffer();
26201
26643
  // src/address/address.ts
26202
26644
  init_buffer();
26203
26645
  var import_secp256k112 = require("@noble/curves/secp256k1");
26204
- var import_utils13 = require("@noble/hashes/utils");
26646
+ var import_utils14 = require("@noble/hashes/utils");
26205
26647
  var import_base3 = require("@scure/base");
26206
26648
  var import_uuidv74 = require("uuidv7");
26207
- var import_utils14 = require("@noble/curves/abstract/utils");
26649
+ var import_utils15 = require("@noble/curves/abstract/utils");
26208
26650
  var AddressNetwork = {
26209
26651
  MAINNET: "sp",
26210
26652
  TESTNET: "spt",
@@ -26220,7 +26662,7 @@ function encodeSparkAddress(payload) {
26220
26662
  paymentIntentFields = payload.paymentIntentFields;
26221
26663
  }
26222
26664
  const sparkAddressProto = SparkAddress.create({
26223
- identityPublicKey: (0, import_utils13.hexToBytes)(payload.identityPublicKey),
26665
+ identityPublicKey: (0, import_utils14.hexToBytes)(payload.identityPublicKey),
26224
26666
  paymentIntentFields
26225
26667
  });
26226
26668
  const serializedPayload = SparkAddress.encode(sparkAddressProto).finish();
@@ -26252,7 +26694,7 @@ function decodeSparkAddress(address2, network) {
26252
26694
  });
26253
26695
  }
26254
26696
  const payload = SparkAddress.decode(import_base3.bech32m.fromWords(decoded.words));
26255
- const publicKey = (0, import_utils13.bytesToHex)(payload.identityPublicKey);
26697
+ const publicKey = (0, import_utils14.bytesToHex)(payload.identityPublicKey);
26256
26698
  isValidPublicKey(publicKey);
26257
26699
  const paymentIntentFields = payload.paymentIntentFields;
26258
26700
  return {
@@ -26260,8 +26702,8 @@ function decodeSparkAddress(address2, network) {
26260
26702
  network,
26261
26703
  paymentIntentFields: paymentIntentFields && {
26262
26704
  id: import_uuidv74.UUID.ofInner(paymentIntentFields.id).toString(),
26263
- assetIdentifier: paymentIntentFields.assetIdentifier ? (0, import_utils13.bytesToHex)(paymentIntentFields.assetIdentifier) : void 0,
26264
- assetAmount: (0, import_utils14.bytesToNumberBE)(paymentIntentFields.assetAmount),
26705
+ assetIdentifier: paymentIntentFields.assetIdentifier ? (0, import_utils14.bytesToHex)(paymentIntentFields.assetIdentifier) : void 0,
26706
+ assetAmount: (0, import_utils15.bytesToNumberBE)(paymentIntentFields.assetAmount),
26265
26707
  memo: paymentIntentFields.memo
26266
26708
  }
26267
26709
  };
@@ -26362,7 +26804,7 @@ var TokenTransactionService = class {
26362
26804
  if (!checkIfSelectedOutputsAreAvailable(
26363
26805
  outputsToUse,
26364
26806
  tokenOutputs,
26365
- (0, import_utils16.hexToBytes)(receiverOutputs[0].tokenPublicKey)
26807
+ (0, import_utils17.hexToBytes)(receiverOutputs[0].tokenPublicKey)
26366
26808
  )) {
26367
26809
  throw new ValidationError(
26368
26810
  "One or more selected TTXOs are not available",
@@ -26403,8 +26845,8 @@ var TokenTransactionService = class {
26403
26845
  this.config.getNetworkType()
26404
26846
  );
26405
26847
  return {
26406
- receiverSparkAddress: (0, import_utils16.hexToBytes)(receiverAddress.identityPublicKey),
26407
- tokenPublicKey: (0, import_utils16.hexToBytes)(transfer.tokenPublicKey),
26848
+ receiverSparkAddress: (0, import_utils17.hexToBytes)(receiverAddress.identityPublicKey),
26849
+ tokenPublicKey: (0, import_utils17.hexToBytes)(transfer.tokenPublicKey),
26408
26850
  tokenAmount: transfer.tokenAmount
26409
26851
  };
26410
26852
  });
@@ -26436,7 +26878,7 @@ var TokenTransactionService = class {
26436
26878
  const tokenOutputs = tokenOutputData.map((output) => ({
26437
26879
  ownerPublicKey: output.receiverSparkAddress,
26438
26880
  tokenPublicKey: output.tokenPublicKey,
26439
- tokenAmount: (0, import_utils15.numberToBytesBE)(output.tokenAmount, 16)
26881
+ tokenAmount: (0, import_utils16.numberToBytesBE)(output.tokenAmount, 16)
26440
26882
  }));
26441
26883
  if (availableTokenAmount > totalRequestedAmount) {
26442
26884
  const changeAmount = availableTokenAmount - totalRequestedAmount;
@@ -26444,7 +26886,7 @@ var TokenTransactionService = class {
26444
26886
  tokenOutputs.push({
26445
26887
  ownerPublicKey: await this.config.signer.getIdentityPublicKey(),
26446
26888
  tokenPublicKey: firstTokenPublicKey,
26447
- tokenAmount: (0, import_utils15.numberToBytesBE)(changeAmount, 16)
26889
+ tokenAmount: (0, import_utils16.numberToBytesBE)(changeAmount, 16)
26448
26890
  });
26449
26891
  }
26450
26892
  return {
@@ -26471,7 +26913,7 @@ var TokenTransactionService = class {
26471
26913
  const tokenOutputs = tokenOutputData.map((output) => ({
26472
26914
  ownerPublicKey: output.receiverSparkAddress,
26473
26915
  tokenPublicKey: output.tokenPublicKey,
26474
- tokenAmount: (0, import_utils15.numberToBytesBE)(output.tokenAmount, 16)
26916
+ tokenAmount: (0, import_utils16.numberToBytesBE)(output.tokenAmount, 16)
26475
26917
  }));
26476
26918
  if (availableTokenAmount > totalRequestedAmount) {
26477
26919
  const changeAmount = availableTokenAmount - totalRequestedAmount;
@@ -26479,7 +26921,7 @@ var TokenTransactionService = class {
26479
26921
  tokenOutputs.push({
26480
26922
  ownerPublicKey: await this.config.signer.getIdentityPublicKey(),
26481
26923
  tokenPublicKey: firstTokenPublicKey,
26482
- tokenAmount: (0, import_utils15.numberToBytesBE)(changeAmount, 16)
26924
+ tokenAmount: (0, import_utils16.numberToBytesBE)(changeAmount, 16)
26483
26925
  });
26484
26926
  }
26485
26927
  return {
@@ -26504,7 +26946,7 @@ var TokenTransactionService = class {
26504
26946
  for (const [_, operator] of Object.entries(
26505
26947
  this.config.getSigningOperators()
26506
26948
  )) {
26507
- operatorKeys.push((0, import_utils16.hexToBytes)(operator.identityPublicKey));
26949
+ operatorKeys.push((0, import_utils17.hexToBytes)(operator.identityPublicKey));
26508
26950
  }
26509
26951
  return operatorKeys;
26510
26952
  }
@@ -26588,7 +27030,7 @@ var TokenTransactionService = class {
26588
27030
  {
26589
27031
  field: "revocationCommitment",
26590
27032
  value: derivedRevocationCommitment,
26591
- expected: (0, import_utils15.bytesToHex)(outputsToSpendCommitments[outputIndex]),
27033
+ expected: (0, import_utils16.bytesToHex)(outputsToSpendCommitments[outputIndex]),
26592
27034
  outputIndex
26593
27035
  }
26594
27036
  )
@@ -26614,7 +27056,7 @@ var TokenTransactionService = class {
26614
27056
  threshold
26615
27057
  );
26616
27058
  }
26617
- return (0, import_utils15.bytesToHex)(finalTokenTransactionHash);
27059
+ return (0, import_utils16.bytesToHex)(finalTokenTransactionHash);
26618
27060
  }
26619
27061
  async broadcastTokenTransactionV1(tokenTransaction, signingOperators, outputsToSpendSigningPublicKeys, outputsToSpendCommitments) {
26620
27062
  const { finalTokenTransaction, finalTokenTransactionHash, threshold } = await this.startTokenTransaction(
@@ -26628,13 +27070,13 @@ var TokenTransactionService = class {
26628
27070
  finalTokenTransactionHash,
26629
27071
  signingOperators
26630
27072
  );
26631
- return (0, import_utils15.bytesToHex)(finalTokenTransactionHash);
27073
+ return (0, import_utils16.bytesToHex)(finalTokenTransactionHash);
26632
27074
  }
26633
27075
  async startTokenTransactionV0(tokenTransaction, signingOperators, outputsToSpendSigningPublicKeys, outputsToSpendCommitments) {
26634
27076
  const sparkClient = await this.connectionManager.createSparkClient(
26635
27077
  this.config.getCoordinatorAddress()
26636
27078
  );
26637
- const partialTokenTransactionHash = hashTokenTransaction(
27079
+ const partialTokenTransactionHash = hashTokenTransactionV0(
26638
27080
  tokenTransaction,
26639
27081
  true
26640
27082
  );
@@ -26715,7 +27157,7 @@ var TokenTransactionService = class {
26715
27157
  this.config.getThreshold()
26716
27158
  );
26717
27159
  const finalTokenTransaction = startResponse.finalTokenTransaction;
26718
- const finalTokenTransactionHash = hashTokenTransaction(
27160
+ const finalTokenTransactionHash = hashTokenTransactionV0(
26719
27161
  finalTokenTransaction,
26720
27162
  false
26721
27163
  );
@@ -26783,7 +27225,9 @@ var TokenTransactionService = class {
26783
27225
  const startResponse = await sparkClient.start_transaction(
26784
27226
  {
26785
27227
  identityPublicKey: await this.config.signer.getIdentityPublicKey(),
26786
- partialTokenTransaction: tokenTransaction
27228
+ partialTokenTransaction: tokenTransaction,
27229
+ validityDurationSeconds: await this.config.getTokenValidityDurationSeconds(),
27230
+ partialTokenTransactionOwnerSignatures: ownerSignaturesWithIndex
26787
27231
  },
26788
27232
  {
26789
27233
  retry: true,
@@ -26825,7 +27269,7 @@ var TokenTransactionService = class {
26825
27269
  const identityPublicKey = await this.config.signer.getIdentityPublicKey();
26826
27270
  const payload = {
26827
27271
  finalTokenTransactionHash,
26828
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27272
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
26829
27273
  };
26830
27274
  const payloadHash = await hashOperatorSpecificTokenTransactionSignablePayload(payload);
26831
27275
  let operatorSpecificSignatures = [];
@@ -26982,7 +27426,7 @@ var TokenTransactionService = class {
26982
27426
  []
26983
27427
  );
26984
27428
  unsortedTokenOutputs.forEach((output) => {
26985
- const tokenKey = (0, import_utils15.bytesToHex)(output.output.tokenPublicKey);
27429
+ const tokenKey = (0, import_utils16.bytesToHex)(output.output.tokenPublicKey);
26986
27430
  const index = output.previousTransactionVout;
26987
27431
  tokenOutputs.set(tokenKey, [
26988
27432
  { ...output, previousTransactionVout: index }
@@ -26998,7 +27442,7 @@ var TokenTransactionService = class {
26998
27442
  });
26999
27443
  }
27000
27444
  const exactMatch = tokenOutputs.find(
27001
- (item) => (0, import_utils15.bytesToNumberBE)(item.output.tokenAmount) === tokenAmount
27445
+ (item) => (0, import_utils16.bytesToNumberBE)(item.output.tokenAmount) === tokenAmount
27002
27446
  );
27003
27447
  if (exactMatch) {
27004
27448
  return [exactMatch];
@@ -27009,7 +27453,7 @@ var TokenTransactionService = class {
27009
27453
  for (const outputWithPreviousTransactionData of tokenOutputs) {
27010
27454
  if (remainingAmount <= 0n) break;
27011
27455
  selectedOutputs.push(outputWithPreviousTransactionData);
27012
- remainingAmount -= (0, import_utils15.bytesToNumberBE)(
27456
+ remainingAmount -= (0, import_utils16.bytesToNumberBE)(
27013
27457
  outputWithPreviousTransactionData.output.tokenAmount
27014
27458
  );
27015
27459
  }
@@ -27025,13 +27469,13 @@ var TokenTransactionService = class {
27025
27469
  if (strategy === "SMALL_FIRST") {
27026
27470
  tokenOutputs.sort((a, b) => {
27027
27471
  return Number(
27028
- (0, import_utils15.bytesToNumberBE)(a.output.tokenAmount) - (0, import_utils15.bytesToNumberBE)(b.output.tokenAmount)
27472
+ (0, import_utils16.bytesToNumberBE)(a.output.tokenAmount) - (0, import_utils16.bytesToNumberBE)(b.output.tokenAmount)
27029
27473
  );
27030
27474
  });
27031
27475
  } else {
27032
27476
  tokenOutputs.sort((a, b) => {
27033
27477
  return Number(
27034
- (0, import_utils15.bytesToNumberBE)(b.output.tokenAmount) - (0, import_utils15.bytesToNumberBE)(a.output.tokenAmount)
27478
+ (0, import_utils16.bytesToNumberBE)(b.output.tokenAmount) - (0, import_utils16.bytesToNumberBE)(a.output.tokenAmount)
27035
27479
  );
27036
27480
  });
27037
27481
  }
@@ -27039,7 +27483,7 @@ var TokenTransactionService = class {
27039
27483
  // Helper function for deciding if the signer public key is the identity public key
27040
27484
  async signMessageWithKey(message, publicKey) {
27041
27485
  const tokenSignatures = this.config.getTokenSignatures();
27042
- if ((0, import_utils15.bytesToHex)(publicKey) === (0, import_utils15.bytesToHex)(await this.config.signer.getIdentityPublicKey())) {
27486
+ if ((0, import_utils16.bytesToHex)(publicKey) === (0, import_utils16.bytesToHex)(await this.config.signer.getIdentityPublicKey())) {
27043
27487
  if (tokenSignatures === "SCHNORR") {
27044
27488
  return await this.config.signer.signSchnorrWithIdentityKey(message);
27045
27489
  } else {
@@ -27115,7 +27559,7 @@ var TokenTransactionService = class {
27115
27559
  }
27116
27560
  const payload = {
27117
27561
  finalTokenTransactionHash,
27118
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27562
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
27119
27563
  };
27120
27564
  const payloadHash = await hashOperatorSpecificTokenTransactionSignablePayload(payload);
27121
27565
  const ownerSignature = await this.signMessageWithKey(
@@ -27131,7 +27575,7 @@ var TokenTransactionService = class {
27131
27575
  for (let i = 0; i < transferInput.outputsToSpend.length; i++) {
27132
27576
  const payload = {
27133
27577
  finalTokenTransactionHash,
27134
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27578
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
27135
27579
  };
27136
27580
  const payloadHash = await hashOperatorSpecificTokenTransactionSignablePayload(payload);
27137
27581
  let ownerSignature;
@@ -27148,7 +27592,7 @@ var TokenTransactionService = class {
27148
27592
  }
27149
27593
  inputTtxoSignaturesPerOperator.push({
27150
27594
  ttxoSignatures,
27151
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27595
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
27152
27596
  });
27153
27597
  }
27154
27598
  return inputTtxoSignaturesPerOperator;
@@ -27160,7 +27604,7 @@ function isTokenTransaction(tokenTransaction) {
27160
27604
 
27161
27605
  // src/services/tree-creation.ts
27162
27606
  init_buffer();
27163
- var import_utils17 = require("@noble/curves/abstract/utils");
27607
+ var import_utils18 = require("@noble/curves/abstract/utils");
27164
27608
  var import_sha212 = require("@noble/hashes/sha2");
27165
27609
  var import_btc_signer5 = require("@scure/btc-signer");
27166
27610
  var INITIAL_TIME_LOCK3 = 2e3;
@@ -27209,7 +27653,7 @@ var TreeCreationService = class {
27209
27653
  request.source = {
27210
27654
  $case: "onChainUtxo",
27211
27655
  onChainUtxo: {
27212
- txid: (0, import_utils17.hexToBytes)(getTxId(parentTx)),
27656
+ txid: (0, import_utils18.hexToBytes)(getTxId(parentTx)),
27213
27657
  vout,
27214
27658
  rawTx: parentTx.toBytes(),
27215
27659
  network: this.config.getNetworkProto()
@@ -27250,7 +27694,7 @@ var TreeCreationService = class {
27250
27694
  request.source = {
27251
27695
  $case: "onChainUtxo",
27252
27696
  onChainUtxo: {
27253
- txid: (0, import_utils17.hexToBytes)(getTxId(parentTx)),
27697
+ txid: (0, import_utils18.hexToBytes)(getTxId(parentTx)),
27254
27698
  vout,
27255
27699
  rawTx: parentTx.toBytes(),
27256
27700
  network: this.config.getNetworkProto()
@@ -27621,13 +28065,13 @@ var TreeCreationService = class {
27621
28065
  };
27622
28066
 
27623
28067
  // src/spark-wallet/spark-wallet.ts
27624
- var import_lrc20_sdk3 = require("@buildonspark/lrc20-sdk");
28068
+ var import_lrc20_sdk4 = require("@buildonspark/lrc20-sdk");
27625
28069
  var import_sha213 = require("@noble/hashes/sha2");
27626
28070
  var import_eventemitter3 = require("eventemitter3");
27627
28071
 
27628
28072
  // src/services/signing.ts
27629
28073
  init_buffer();
27630
- var import_utils18 = require("@noble/curves/abstract/utils");
28074
+ var import_utils19 = require("@noble/curves/abstract/utils");
27631
28075
  var SigningService = class {
27632
28076
  config;
27633
28077
  constructor(config) {
@@ -27646,7 +28090,7 @@ var SigningService = class {
27646
28090
  }
27647
28091
  const nodeTx = getTxFromRawTxBytes(leaf.leaf.nodeTx);
27648
28092
  const nodeOutPoint = {
27649
- txid: (0, import_utils18.hexToBytes)(getTxId(nodeTx)),
28093
+ txid: (0, import_utils19.hexToBytes)(getTxId(nodeTx)),
27650
28094
  index: 0
27651
28095
  };
27652
28096
  const currRefundTx = getTxFromRawTxBytes(leaf.leaf.refundTx);
@@ -27704,15 +28148,15 @@ var SigningService = class {
27704
28148
 
27705
28149
  // src/tests/utils/test-faucet.ts
27706
28150
  init_buffer();
27707
- var import_utils19 = require("@noble/curves/abstract/utils");
28151
+ var import_utils20 = require("@noble/curves/abstract/utils");
27708
28152
  var import_secp256k115 = require("@noble/curves/secp256k1");
27709
28153
  var btc4 = __toESM(require("@scure/btc-signer"), 1);
27710
28154
  var import_btc_signer6 = require("@scure/btc-signer");
27711
- var import_utils20 = require("@scure/btc-signer/utils");
27712
- var STATIC_FAUCET_KEY = (0, import_utils19.hexToBytes)(
28155
+ var import_utils21 = require("@scure/btc-signer/utils");
28156
+ var STATIC_FAUCET_KEY = (0, import_utils20.hexToBytes)(
27713
28157
  "deadbeef1337cafe4242424242424242deadbeef1337cafe4242424242424242"
27714
28158
  );
27715
- var STATIC_MINING_KEY = (0, import_utils19.hexToBytes)(
28159
+ var STATIC_MINING_KEY = (0, import_utils20.hexToBytes)(
27716
28160
  "1337cafe4242deadbeef4242424242421337cafe4242deadbeef424242424242"
27717
28161
  );
27718
28162
  var SATS_PER_BTC = 1e8;
@@ -27775,7 +28219,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27775
28219
  if (!scanResult.success || scanResult.unspents.length === 0) {
27776
28220
  const blockHash = await this.generateToAddress(1, address2);
27777
28221
  const block = await this.getBlock(blockHash[0]);
27778
- const fundingTx = import_btc_signer6.Transaction.fromRaw((0, import_utils19.hexToBytes)(block.tx[0].hex), {
28222
+ const fundingTx = import_btc_signer6.Transaction.fromRaw((0, import_utils20.hexToBytes)(block.tx[0].hex), {
27779
28223
  allowUnknownOutputs: true
27780
28224
  });
27781
28225
  await this.generateToAddress(100, this.miningAddress);
@@ -27837,13 +28281,13 @@ var BitcoinFaucet = class _BitcoinFaucet {
27837
28281
  },
27838
28282
  STATIC_MINING_KEY
27839
28283
  );
27840
- await this.broadcastTx((0, import_utils19.bytesToHex)(signedSplitTx.extract()));
28284
+ await this.broadcastTx((0, import_utils20.bytesToHex)(signedSplitTx.extract()));
27841
28285
  const splitTxId = signedSplitTx.id;
27842
28286
  for (let i = 0; i < numCoinsToCreate; i++) {
27843
28287
  this.coins.push({
27844
28288
  key: STATIC_FAUCET_KEY,
27845
28289
  outpoint: {
27846
- txid: (0, import_utils19.hexToBytes)(splitTxId),
28290
+ txid: (0, import_utils20.hexToBytes)(splitTxId),
27847
28291
  index: i
27848
28292
  },
27849
28293
  txout: signedSplitTx.getOutput(i)
@@ -27871,7 +28315,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27871
28315
  coinToSend.txout,
27872
28316
  coinToSend.key
27873
28317
  );
27874
- await this.broadcastTx((0, import_utils19.bytesToHex)(signedTx.extract()));
28318
+ await this.broadcastTx((0, import_utils20.bytesToHex)(signedTx.extract()));
27875
28319
  }
27876
28320
  async signFaucetCoin(unsignedTx, fundingTxOut, key) {
27877
28321
  const pubKey = import_secp256k115.secp256k1.getPublicKey(key);
@@ -27891,7 +28335,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27891
28335
  new Array(unsignedTx.inputsLength).fill(fundingTxOut.amount)
27892
28336
  );
27893
28337
  const merkleRoot = new Uint8Array();
27894
- const tweakedKey = (0, import_utils20.taprootTweakPrivKey)(key, merkleRoot);
28338
+ const tweakedKey = (0, import_utils21.taprootTweakPrivKey)(key, merkleRoot);
27895
28339
  if (!tweakedKey)
27896
28340
  throw new Error("Invalid private key for taproot tweaking");
27897
28341
  const signature = import_secp256k115.schnorr.sign(sighash, tweakedKey);
@@ -27990,7 +28434,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27990
28434
  });
27991
28435
  }
27992
28436
  const signedTx = await this.signFaucetCoin(tx, coin.txout, coin.key);
27993
- const txHex = (0, import_utils19.bytesToHex)(signedTx.extract());
28437
+ const txHex = (0, import_utils20.bytesToHex)(signedTx.extract());
27994
28438
  await this.broadcastTx(txHex);
27995
28439
  const randomKey = import_secp256k115.secp256k1.utils.randomPrivateKey();
27996
28440
  const randomPubKey = import_secp256k115.secp256k1.getPublicKey(randomKey);
@@ -28008,18 +28452,18 @@ var BitcoinFaucet = class _BitcoinFaucet {
28008
28452
 
28009
28453
  // src/types/sdk-types.ts
28010
28454
  init_buffer();
28011
- var import_utils21 = require("@noble/curves/abstract/utils");
28455
+ var import_utils22 = require("@noble/curves/abstract/utils");
28012
28456
  function mapTreeNodeToWalletLeaf(proto) {
28013
28457
  return {
28014
28458
  id: proto.id,
28015
28459
  treeId: proto.treeId,
28016
28460
  value: proto.value,
28017
28461
  parentNodeId: proto.parentNodeId,
28018
- nodeTx: (0, import_utils21.bytesToHex)(proto.nodeTx),
28019
- refundTx: (0, import_utils21.bytesToHex)(proto.refundTx),
28462
+ nodeTx: (0, import_utils22.bytesToHex)(proto.nodeTx),
28463
+ refundTx: (0, import_utils22.bytesToHex)(proto.refundTx),
28020
28464
  vout: proto.vout,
28021
- verifyingPublicKey: (0, import_utils21.bytesToHex)(proto.verifyingPublicKey),
28022
- ownerIdentityPublicKey: (0, import_utils21.bytesToHex)(proto.ownerIdentityPublicKey),
28465
+ verifyingPublicKey: (0, import_utils22.bytesToHex)(proto.verifyingPublicKey),
28466
+ ownerIdentityPublicKey: (0, import_utils22.bytesToHex)(proto.ownerIdentityPublicKey),
28023
28467
  signingKeyshare: proto.signingKeyshare,
28024
28468
  status: proto.status,
28025
28469
  network: Network[proto.network]
@@ -28028,14 +28472,14 @@ function mapTreeNodeToWalletLeaf(proto) {
28028
28472
  function mapTransferLeafToWalletTransferLeaf(proto) {
28029
28473
  return {
28030
28474
  leaf: proto.leaf ? mapTreeNodeToWalletLeaf(proto.leaf) : void 0,
28031
- secretCipher: (0, import_utils21.bytesToHex)(proto.secretCipher),
28032
- signature: (0, import_utils21.bytesToHex)(proto.signature),
28033
- intermediateRefundTx: (0, import_utils21.bytesToHex)(proto.intermediateRefundTx)
28475
+ secretCipher: (0, import_utils22.bytesToHex)(proto.secretCipher),
28476
+ signature: (0, import_utils22.bytesToHex)(proto.signature),
28477
+ intermediateRefundTx: (0, import_utils22.bytesToHex)(proto.intermediateRefundTx)
28034
28478
  };
28035
28479
  }
28036
28480
  function mapTransferToWalletTransfer(proto, identityPublicKey) {
28037
- const receiverIdentityPublicKey = (0, import_utils21.bytesToHex)(proto.receiverIdentityPublicKey);
28038
- const senderIdentityPublicKey = (0, import_utils21.bytesToHex)(proto.senderIdentityPublicKey);
28481
+ const receiverIdentityPublicKey = (0, import_utils22.bytesToHex)(proto.receiverIdentityPublicKey);
28482
+ const senderIdentityPublicKey = (0, import_utils22.bytesToHex)(proto.senderIdentityPublicKey);
28039
28483
  return {
28040
28484
  id: proto.id,
28041
28485
  senderIdentityPublicKey,
@@ -28161,7 +28605,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28161
28605
  try {
28162
28606
  if (event?.$case === "transfer" && event.transfer.transfer && event.transfer.transfer.type !== 40 /* COUNTER_SWAP */) {
28163
28607
  const { senderIdentityPublicKey, receiverIdentityPublicKey } = event.transfer.transfer;
28164
- if (event.transfer.transfer && !(0, import_utils22.equalBytes)(senderIdentityPublicKey, receiverIdentityPublicKey)) {
28608
+ if (event.transfer.transfer && !(0, import_utils23.equalBytes)(senderIdentityPublicKey, receiverIdentityPublicKey)) {
28165
28609
  await this.claimTransfer({
28166
28610
  transfer: event.transfer.transfer,
28167
28611
  emit: true,
@@ -28233,7 +28677,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28233
28677
  setTimeout(maybeUnref, 100);
28234
28678
  }
28235
28679
  };
28236
- if (import_core12.isNode) {
28680
+ if (import_core14.isNode) {
28237
28681
  maybeUnref();
28238
28682
  }
28239
28683
  const claimedTransfersIds = await this.claimTransfers();
@@ -28323,10 +28767,10 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28323
28767
  leavesToIgnore.add(nodeId);
28324
28768
  continue;
28325
28769
  }
28326
- if (leaf.status !== operatorLeaf.status || !leaf.signingKeyshare || !operatorLeaf.signingKeyshare || !(0, import_utils22.equalBytes)(
28770
+ if (leaf.status !== operatorLeaf.status || !leaf.signingKeyshare || !operatorLeaf.signingKeyshare || !(0, import_utils23.equalBytes)(
28327
28771
  leaf.signingKeyshare.publicKey,
28328
28772
  operatorLeaf.signingKeyshare.publicKey
28329
- ) || !(0, import_utils22.equalBytes)(leaf.nodeTx, operatorLeaf.nodeTx) || !(0, import_utils22.equalBytes)(leaf.refundTx, operatorLeaf.refundTx)) {
28773
+ ) || !(0, import_utils23.equalBytes)(leaf.nodeTx, operatorLeaf.nodeTx) || !(0, import_utils23.equalBytes)(leaf.refundTx, operatorLeaf.refundTx)) {
28330
28774
  leavesToIgnore.add(nodeId);
28331
28775
  }
28332
28776
  }
@@ -28334,7 +28778,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28334
28778
  }
28335
28779
  }
28336
28780
  const verifyKey = (pubkey1, pubkey2, verifyingKey) => {
28337
- return (0, import_utils22.equalBytes)(addPublicKeys(pubkey1, pubkey2), verifyingKey);
28781
+ return (0, import_utils23.equalBytes)(addPublicKeys(pubkey1, pubkey2), verifyingKey);
28338
28782
  };
28339
28783
  for (const [id, leaf] of Object.entries(leaves.nodes)) {
28340
28784
  if (!verifyKey(
@@ -28468,7 +28912,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28468
28912
  * @returns {Promise<string>} The identity public key as a hex string.
28469
28913
  */
28470
28914
  async getIdentityPublicKey() {
28471
- return (0, import_utils22.bytesToHex)(await this.config.signer.getIdentityPublicKey());
28915
+ return (0, import_utils23.bytesToHex)(await this.config.signer.getIdentityPublicKey());
28472
28916
  }
28473
28917
  /**
28474
28918
  * Gets the Spark address of the wallet.
@@ -28478,7 +28922,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28478
28922
  async getSparkAddress() {
28479
28923
  if (!this.sparkAddress) {
28480
28924
  this.sparkAddress = encodeSparkAddress({
28481
- identityPublicKey: (0, import_utils22.bytesToHex)(
28925
+ identityPublicKey: (0, import_utils23.bytesToHex)(
28482
28926
  await this.config.signer.getIdentityPublicKey()
28483
28927
  ),
28484
28928
  network: this.config.getNetworkType()
@@ -28515,14 +28959,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28515
28959
  isValidPublicKey(assetIdentifier);
28516
28960
  }
28517
28961
  const paymentRequest = encodeSparkAddress({
28518
- identityPublicKey: (0, import_utils22.bytesToHex)(
28962
+ identityPublicKey: (0, import_utils23.bytesToHex)(
28519
28963
  await this.config.signer.getIdentityPublicKey()
28520
28964
  ),
28521
28965
  network: this.config.getNetworkType(),
28522
28966
  paymentIntentFields: {
28523
28967
  id: (0, import_uuidv75.uuidv7obj)().bytes,
28524
- assetIdentifier: assetIdentifier ? (0, import_utils22.hexToBytes)(assetIdentifier) : void 0,
28525
- assetAmount: (0, import_utils22.numberToVarBytesBE)(assetAmount),
28968
+ assetIdentifier: assetIdentifier ? (0, import_utils23.hexToBytes)(assetIdentifier) : void 0,
28969
+ assetAmount: (0, import_utils23.numberToVarBytesBE)(assetAmount),
28526
28970
  memo
28527
28971
  }
28528
28972
  });
@@ -28567,12 +29011,12 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28567
29011
  mnemonic = mnemonicOrSeed;
28568
29012
  seed = await this.config.signer.mnemonicToSeed(mnemonicOrSeed);
28569
29013
  } else {
28570
- seed = (0, import_utils22.hexToBytes)(mnemonicOrSeed);
29014
+ seed = (0, import_utils23.hexToBytes)(mnemonicOrSeed);
28571
29015
  }
28572
29016
  }
28573
29017
  await this.initWalletFromSeed(seed, accountNumber);
28574
29018
  const network = this.config.getNetwork();
28575
- this.lrc20Wallet = await import_lrc20_sdk3.LRCWallet.create(
29019
+ this.lrc20Wallet = await import_lrc20_sdk4.LRCWallet.create(
28576
29020
  LRC_WALLET_NETWORK[network],
28577
29021
  LRC_WALLET_NETWORK_TYPE[network],
28578
29022
  this.config.lrc20ApiConfig,
@@ -28672,7 +29116,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28672
29116
  );
28673
29117
  const { transfer, signatureMap } = await this.transferService.startSwapSignRefund(
28674
29118
  leafKeyTweaks,
28675
- (0, import_utils22.hexToBytes)(this.config.getSspIdentityPublicKey()),
29119
+ (0, import_utils23.hexToBytes)(this.config.getSspIdentityPublicKey()),
28676
29120
  new Date(Date.now() + 2 * 60 * 1e3)
28677
29121
  );
28678
29122
  try {
@@ -28690,10 +29134,10 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28690
29134
  const userLeaves = [];
28691
29135
  userLeaves.push({
28692
29136
  leaf_id: transfer.leaves[0].leaf.id,
28693
- raw_unsigned_refund_transaction: (0, import_utils22.bytesToHex)(
29137
+ raw_unsigned_refund_transaction: (0, import_utils23.bytesToHex)(
28694
29138
  transfer.leaves[0].intermediateRefundTx
28695
29139
  ),
28696
- adaptor_added_signature: (0, import_utils22.bytesToHex)(adaptorSignature)
29140
+ adaptor_added_signature: (0, import_utils23.bytesToHex)(adaptorSignature)
28697
29141
  });
28698
29142
  for (let i = 1; i < transfer.leaves.length; i++) {
28699
29143
  const leaf = transfer.leaves[i];
@@ -28710,14 +29154,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28710
29154
  );
28711
29155
  userLeaves.push({
28712
29156
  leaf_id: leaf.leaf.id,
28713
- raw_unsigned_refund_transaction: (0, import_utils22.bytesToHex)(
29157
+ raw_unsigned_refund_transaction: (0, import_utils23.bytesToHex)(
28714
29158
  leaf.intermediateRefundTx
28715
29159
  ),
28716
- adaptor_added_signature: (0, import_utils22.bytesToHex)(signature)
29160
+ adaptor_added_signature: (0, import_utils23.bytesToHex)(signature)
28717
29161
  });
28718
29162
  }
28719
29163
  const sspClient = this.getSspClient();
28720
- const adaptorPubkey = (0, import_utils22.bytesToHex)(
29164
+ const adaptorPubkey = (0, import_utils23.bytesToHex)(
28721
29165
  import_secp256k116.secp256k1.getPublicKey(adaptorPrivateKey)
28722
29166
  );
28723
29167
  let request = null;
@@ -28758,12 +29202,12 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28758
29202
  throw new Error(`Leaf not found for node ${nodeId}`);
28759
29203
  }
28760
29204
  const nodeTx = getTxFromRawTxBytes(node.nodeTx);
28761
- const refundTxBytes = (0, import_utils22.hexToBytes)(leaf.rawUnsignedRefundTransaction);
29205
+ const refundTxBytes = (0, import_utils23.hexToBytes)(leaf.rawUnsignedRefundTransaction);
28762
29206
  const refundTx = getTxFromRawTxBytes(refundTxBytes);
28763
29207
  const sighash = getSigHashFromTx(refundTx, 0, nodeTx.getOutput(0));
28764
29208
  const nodePublicKey = node.verifyingPublicKey;
28765
29209
  const taprootKey = computeTaprootKeyNoScript(nodePublicKey.slice(1));
28766
- const adaptorSignatureBytes = (0, import_utils22.hexToBytes)(leaf.adaptorSignedSignature);
29210
+ const adaptorSignatureBytes = (0, import_utils23.hexToBytes)(leaf.adaptorSignedSignature);
28767
29211
  applyAdaptorToSignature(
28768
29212
  taprootKey.slice(1),
28769
29213
  sighash,
@@ -28777,7 +29221,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28777
29221
  signatureMap
28778
29222
  );
28779
29223
  const completeResponse = await sspClient.completeLeaveSwap({
28780
- adaptorSecretKey: (0, import_utils22.bytesToHex)(adaptorPrivateKey),
29224
+ adaptorSecretKey: (0, import_utils23.bytesToHex)(adaptorPrivateKey),
28781
29225
  userOutboundTransferExternalId: transfer.id,
28782
29226
  leavesSwapRequestId: request.id
28783
29227
  });
@@ -28803,7 +29247,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28803
29247
  limit,
28804
29248
  offset
28805
29249
  );
28806
- const identityPublicKey = (0, import_utils22.bytesToHex)(
29250
+ const identityPublicKey = (0, import_utils23.bytesToHex)(
28807
29251
  await this.config.signer.getIdentityPublicKey()
28808
29252
  );
28809
29253
  return {
@@ -28824,14 +29268,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28824
29268
  const lrc20Client = await this.lrc20ConnectionManager.createLrc20Client();
28825
29269
  const { balance, tokenBalances } = await this.getBalance();
28826
29270
  const tokenInfo = await lrc20Client.getTokenPubkeyInfo({
28827
- publicKeys: Array.from(tokenBalances.keys()).map(import_utils22.hexToBytes)
29271
+ publicKeys: Array.from(tokenBalances.keys()).map(import_utils23.hexToBytes)
28828
29272
  });
28829
29273
  return tokenInfo.tokenPubkeyInfos.map((info) => ({
28830
- tokenPublicKey: (0, import_utils22.bytesToHex)(info.announcement.publicKey.publicKey),
29274
+ tokenPublicKey: (0, import_utils23.bytesToHex)(info.announcement.publicKey.publicKey),
28831
29275
  tokenName: info.announcement.name,
28832
29276
  tokenSymbol: info.announcement.symbol,
28833
- tokenDecimals: Number((0, import_utils22.bytesToNumberBE)(info.announcement.decimal)),
28834
- maxSupply: (0, import_utils22.bytesToNumberBE)(info.announcement.maxSupply)
29277
+ tokenDecimals: Number((0, import_utils23.bytesToNumberBE)(info.announcement.decimal)),
29278
+ maxSupply: (0, import_utils23.bytesToNumberBE)(info.announcement.maxSupply)
28835
29279
  }));
28836
29280
  }
28837
29281
  /**
@@ -28860,11 +29304,11 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28860
29304
  async getTokenBalance() {
28861
29305
  const lrc20Client = await this.lrc20ConnectionManager.createLrc20Client();
28862
29306
  const tokenInfo = await lrc20Client.getTokenPubkeyInfo({
28863
- publicKeys: Array.from(this.tokenOutputs.keys()).map(import_utils22.hexToBytes)
29307
+ publicKeys: Array.from(this.tokenOutputs.keys()).map(import_utils23.hexToBytes)
28864
29308
  });
28865
29309
  const result = /* @__PURE__ */ new Map();
28866
29310
  for (const info of tokenInfo.tokenPubkeyInfos) {
28867
- const tokenPublicKey = (0, import_utils22.bytesToHex)(
29311
+ const tokenPublicKey = (0, import_utils23.bytesToHex)(
28868
29312
  info.announcement.publicKey.publicKey
28869
29313
  );
28870
29314
  const leaves = this.tokenOutputs.get(tokenPublicKey);
@@ -28874,8 +29318,8 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28874
29318
  tokenPublicKey,
28875
29319
  tokenName: info.announcement.name,
28876
29320
  tokenSymbol: info.announcement.symbol,
28877
- tokenDecimals: Number((0, import_utils22.bytesToNumberBE)(info.announcement.decimal)),
28878
- maxSupply: (0, import_utils22.bytesToNumberBE)(info.announcement.maxSupply)
29321
+ tokenDecimals: Number((0, import_utils23.bytesToNumberBE)(info.announcement.decimal)),
29322
+ maxSupply: (0, import_utils23.bytesToNumberBE)(info.announcement.maxSupply)
28879
29323
  }
28880
29324
  });
28881
29325
  }
@@ -29009,7 +29453,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29009
29453
  if (network === BitcoinNetwork_default.FUTURE_VALUE) {
29010
29454
  network = BitcoinNetwork_default.REGTEST;
29011
29455
  }
29012
- const depositSecretKey = (0, import_utils22.bytesToHex)(
29456
+ const depositSecretKey = (0, import_utils23.bytesToHex)(
29013
29457
  await this.config.signer.getStaticDepositSecretKey(0)
29014
29458
  );
29015
29459
  const message = await this.getStaticDepositSigningPayload(
@@ -29022,7 +29466,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29022
29466
  );
29023
29467
  const hashBuffer = (0, import_sha213.sha256)(message);
29024
29468
  const signatureBytes = await this.config.signer.signMessageWithIdentityKey(hashBuffer);
29025
- const signature = (0, import_utils22.bytesToHex)(signatureBytes);
29469
+ const signature = (0, import_utils23.bytesToHex)(signatureBytes);
29026
29470
  const response = await this.sspClient.claimStaticDeposit({
29027
29471
  transactionId,
29028
29472
  outputIndex,
@@ -29107,7 +29551,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29107
29551
  networkJSON.toLowerCase(),
29108
29552
  2 /* Refund */,
29109
29553
  creditAmountSats,
29110
- (0, import_utils22.bytesToHex)(spendTxSighash)
29554
+ (0, import_utils23.bytesToHex)(spendTxSighash)
29111
29555
  );
29112
29556
  const hashBuffer = (0, import_sha213.sha256)(message);
29113
29557
  const swapResponseUserSignature = await this.config.signer.signMessageWithIdentityKey(hashBuffer);
@@ -29117,7 +29561,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29117
29561
  const transferId = (0, import_uuidv75.uuidv7)();
29118
29562
  const swapResponse = await sparkClient.initiate_utxo_swap({
29119
29563
  onChainUtxo: {
29120
- txid: (0, import_utils22.hexToBytes)(depositTransactionId),
29564
+ txid: (0, import_utils23.hexToBytes)(depositTransactionId),
29121
29565
  vout: outputIndex,
29122
29566
  network: networkType
29123
29567
  },
@@ -29194,7 +29638,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29194
29638
  creditAmountView.setUint32(0, lowerHalf, true);
29195
29639
  creditAmountView.setUint32(4, upperHalf, true);
29196
29640
  parts.push(new Uint8Array(creditAmountBuffer));
29197
- parts.push((0, import_utils22.hexToBytes)(sspSignature));
29641
+ parts.push((0, import_utils23.hexToBytes)(sspSignature));
29198
29642
  const totalLength = parts.reduce((sum, part) => sum + part.length, 0);
29199
29643
  const payload = new Uint8Array(totalLength);
29200
29644
  let offset = 0;
@@ -29544,9 +29988,9 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29544
29988
  this.config.getNetworkType()
29545
29989
  );
29546
29990
  const signerIdentityPublicKey = await this.config.signer.getIdentityPublicKey();
29547
- const isSelfTransfer = (0, import_utils22.equalBytes)(
29991
+ const isSelfTransfer = (0, import_utils23.equalBytes)(
29548
29992
  signerIdentityPublicKey,
29549
- (0, import_utils22.hexToBytes)(receiverAddress.identityPublicKey)
29993
+ (0, import_utils23.hexToBytes)(receiverAddress.identityPublicKey)
29550
29994
  );
29551
29995
  return await this.withLeaves(async () => {
29552
29996
  let leavesToSend = await this.selectLeaves(amountSats);
@@ -29563,7 +30007,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29563
30007
  );
29564
30008
  const transfer = await this.transferService.sendTransferWithKeyTweaks(
29565
30009
  leafKeyTweaks,
29566
- (0, import_utils22.hexToBytes)(receiverAddress.identityPublicKey)
30010
+ (0, import_utils23.hexToBytes)(receiverAddress.identityPublicKey)
29567
30011
  );
29568
30012
  const leavesToRemove = new Set(leavesToSend.map((leaf) => leaf.id));
29569
30013
  this.leaves = this.leaves.filter((leaf) => !leavesToRemove.has(leaf.id));
@@ -29579,7 +30023,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29579
30023
  }
29580
30024
  return mapTransferToWalletTransfer(
29581
30025
  transfer,
29582
- (0, import_utils22.bytesToHex)(await this.config.signer.getIdentityPublicKey())
30026
+ (0, import_utils23.bytesToHex)(await this.config.signer.getIdentityPublicKey())
29583
30027
  );
29584
30028
  });
29585
30029
  }
@@ -29903,7 +30347,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29903
30347
  const invoice2 = await sspClient.requestLightningReceive({
29904
30348
  amountSats: amountSats2,
29905
30349
  network: bitcoinNetwork,
29906
- paymentHash: (0, import_utils22.bytesToHex)(paymentHash),
30350
+ paymentHash: (0, import_utils23.bytesToHex)(paymentHash),
29907
30351
  expirySecs: expirySeconds,
29908
30352
  memo: memo2,
29909
30353
  includeSparkAddress,
@@ -29917,7 +30361,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29917
30361
  const sparkFallbackAddress = decodeInvoice(
29918
30362
  invoice2.invoice.encodedInvoice
29919
30363
  ).fallbackAddress;
29920
- if (sparkFallbackAddress && isValidSparkFallback((0, import_utils22.hexToBytes)(sparkFallbackAddress))) {
30364
+ if (sparkFallbackAddress && isValidSparkFallback((0, import_utils23.hexToBytes)(sparkFallbackAddress))) {
29921
30365
  const invoiceIdentityPubkey = sparkFallbackAddress.slice(6);
29922
30366
  const expectedIdentityPubkey = receiverIdentityPubkey2 ?? await this.getIdentityPublicKey();
29923
30367
  if (invoiceIdentityPubkey !== expectedIdentityPubkey) {
@@ -29958,12 +30402,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29958
30402
  * @param {Object} params - Parameters for paying the invoice
29959
30403
  * @param {string} params.invoice - The BOLT11-encoded Lightning invoice to pay
29960
30404
  * @param {boolean} [params.preferSpark] - Whether to prefer a spark transfer over lightning for the payment
30405
+ * @param {number} [params.amountSatsToSend] - The amount in sats to send. This is only valid for 0 amount lightning invoices.
29961
30406
  * @returns {Promise<LightningSendRequest>} The Lightning payment request details
29962
30407
  */
29963
30408
  async payLightningInvoice({
29964
30409
  invoice,
29965
30410
  maxFeeSats,
29966
- preferSpark = false
30411
+ preferSpark = false,
30412
+ amountSatsToSend
29967
30413
  }) {
29968
30414
  const invoiceNetwork = getNetworkFromInvoice(invoice);
29969
30415
  const walletNetwork = this.config.getNetwork();
@@ -29978,11 +30424,40 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29978
30424
  );
29979
30425
  }
29980
30426
  const decodedInvoice = decodeInvoice(invoice);
29981
- const amountSats = decodedInvoice.amountMSats !== null ? Number(decodedInvoice.amountMSats / 1000n) : 0;
30427
+ const amountMSats = decodedInvoice.amountMSats;
30428
+ const isZeroAmountInvoice = !amountMSats;
30429
+ if (!isZeroAmountInvoice && amountSatsToSend !== void 0) {
30430
+ throw new ValidationError(
30431
+ "Invalid amount. User can only specify amountSatsToSend for 0 amount lightning invoice",
30432
+ {
30433
+ field: "amountMSats",
30434
+ value: Number(amountMSats),
30435
+ expected: "0"
30436
+ }
30437
+ );
30438
+ }
30439
+ if (isZeroAmountInvoice && amountSatsToSend === void 0) {
30440
+ throw new ValidationError(
30441
+ "Invalid amount. User must specify amountSatsToSend for 0 amount lightning invoice",
30442
+ {
30443
+ field: "amountMSats",
30444
+ value: Number(amountMSats),
30445
+ expected: "0"
30446
+ }
30447
+ );
30448
+ }
30449
+ const amountSats = isZeroAmountInvoice ? amountSatsToSend : Number(amountMSats / 1000n);
30450
+ if (isNaN(amountSats) || amountSats <= 0) {
30451
+ throw new ValidationError("Invalid amount", {
30452
+ field: "amountSats",
30453
+ value: amountSats,
30454
+ expected: "greater than 0"
30455
+ });
30456
+ }
29982
30457
  const sparkFallbackAddress = decodedInvoice.fallbackAddress;
29983
30458
  const paymentHash = decodedInvoice.paymentHash;
29984
30459
  if (preferSpark) {
29985
- if (sparkFallbackAddress === void 0 || isValidSparkFallback((0, import_utils22.hexToBytes)(sparkFallbackAddress)) === false) {
30460
+ if (sparkFallbackAddress === void 0 || isValidSparkFallback((0, import_utils23.hexToBytes)(sparkFallbackAddress)) === false) {
29986
30461
  console.warn(
29987
30462
  "No valid spark address found in invoice. Defaulting to lightning."
29988
30463
  );
@@ -30000,15 +30475,9 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30000
30475
  }
30001
30476
  return await this.withLeaves(async () => {
30002
30477
  const sspClient = this.getSspClient();
30003
- if (isNaN(amountSats) || amountSats <= 0) {
30004
- throw new ValidationError("Invalid amount", {
30005
- field: "amountSats",
30006
- value: amountSats,
30007
- expected: "positive number"
30008
- });
30009
- }
30010
30478
  const feeEstimate = await this.getLightningSendFeeEstimate({
30011
- encodedInvoice: invoice
30479
+ encodedInvoice: invoice,
30480
+ amountSats: isZeroAmountInvoice ? amountSatsToSend : void 0
30012
30481
  });
30013
30482
  if (maxFeeSats < feeEstimate) {
30014
30483
  throw new ValidationError("maxFeeSats does not cover fee estimate", {
@@ -30040,25 +30509,27 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30040
30509
  );
30041
30510
  const swapResponse = await this.lightningService.swapNodesForPreimage({
30042
30511
  leaves: leavesToSend,
30043
- receiverIdentityPubkey: (0, import_utils22.hexToBytes)(
30512
+ receiverIdentityPubkey: (0, import_utils23.hexToBytes)(
30044
30513
  this.config.getSspIdentityPublicKey()
30045
30514
  ),
30046
- paymentHash: (0, import_utils22.hexToBytes)(paymentHash),
30515
+ paymentHash: (0, import_utils23.hexToBytes)(paymentHash),
30047
30516
  isInboundPayment: false,
30048
30517
  invoiceString: invoice,
30049
- feeSats: feeEstimate
30518
+ feeSats: feeEstimate,
30519
+ amountSatsToSend
30050
30520
  });
30051
30521
  if (!swapResponse.transfer) {
30052
30522
  throw new Error("Failed to swap nodes for preimage");
30053
30523
  }
30054
- const transfer = await this.transferService.sendTransferTweakKey(
30524
+ await this.transferService.deliverTransferPackage(
30055
30525
  swapResponse.transfer,
30056
30526
  leavesToSend,
30057
30527
  /* @__PURE__ */ new Map()
30058
30528
  );
30059
30529
  const sspResponse = await sspClient.requestLightningSend({
30060
30530
  encodedInvoice: invoice,
30061
- idempotencyKey: paymentHash
30531
+ idempotencyKey: paymentHash,
30532
+ amountSats: isZeroAmountInvoice ? amountSatsToSend : void 0
30062
30533
  });
30063
30534
  if (!sspResponse) {
30064
30535
  throw new Error("Failed to contact SSP");
@@ -30075,14 +30546,18 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30075
30546
  * @returns {Promise<number>} Fee estimate for sending Lightning payments
30076
30547
  */
30077
30548
  async getLightningSendFeeEstimate({
30078
- encodedInvoice
30549
+ encodedInvoice,
30550
+ amountSats
30079
30551
  }) {
30080
30552
  const sspClient = this.getSspClient();
30081
- const feeEstimate = await sspClient.getLightningSendFeeEstimate(encodedInvoice);
30553
+ const feeEstimate = await sspClient.getLightningSendFeeEstimate(
30554
+ encodedInvoice,
30555
+ amountSats
30556
+ );
30082
30557
  if (!feeEstimate) {
30083
30558
  throw new Error("Failed to get lightning send fee estimate");
30084
30559
  }
30085
- const satsFeeEstimate = (0, import_core12.mapCurrencyAmount)(feeEstimate.feeEstimate);
30560
+ const satsFeeEstimate = (0, import_core14.mapCurrencyAmount)(feeEstimate.feeEstimate);
30086
30561
  return Math.ceil(satsFeeEstimate.sats);
30087
30562
  }
30088
30563
  // ***** Tree Creation Flow *****
@@ -30240,11 +30715,11 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30240
30715
  const connectorOutputs = [];
30241
30716
  for (let i = 0; i < connectorTx.outputsLength - 1; i++) {
30242
30717
  connectorOutputs.push({
30243
- txid: (0, import_utils22.hexToBytes)(connectorTxId),
30718
+ txid: (0, import_utils23.hexToBytes)(connectorTxId),
30244
30719
  index: i
30245
30720
  });
30246
30721
  }
30247
- const sspPubIdentityKey = (0, import_utils22.hexToBytes)(this.config.getSspIdentityPublicKey());
30722
+ const sspPubIdentityKey = (0, import_utils23.hexToBytes)(this.config.getSspIdentityPublicKey());
30248
30723
  const transfer = await this.coopExitService.getConnectorRefundSignatures({
30249
30724
  leaves: leafKeyTweaks,
30250
30725
  exitTxId: coopExitTxId,
@@ -30331,7 +30806,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30331
30806
  );
30332
30807
  const groupedOutputs = /* @__PURE__ */ new Map();
30333
30808
  filteredTokenOutputs.forEach((output) => {
30334
- const tokenKey = (0, import_utils22.bytesToHex)(output.output.tokenPublicKey);
30809
+ const tokenKey = (0, import_utils23.bytesToHex)(output.output.tokenPublicKey);
30335
30810
  const index = output.previousTransactionVout;
30336
30811
  if (!groupedOutputs.has(tokenKey)) {
30337
30812
  groupedOutputs.set(tokenKey, []);
@@ -30429,14 +30904,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30429
30904
  let queryParams;
30430
30905
  if (tokenTransactionHashes?.length) {
30431
30906
  queryParams = {
30432
- tokenPublicKeys: tokenPublicKeys?.map(import_utils22.hexToBytes),
30433
- ownerPublicKeys: [(0, import_utils22.hexToBytes)(await this.getIdentityPublicKey())],
30434
- tokenTransactionHashes: tokenTransactionHashes.map(import_utils22.hexToBytes)
30907
+ tokenPublicKeys: tokenPublicKeys?.map(import_utils23.hexToBytes),
30908
+ ownerPublicKeys: [(0, import_utils23.hexToBytes)(await this.getIdentityPublicKey())],
30909
+ tokenTransactionHashes: tokenTransactionHashes.map(import_utils23.hexToBytes)
30435
30910
  };
30436
30911
  } else {
30437
30912
  queryParams = {
30438
- tokenPublicKeys: tokenPublicKeys?.map(import_utils22.hexToBytes),
30439
- ownerPublicKeys: [(0, import_utils22.hexToBytes)(await this.getIdentityPublicKey())]
30913
+ tokenPublicKeys: tokenPublicKeys?.map(import_utils23.hexToBytes),
30914
+ ownerPublicKeys: [(0, import_utils23.hexToBytes)(await this.getIdentityPublicKey())]
30440
30915
  };
30441
30916
  }
30442
30917
  const response = await sparkClient.query_token_transactions(queryParams);
@@ -30461,7 +30936,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30461
30936
  hash,
30462
30937
  compact
30463
30938
  );
30464
- return (0, import_utils22.bytesToHex)(signature);
30939
+ return (0, import_utils23.bytesToHex)(signature);
30465
30940
  }
30466
30941
  /**
30467
30942
  * Validates a message with the identity key.
@@ -30473,7 +30948,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30473
30948
  async validateMessageWithIdentityKey(message, signature) {
30474
30949
  const hash = (0, import_sha213.sha256)(message);
30475
30950
  if (typeof signature === "string") {
30476
- signature = (0, import_utils22.hexToBytes)(signature);
30951
+ signature = (0, import_utils23.hexToBytes)(signature);
30477
30952
  }
30478
30953
  return this.config.signer.validateMessageWithIdentityKey(hash, signature);
30479
30954
  }
@@ -30486,7 +30961,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30486
30961
  */
30487
30962
  async signTransaction(txHex, keyType = "auto-detect") {
30488
30963
  try {
30489
- const tx = import_btc_signer7.Transaction.fromRaw((0, import_utils22.hexToBytes)(txHex));
30964
+ const tx = import_btc_signer7.Transaction.fromRaw((0, import_utils23.hexToBytes)(txHex));
30490
30965
  let publicKey;
30491
30966
  switch (keyType.toLowerCase()) {
30492
30967
  case "identity":
@@ -30519,7 +30994,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30519
30994
  publicKey,
30520
30995
  this.config.getNetwork()
30521
30996
  );
30522
- if ((0, import_utils22.bytesToHex)(script) === (0, import_utils22.bytesToHex)(identityScript)) {
30997
+ if ((0, import_utils23.bytesToHex)(script) === (0, import_utils23.bytesToHex)(identityScript)) {
30523
30998
  try {
30524
30999
  this.config.signer.signTransactionIndex(tx, i, publicKey);
30525
31000
  inputsSigned++;
@@ -30563,13 +31038,13 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30563
31038
  depositPubKey,
30564
31039
  this.config.getNetwork()
30565
31040
  );
30566
- if ((0, import_utils22.bytesToHex)(script) === (0, import_utils22.bytesToHex)(identityScript)) {
31041
+ if ((0, import_utils23.bytesToHex)(script) === (0, import_utils23.bytesToHex)(identityScript)) {
30567
31042
  return {
30568
31043
  publicKey: identityPubKey,
30569
31044
  keyType: "identity"
30570
31045
  };
30571
31046
  }
30572
- if ((0, import_utils22.bytesToHex)(script) === (0, import_utils22.bytesToHex)(depositScript)) {
31047
+ if ((0, import_utils23.bytesToHex)(script) === (0, import_utils23.bytesToHex)(depositScript)) {
30573
31048
  return {
30574
31049
  publicKey: depositPubKey,
30575
31050
  keyType: "deposit"
@@ -30967,7 +31442,7 @@ async function isTxBroadcast(txid, baseUrl, network) {
30967
31442
 
30968
31443
  // src/utils/unilateral-exit.ts
30969
31444
  init_buffer();
30970
- var import_utils23 = require("@noble/curves/abstract/utils");
31445
+ var import_utils24 = require("@noble/curves/abstract/utils");
30971
31446
  var import_legacy = require("@noble/hashes/legacy");
30972
31447
  var import_sha214 = require("@noble/hashes/sha2");
30973
31448
  var btc5 = __toESM(require("@scure/btc-signer"), 1);
@@ -30982,7 +31457,7 @@ function isEphemeralAnchorOutput(script, amount) {
30982
31457
  }
30983
31458
  async function constructUnilateralExitTxs(nodeHexStrings, sparkClient, network) {
30984
31459
  const result = [];
30985
- const nodes = nodeHexStrings.map((hex) => TreeNode.decode((0, import_utils23.hexToBytes)(hex)));
31460
+ const nodes = nodeHexStrings.map((hex) => TreeNode.decode((0, import_utils24.hexToBytes)(hex)));
30986
31461
  const nodeMap = /* @__PURE__ */ new Map();
30987
31462
  for (const node of nodes) {
30988
31463
  nodeMap.set(node.id, node);
@@ -31038,10 +31513,10 @@ async function constructUnilateralExitTxs(nodeHexStrings, sparkClient, network)
31038
31513
  }
31039
31514
  }
31040
31515
  for (const chainNode of chain) {
31041
- const nodeTx = (0, import_utils23.bytesToHex)(chainNode.nodeTx);
31516
+ const nodeTx = (0, import_utils24.bytesToHex)(chainNode.nodeTx);
31042
31517
  transactions.push(nodeTx);
31043
31518
  if (chainNode.id === node.id) {
31044
- const refundTx = (0, import_utils23.bytesToHex)(chainNode.refundTx);
31519
+ const refundTx = (0, import_utils24.bytesToHex)(chainNode.refundTx);
31045
31520
  transactions.push(refundTx);
31046
31521
  }
31047
31522
  }
@@ -31071,7 +31546,7 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31071
31546
  `Node hex string at index ${i} appears to be a raw transaction hex, not a TreeNode protobuf. Use 'leafidtohex' command to convert node IDs to proper hex strings.`
31072
31547
  );
31073
31548
  }
31074
- const nodeBytes = (0, import_utils23.hexToBytes)(hex);
31549
+ const nodeBytes = (0, import_utils24.hexToBytes)(hex);
31075
31550
  const node = TreeNode.decode(nodeBytes);
31076
31551
  if (!node.id) {
31077
31552
  throw new Error(
@@ -31147,7 +31622,7 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31147
31622
  }
31148
31623
  }
31149
31624
  for (const chainNode of chain) {
31150
- let nodeTxHex = (0, import_utils23.bytesToHex)(chainNode.nodeTx);
31625
+ let nodeTxHex = (0, import_utils24.bytesToHex)(chainNode.nodeTx);
31151
31626
  try {
31152
31627
  const txObj = getTxFromRawTxHex(nodeTxHex);
31153
31628
  const txid = getTxId(txObj);
@@ -31164,7 +31639,7 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31164
31639
  for (let i = txObj.outputsLength - 1; i >= 0; i--) {
31165
31640
  const output = txObj.getOutput(i);
31166
31641
  if (output?.amount === 0n && output.script) {
31167
- anchorOutputScriptHex = (0, import_utils23.bytesToHex)(output.script);
31642
+ anchorOutputScriptHex = (0, import_utils24.bytesToHex)(output.script);
31168
31643
  break;
31169
31644
  }
31170
31645
  }
@@ -31185,11 +31660,11 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31185
31660
  usedUtxos,
31186
31661
  correctedParentTx
31187
31662
  } = constructFeeBumpTx(nodeTxHex, availableUtxos, feeRate, void 0);
31188
- const feeBumpTx = btc5.Transaction.fromPSBT((0, import_utils23.hexToBytes)(nodeFeeBumpPsbt));
31663
+ const feeBumpTx = btc5.Transaction.fromPSBT((0, import_utils24.hexToBytes)(nodeFeeBumpPsbt));
31189
31664
  var feeBumpOut = feeBumpTx.outputsLength === 1 ? feeBumpTx.getOutput(0) : null;
31190
31665
  var feeBumpOutPubKey = null;
31191
31666
  for (const usedUtxo of usedUtxos) {
31192
- if (feeBumpOut && (0, import_utils23.bytesToHex)(feeBumpOut.script) == usedUtxo.script) {
31667
+ if (feeBumpOut && (0, import_utils24.bytesToHex)(feeBumpOut.script) == usedUtxo.script) {
31193
31668
  feeBumpOutPubKey = usedUtxo.publicKey;
31194
31669
  }
31195
31670
  const index = availableUtxos.findIndex(
@@ -31204,20 +31679,20 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31204
31679
  txid: getTxId(feeBumpTx),
31205
31680
  vout: 0,
31206
31681
  value: feeBumpOut.amount,
31207
- script: (0, import_utils23.bytesToHex)(feeBumpOut.script),
31682
+ script: (0, import_utils24.bytesToHex)(feeBumpOut.script),
31208
31683
  publicKey: feeBumpOutPubKey
31209
31684
  });
31210
31685
  const finalNodeTx = correctedParentTx || nodeTxHex;
31211
31686
  txPackages.push({ tx: finalNodeTx, feeBumpPsbt: nodeFeeBumpPsbt });
31212
31687
  if (chainNode.id === node.id) {
31213
- let refundTxHex = (0, import_utils23.bytesToHex)(chainNode.refundTx);
31688
+ let refundTxHex = (0, import_utils24.bytesToHex)(chainNode.refundTx);
31214
31689
  try {
31215
31690
  const txObj = getTxFromRawTxHex(refundTxHex);
31216
31691
  let anchorOutputScriptHex;
31217
31692
  for (let i = txObj.outputsLength - 1; i >= 0; i--) {
31218
31693
  const output = txObj.getOutput(i);
31219
31694
  if (output?.amount === 0n && output.script) {
31220
- anchorOutputScriptHex = (0, import_utils23.bytesToHex)(output.script);
31695
+ anchorOutputScriptHex = (0, import_utils24.bytesToHex)(output.script);
31221
31696
  break;
31222
31697
  }
31223
31698
  }
@@ -31331,10 +31806,10 @@ function constructFeeBumpTx(txHex, utxos, feeRate, previousFeeBumpTx) {
31331
31806
  if (!fundingUtxo) {
31332
31807
  throw new Error(`UTXO at index ${i} is undefined`);
31333
31808
  }
31334
- const pubKeyHash = hash160((0, import_utils23.hexToBytes)(fundingUtxo.publicKey));
31809
+ const pubKeyHash = hash160((0, import_utils24.hexToBytes)(fundingUtxo.publicKey));
31335
31810
  const scriptToUse = new Uint8Array([0, 20, ...pubKeyHash]);
31336
- const providedScript = (0, import_utils23.hexToBytes)(fundingUtxo.script);
31337
- if ((0, import_utils23.bytesToHex)(scriptToUse) !== (0, import_utils23.bytesToHex)(providedScript)) {
31811
+ const providedScript = (0, import_utils24.hexToBytes)(fundingUtxo.script);
31812
+ if ((0, import_utils24.bytesToHex)(scriptToUse) !== (0, import_utils24.bytesToHex)(providedScript)) {
31338
31813
  throw new Error(
31339
31814
  `\u274C Derived script doesn't match provided script for UTXO ${i + 1}.`
31340
31815
  );
@@ -31399,7 +31874,7 @@ function constructFeeBumpTx(txHex, utxos, feeRate, previousFeeBumpTx) {
31399
31874
  }
31400
31875
  let psbtHex;
31401
31876
  try {
31402
- psbtHex = (0, import_utils23.bytesToHex)(builder.toPSBT());
31877
+ psbtHex = (0, import_utils24.bytesToHex)(builder.toPSBT());
31403
31878
  } catch (error) {
31404
31879
  throw new Error(`Failed to extract transaction: ${error}`);
31405
31880
  }