@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
@@ -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();
@@ -1455,8 +1486,8 @@ init_buffer();
1455
1486
 
1456
1487
  // src/spark-wallet/spark-wallet.ts
1457
1488
  init_buffer();
1458
- var import_core12 = require("@lightsparkdev/core");
1459
- var import_utils22 = require("@noble/curves/abstract/utils");
1489
+ var import_core14 = require("@lightsparkdev/core");
1490
+ var import_utils23 = require("@noble/curves/abstract/utils");
1460
1491
  var import_secp256k116 = require("@noble/curves/secp256k1");
1461
1492
  var import_bip392 = require("@scure/bip39");
1462
1493
  var import_english2 = require("@scure/bip39/wordlists/english");
@@ -1575,11 +1606,23 @@ var CurrencyAmountToJson = (obj) => {
1575
1606
  };
1576
1607
  };
1577
1608
 
1609
+ // src/graphql/objects/ExitSpeed.ts
1610
+ init_buffer();
1611
+ var ExitSpeed = /* @__PURE__ */ ((ExitSpeed2) => {
1612
+ ExitSpeed2["FUTURE_VALUE"] = "FUTURE_VALUE";
1613
+ ExitSpeed2["FAST"] = "FAST";
1614
+ ExitSpeed2["MEDIUM"] = "MEDIUM";
1615
+ ExitSpeed2["SLOW"] = "SLOW";
1616
+ return ExitSpeed2;
1617
+ })(ExitSpeed || {});
1618
+ var ExitSpeed_default = ExitSpeed;
1619
+
1578
1620
  // src/graphql/objects/SparkCoopExitRequestStatus.ts
1579
1621
  init_buffer();
1580
1622
  var SparkCoopExitRequestStatus = /* @__PURE__ */ ((SparkCoopExitRequestStatus2) => {
1581
1623
  SparkCoopExitRequestStatus2["FUTURE_VALUE"] = "FUTURE_VALUE";
1582
1624
  SparkCoopExitRequestStatus2["INITIATED"] = "INITIATED";
1625
+ SparkCoopExitRequestStatus2["INBOUND_TRANSFER_CHECKED"] = "INBOUND_TRANSFER_CHECKED";
1583
1626
  SparkCoopExitRequestStatus2["TX_SIGNED"] = "TX_SIGNED";
1584
1627
  SparkCoopExitRequestStatus2["TX_BROADCASTED"] = "TX_BROADCASTED";
1585
1628
  SparkCoopExitRequestStatus2["WAITING_ON_TX_CONFIRMATIONS"] = "WAITING_ON_TX_CONFIRMATIONS";
@@ -1764,6 +1807,8 @@ var CoopExitRequestFromJson = (obj) => {
1764
1807
  rawCoopExitTransaction: obj["coop_exit_request_raw_coop_exit_transaction"],
1765
1808
  coopExitTxid: obj["coop_exit_request_coop_exit_txid"],
1766
1809
  typename: "CoopExitRequest",
1810
+ feeQuoteId: obj["coop_exit_request_fee_quote"]?.id ?? void 0,
1811
+ exitSpeed: !!obj["coop_exit_request_exit_speed"] ? ExitSpeed_default[obj["coop_exit_request_exit_speed"]] ?? ExitSpeed_default.FUTURE_VALUE : null,
1767
1812
  transfer: !!obj["coop_exit_request_transfer"] ? TransferFromJson(obj["coop_exit_request_transfer"]) : void 0
1768
1813
  };
1769
1814
  };
@@ -1790,6 +1835,10 @@ fragment CoopExitRequestFragment on CoopExitRequest {
1790
1835
  currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
1791
1836
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1792
1837
  }
1838
+ coop_exit_request_fee_quote: fee_quote {
1839
+ id
1840
+ }
1841
+ coop_exit_request_exit_speed: exit_speed
1793
1842
  coop_exit_request_status: status
1794
1843
  coop_exit_request_expires_at: expires_at
1795
1844
  coop_exit_request_raw_connector_transaction: raw_connector_transaction
@@ -1806,6 +1855,9 @@ fragment CoopExitRequestFragment on CoopExitRequest {
1806
1855
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1807
1856
  }
1808
1857
  transfer_spark_id: spark_id
1858
+ transfer_user_request: user_request {
1859
+ id
1860
+ }
1809
1861
  }
1810
1862
  }`;
1811
1863
 
@@ -1930,6 +1982,9 @@ fragment LeavesSwapRequestFragment on LeavesSwapRequest {
1930
1982
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1931
1983
  }
1932
1984
  transfer_spark_id: spark_id
1985
+ transfer_user_request: user_request {
1986
+ id
1987
+ }
1933
1988
  }
1934
1989
  leaves_swap_request_outbound_transfer: outbound_transfer {
1935
1990
  __typename
@@ -1942,6 +1997,9 @@ fragment LeavesSwapRequestFragment on LeavesSwapRequest {
1942
1997
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
1943
1998
  }
1944
1999
  transfer_spark_id: spark_id
2000
+ transfer_user_request: user_request {
2001
+ id
2002
+ }
1945
2003
  }
1946
2004
  leaves_swap_request_expires_at: expires_at
1947
2005
  leaves_swap_request_swap_leaves: swap_leaves {
@@ -2075,7 +2133,8 @@ var LightningReceiveRequestFromJson = (obj) => {
2075
2133
  status: LightningReceiveRequestStatus_default[obj["lightning_receive_request_status"]] ?? LightningReceiveRequestStatus_default.FUTURE_VALUE,
2076
2134
  typename: "LightningReceiveRequest",
2077
2135
  transfer: !!obj["lightning_receive_request_transfer"] ? TransferFromJson(obj["lightning_receive_request_transfer"]) : void 0,
2078
- paymentPreimage: obj["lightning_receive_request_payment_preimage"]
2136
+ paymentPreimage: obj["lightning_receive_request_payment_preimage"],
2137
+ receiverIdentityPublicKey: obj["lightning_receive_request_receiver_identity_public_key"]
2079
2138
  };
2080
2139
  };
2081
2140
  var FRAGMENT6 = `
@@ -2114,8 +2173,12 @@ fragment LightningReceiveRequestFragment on LightningReceiveRequest {
2114
2173
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2115
2174
  }
2116
2175
  transfer_spark_id: spark_id
2176
+ transfer_user_request: user_request {
2177
+ id
2178
+ }
2117
2179
  }
2118
2180
  lightning_receive_request_payment_preimage: payment_preimage
2181
+ lightning_receive_request_receiver_identity_public_key: receiver_identity_public_key
2119
2182
  }`;
2120
2183
 
2121
2184
  // src/graphql/mutations/RequestLightningReceive.ts
@@ -2217,6 +2280,9 @@ fragment LightningSendRequestFragment on LightningSendRequest {
2217
2280
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2218
2281
  }
2219
2282
  transfer_spark_id: spark_id
2283
+ transfer_user_request: user_request {
2284
+ id
2285
+ }
2220
2286
  }
2221
2287
  lightning_send_request_payment_preimage: payment_preimage
2222
2288
  }`;
@@ -2226,10 +2292,12 @@ var RequestLightningSend = `
2226
2292
  mutation RequestLightningSend(
2227
2293
  $encoded_invoice: String!
2228
2294
  $idempotency_key: String!
2295
+ $amount_sats: Long
2229
2296
  ) {
2230
2297
  request_lightning_send(input: {
2231
2298
  encoded_invoice: $encoded_invoice
2232
2299
  idempotency_key: $idempotency_key
2300
+ amount_sats: $amount_sats
2233
2301
  }) {
2234
2302
  request {
2235
2303
  ...LightningSendRequestFragment
@@ -2520,10 +2588,12 @@ init_buffer();
2520
2588
  var LightningSendFeeEstimate = `
2521
2589
  query LightningSendFeeEstimate(
2522
2590
  $encoded_invoice: String!
2591
+ $amount_sats: Long
2523
2592
  ) {
2524
2593
  lightning_send_fee_estimate(
2525
2594
  input: {
2526
2595
  encoded_invoice: $encoded_invoice
2596
+ amount_sats: $amount_sats
2527
2597
  }
2528
2598
  ) {
2529
2599
  ...LightningSendFeeEstimateOutputFragment
@@ -2607,6 +2677,10 @@ fragment UserRequestFragment on UserRequest {
2607
2677
  currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
2608
2678
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2609
2679
  }
2680
+ coop_exit_request_fee_quote: fee_quote {
2681
+ id
2682
+ }
2683
+ coop_exit_request_exit_speed: exit_speed
2610
2684
  coop_exit_request_status: status
2611
2685
  coop_exit_request_expires_at: expires_at
2612
2686
  coop_exit_request_raw_connector_transaction: raw_connector_transaction
@@ -2623,6 +2697,9 @@ fragment UserRequestFragment on UserRequest {
2623
2697
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2624
2698
  }
2625
2699
  transfer_spark_id: spark_id
2700
+ transfer_user_request: user_request {
2701
+ id
2702
+ }
2626
2703
  }
2627
2704
  }
2628
2705
  ... on LeavesSwapRequest {
@@ -2667,6 +2744,9 @@ fragment UserRequestFragment on UserRequest {
2667
2744
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2668
2745
  }
2669
2746
  transfer_spark_id: spark_id
2747
+ transfer_user_request: user_request {
2748
+ id
2749
+ }
2670
2750
  }
2671
2751
  leaves_swap_request_outbound_transfer: outbound_transfer {
2672
2752
  __typename
@@ -2679,6 +2759,9 @@ fragment UserRequestFragment on UserRequest {
2679
2759
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2680
2760
  }
2681
2761
  transfer_spark_id: spark_id
2762
+ transfer_user_request: user_request {
2763
+ id
2764
+ }
2682
2765
  }
2683
2766
  leaves_swap_request_expires_at: expires_at
2684
2767
  leaves_swap_request_swap_leaves: swap_leaves {
@@ -2723,8 +2806,12 @@ fragment UserRequestFragment on UserRequest {
2723
2806
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2724
2807
  }
2725
2808
  transfer_spark_id: spark_id
2809
+ transfer_user_request: user_request {
2810
+ id
2811
+ }
2726
2812
  }
2727
2813
  lightning_receive_request_payment_preimage: payment_preimage
2814
+ lightning_receive_request_receiver_identity_public_key: receiver_identity_public_key
2728
2815
  }
2729
2816
  ... on LightningSendRequest {
2730
2817
  __typename
@@ -2754,6 +2841,9 @@ fragment UserRequestFragment on UserRequest {
2754
2841
  currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
2755
2842
  }
2756
2843
  transfer_spark_id: spark_id
2844
+ transfer_user_request: user_request {
2845
+ id
2846
+ }
2757
2847
  }
2758
2848
  lightning_send_request_payment_preimage: payment_preimage
2759
2849
  }
@@ -2834,11 +2924,12 @@ var SspClient = class {
2834
2924
  }
2835
2925
  });
2836
2926
  }
2837
- async getLightningSendFeeEstimate(encodedInvoice) {
2927
+ async getLightningSendFeeEstimate(encodedInvoice, amountSats) {
2838
2928
  return await this.executeRawQuery({
2839
2929
  queryPayload: LightningSendFeeEstimate,
2840
2930
  variables: {
2841
- encoded_invoice: encodedInvoice
2931
+ encoded_invoice: encodedInvoice,
2932
+ amount_sats: amountSats
2842
2933
  },
2843
2934
  constructObject: (response) => {
2844
2935
  return LightningSendFeeEstimateOutputFromJson(
@@ -2934,13 +3025,15 @@ var SspClient = class {
2934
3025
  }
2935
3026
  async requestLightningSend({
2936
3027
  encodedInvoice,
2937
- idempotencyKey
3028
+ idempotencyKey,
3029
+ amountSats
2938
3030
  }) {
2939
3031
  return await this.executeRawQuery({
2940
3032
  queryPayload: RequestLightningSend,
2941
3033
  variables: {
2942
3034
  encoded_invoice: encodedInvoice,
2943
- idempotency_key: idempotencyKey
3035
+ idempotency_key: idempotencyKey,
3036
+ amount_sats: amountSats
2944
3037
  },
2945
3038
  constructObject: (response) => {
2946
3039
  return LightningSendRequestFromJson(
@@ -3200,16 +3293,9 @@ init_buffer();
3200
3293
  init_buffer();
3201
3294
  var import_core7 = require("@lightsparkdev/core");
3202
3295
 
3203
- // src/graphql/objects/ExitSpeed.ts
3296
+ // src/graphql/objects/CoopExitFeeQuote.ts
3204
3297
  init_buffer();
3205
- var ExitSpeed = /* @__PURE__ */ ((ExitSpeed2) => {
3206
- ExitSpeed2["FUTURE_VALUE"] = "FUTURE_VALUE";
3207
- ExitSpeed2["FAST"] = "FAST";
3208
- ExitSpeed2["MEDIUM"] = "MEDIUM";
3209
- ExitSpeed2["SLOW"] = "SLOW";
3210
- return ExitSpeed2;
3211
- })(ExitSpeed || {});
3212
- var ExitSpeed_default = ExitSpeed;
3298
+ var import_core8 = require("@lightsparkdev/core");
3213
3299
 
3214
3300
  // src/graphql/objects/SparkUserRequestStatus.ts
3215
3301
  init_buffer();
@@ -3219,7 +3305,7 @@ init_buffer();
3219
3305
 
3220
3306
  // src/graphql/objects/SparkWalletUser.ts
3221
3307
  init_buffer();
3222
- var import_core8 = require("@lightsparkdev/core");
3308
+ var import_core9 = require("@lightsparkdev/core");
3223
3309
 
3224
3310
  // src/graphql/objects/SparkWalletUserToUserRequestsConnection.ts
3225
3311
  init_buffer();
@@ -4124,7 +4210,7 @@ var DepositAddressProof = {
4124
4210
  },
4125
4211
  fromJSON(object) {
4126
4212
  return {
4127
- addressSignatures: isObject8(object.addressSignatures) ? Object.entries(object.addressSignatures).reduce((acc, [key, value]) => {
4213
+ addressSignatures: isObject9(object.addressSignatures) ? Object.entries(object.addressSignatures).reduce((acc, [key, value]) => {
4128
4214
  acc[key] = bytesFromBase642(value);
4129
4215
  return acc;
4130
4216
  }, {}) : {},
@@ -4906,18 +4992,18 @@ var SigningResult = {
4906
4992
  },
4907
4993
  fromJSON(object) {
4908
4994
  return {
4909
- publicKeys: isObject8(object.publicKeys) ? Object.entries(object.publicKeys).reduce((acc, [key, value]) => {
4995
+ publicKeys: isObject9(object.publicKeys) ? Object.entries(object.publicKeys).reduce((acc, [key, value]) => {
4910
4996
  acc[key] = bytesFromBase642(value);
4911
4997
  return acc;
4912
4998
  }, {}) : {},
4913
- signingNonceCommitments: isObject8(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
4999
+ signingNonceCommitments: isObject9(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
4914
5000
  (acc, [key, value]) => {
4915
5001
  acc[key] = SigningCommitment.fromJSON(value);
4916
5002
  return acc;
4917
5003
  },
4918
5004
  {}
4919
5005
  ) : {},
4920
- signatureShares: isObject8(object.signatureShares) ? Object.entries(object.signatureShares).reduce((acc, [key, value]) => {
5006
+ signatureShares: isObject9(object.signatureShares) ? Object.entries(object.signatureShares).reduce((acc, [key, value]) => {
4921
5007
  acc[key] = bytesFromBase642(value);
4922
5008
  return acc;
4923
5009
  }, {}) : {},
@@ -8945,7 +9031,7 @@ var TransferPackage = {
8945
9031
  fromJSON(object) {
8946
9032
  return {
8947
9033
  leavesToSend: globalThis.Array.isArray(object?.leavesToSend) ? object.leavesToSend.map((e) => UserSignedTxSigningJob.fromJSON(e)) : [],
8948
- keyTweakPackage: isObject8(object.keyTweakPackage) ? Object.entries(object.keyTweakPackage).reduce((acc, [key, value]) => {
9034
+ keyTweakPackage: isObject9(object.keyTweakPackage) ? Object.entries(object.keyTweakPackage).reduce((acc, [key, value]) => {
8949
9035
  acc[key] = bytesFromBase642(value);
8950
9036
  return acc;
8951
9037
  }, {}) : {},
@@ -9207,7 +9293,7 @@ var SendLeafKeyTweak = {
9207
9293
  return {
9208
9294
  leafId: isSet3(object.leafId) ? globalThis.String(object.leafId) : "",
9209
9295
  secretShareTweak: isSet3(object.secretShareTweak) ? SecretShare.fromJSON(object.secretShareTweak) : void 0,
9210
- pubkeySharesTweak: isObject8(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
9296
+ pubkeySharesTweak: isObject9(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
9211
9297
  acc[key] = bytesFromBase642(value);
9212
9298
  return acc;
9213
9299
  }, {}) : {},
@@ -10180,7 +10266,7 @@ var ClaimLeafKeyTweak = {
10180
10266
  return {
10181
10267
  leafId: isSet3(object.leafId) ? globalThis.String(object.leafId) : "",
10182
10268
  secretShareTweak: isSet3(object.secretShareTweak) ? SecretShare.fromJSON(object.secretShareTweak) : void 0,
10183
- pubkeySharesTweak: isObject8(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
10269
+ pubkeySharesTweak: isObject9(object.pubkeySharesTweak) ? Object.entries(object.pubkeySharesTweak).reduce((acc, [key, value]) => {
10184
10270
  acc[key] = bytesFromBase642(value);
10185
10271
  return acc;
10186
10272
  }, {}) : {}
@@ -10856,7 +10942,7 @@ var RequestedSigningCommitments = {
10856
10942
  },
10857
10943
  fromJSON(object) {
10858
10944
  return {
10859
- signingNonceCommitments: isObject8(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
10945
+ signingNonceCommitments: isObject9(object.signingNonceCommitments) ? Object.entries(object.signingNonceCommitments).reduce(
10860
10946
  (acc, [key, value]) => {
10861
10947
  acc[key] = SigningCommitment.fromJSON(value);
10862
10948
  return acc;
@@ -11103,7 +11189,7 @@ var SigningCommitments = {
11103
11189
  },
11104
11190
  fromJSON(object) {
11105
11191
  return {
11106
- signingCommitments: isObject8(object.signingCommitments) ? Object.entries(object.signingCommitments).reduce(
11192
+ signingCommitments: isObject9(object.signingCommitments) ? Object.entries(object.signingCommitments).reduce(
11107
11193
  (acc, [key, value]) => {
11108
11194
  acc[key] = SigningCommitment.fromJSON(value);
11109
11195
  return acc;
@@ -13204,7 +13290,7 @@ var GetSigningOperatorListResponse = {
13204
13290
  },
13205
13291
  fromJSON(object) {
13206
13292
  return {
13207
- signingOperators: isObject8(object.signingOperators) ? Object.entries(object.signingOperators).reduce(
13293
+ signingOperators: isObject9(object.signingOperators) ? Object.entries(object.signingOperators).reduce(
13208
13294
  (acc, [key, value]) => {
13209
13295
  acc[key] = SigningOperatorInfo.fromJSON(value);
13210
13296
  return acc;
@@ -13871,7 +13957,7 @@ var QueryNodesResponse = {
13871
13957
  },
13872
13958
  fromJSON(object) {
13873
13959
  return {
13874
- nodes: isObject8(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
13960
+ nodes: isObject9(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
13875
13961
  acc[key] = TreeNode.fromJSON(value);
13876
13962
  return acc;
13877
13963
  }, {}) : {},
@@ -14587,7 +14673,7 @@ var QueryBalanceResponse = {
14587
14673
  fromJSON(object) {
14588
14674
  return {
14589
14675
  balance: isSet3(object.balance) ? globalThis.Number(object.balance) : 0,
14590
- nodeBalances: isObject8(object.nodeBalances) ? Object.entries(object.nodeBalances).reduce((acc, [key, value]) => {
14676
+ nodeBalances: isObject9(object.nodeBalances) ? Object.entries(object.nodeBalances).reduce((acc, [key, value]) => {
14591
14677
  acc[key] = Number(value);
14592
14678
  return acc;
14593
14679
  }, {}) : {}
@@ -15597,7 +15683,7 @@ var QueryNodesDistributionResponse = {
15597
15683
  },
15598
15684
  fromJSON(object) {
15599
15685
  return {
15600
- nodeDistribution: isObject8(object.nodeDistribution) ? Object.entries(object.nodeDistribution).reduce((acc, [key, value]) => {
15686
+ nodeDistribution: isObject9(object.nodeDistribution) ? Object.entries(object.nodeDistribution).reduce((acc, [key, value]) => {
15601
15687
  acc[globalThis.Number(key)] = Number(value);
15602
15688
  return acc;
15603
15689
  }, {}) : {}
@@ -15846,7 +15932,7 @@ var QueryNodesByValueResponse = {
15846
15932
  },
15847
15933
  fromJSON(object) {
15848
15934
  return {
15849
- nodes: isObject8(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
15935
+ nodes: isObject9(object.nodes) ? Object.entries(object.nodes).reduce((acc, [key, value]) => {
15850
15936
  acc[key] = TreeNode.fromJSON(value);
15851
15937
  return acc;
15852
15938
  }, {}) : {},
@@ -16374,7 +16460,7 @@ function longToNumber2(int64) {
16374
16460
  }
16375
16461
  return num;
16376
16462
  }
16377
- function isObject8(value) {
16463
+ function isObject9(value) {
16378
16464
  return typeof value === "object" && value !== null;
16379
16465
  }
16380
16466
  function isSet3(value) {
@@ -16386,7 +16472,7 @@ init_buffer();
16386
16472
 
16387
16473
  // src/signer/signer.ts
16388
16474
  init_buffer();
16389
- var import_utils4 = require("@noble/curves/abstract/utils");
16475
+ var import_utils5 = require("@noble/curves/abstract/utils");
16390
16476
  var import_secp256k15 = require("@noble/curves/secp256k1");
16391
16477
  var import_bip32 = require("@scure/bip32");
16392
16478
  var import_bip39 = require("@scure/bip39");
@@ -16395,29 +16481,41 @@ var ecies = __toESM(require("eciesjs"), 1);
16395
16481
 
16396
16482
  // src/constants.ts
16397
16483
  init_buffer();
16484
+ var import_core10 = require("@lightsparkdev/core");
16398
16485
  var isReactNative = typeof navigator !== "undefined" && navigator.product === "ReactNative";
16399
16486
  var isBun = globalThis.Bun !== void 0;
16487
+ var packageVersion = true ? "0.1.43" : "unknown";
16488
+ var baseEnvStr = "unknown";
16489
+ if (import_core10.isNode) {
16490
+ baseEnvStr = `node/${process.version}`;
16491
+ } else if (isReactNative) {
16492
+ baseEnvStr = "react-native";
16493
+ } else {
16494
+ const userAgent = typeof navigator !== "undefined" && navigator.userAgent || "unknown-user-agent";
16495
+ baseEnvStr = `browser/${userAgent}`;
16496
+ }
16497
+ var clientEnv = `js-spark-sdk/${packageVersion} ${baseEnvStr}`;
16400
16498
 
16401
16499
  // src/utils/adaptor-signature.ts
16402
16500
  init_buffer();
16403
16501
  var import_modular = require("@noble/curves/abstract/modular");
16404
- var import_utils = require("@noble/curves/abstract/utils");
16502
+ var import_utils2 = require("@noble/curves/abstract/utils");
16405
16503
  var import_secp256k1 = require("@noble/curves/secp256k1");
16406
16504
  function generateSignatureFromExistingAdaptor(signature, adaptorPrivateKeyBytes) {
16407
16505
  const { r, s } = parseSignature(signature);
16408
- const sBigInt = (0, import_utils.bytesToNumberBE)(s);
16409
- const tBigInt = (0, import_utils.bytesToNumberBE)(adaptorPrivateKeyBytes);
16506
+ const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
16507
+ const tBigInt = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKeyBytes);
16410
16508
  const newS = (0, import_modular.mod)(sBigInt - tBigInt, import_secp256k1.secp256k1.CURVE.n);
16411
- const newSignature = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(newS, 32)]);
16509
+ const newSignature = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
16412
16510
  return newSignature;
16413
16511
  }
16414
16512
  function generateAdaptorFromSignature(signature) {
16415
16513
  const adaptorPrivateKey = import_secp256k1.secp256k1.utils.randomPrivateKey();
16416
16514
  const { r, s } = parseSignature(signature);
16417
- const sBigInt = (0, import_utils.bytesToNumberBE)(s);
16418
- const tBigInt = (0, import_utils.bytesToNumberBE)(adaptorPrivateKey);
16515
+ const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
16516
+ const tBigInt = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKey);
16419
16517
  const newS = (0, import_modular.mod)(sBigInt - tBigInt, import_secp256k1.secp256k1.CURVE.n);
16420
- const newSignature = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(newS, 32)]);
16518
+ const newSignature = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
16421
16519
  return {
16422
16520
  adaptorSignature: newSignature,
16423
16521
  adaptorPrivateKey
@@ -16434,15 +16532,15 @@ function validateOutboundAdaptorSignature(pubkey, hash, signature, adaptorPubkey
16434
16532
  }
16435
16533
  function applyAdaptorToSignature(pubkey, hash, signature, adaptorPrivateKeyBytes) {
16436
16534
  const { r, s } = parseSignature(signature);
16437
- const sBigInt = (0, import_utils.bytesToNumberBE)(s);
16438
- const adaptorPrivateKey = (0, import_utils.bytesToNumberBE)(adaptorPrivateKeyBytes);
16535
+ const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
16536
+ const adaptorPrivateKey = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKeyBytes);
16439
16537
  const newS = (0, import_modular.mod)(sBigInt + adaptorPrivateKey, import_secp256k1.secp256k1.CURVE.n);
16440
- const newSig = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(newS, 32)]);
16538
+ const newSig = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
16441
16539
  if (import_secp256k1.schnorr.verify(newSig, hash, pubkey)) {
16442
16540
  return newSig;
16443
16541
  }
16444
16542
  const altS = (0, import_modular.mod)(sBigInt - adaptorPrivateKey, import_secp256k1.secp256k1.CURVE.n);
16445
- const altSig = new Uint8Array([...r, ...(0, import_utils.numberToBytesBE)(altS, 32)]);
16543
+ const altSig = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(altS, 32)]);
16446
16544
  if (import_secp256k1.schnorr.verify(altSig, hash, pubkey)) {
16447
16545
  return altSig;
16448
16546
  }
@@ -16452,7 +16550,7 @@ function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, i
16452
16550
  if (hash.length !== 32) {
16453
16551
  throw new Error(`wrong size for message (got ${hash.length}, want 32)`);
16454
16552
  }
16455
- const pubKey = import_secp256k1.schnorr.utils.lift_x((0, import_utils.bytesToNumberBE)(pubKeyBytes));
16553
+ const pubKey = import_secp256k1.schnorr.utils.lift_x((0, import_utils2.bytesToNumberBE)(pubKeyBytes));
16456
16554
  pubKey.assertValidity();
16457
16555
  const { r, s } = parseSignature(signature);
16458
16556
  const commitmenet = import_secp256k1.schnorr.utils.taggedHash(
@@ -16464,11 +16562,11 @@ function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, i
16464
16562
  if (commitmenet.length > 32) {
16465
16563
  throw new Error("hash of (r || P || m) too big");
16466
16564
  }
16467
- const e = (0, import_modular.mod)((0, import_utils.bytesToNumberBE)(commitmenet), import_secp256k1.secp256k1.CURVE.n);
16565
+ const e = (0, import_modular.mod)((0, import_utils2.bytesToNumberBE)(commitmenet), import_secp256k1.secp256k1.CURVE.n);
16468
16566
  const negE = (0, import_modular.mod)(-e, import_secp256k1.secp256k1.CURVE.n);
16469
16567
  const R = import_secp256k1.secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(
16470
16568
  pubKey,
16471
- (0, import_utils.bytesToNumberBE)(s),
16569
+ (0, import_utils2.bytesToNumberBE)(s),
16472
16570
  negE
16473
16571
  );
16474
16572
  if (!R) {
@@ -16484,7 +16582,7 @@ function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, i
16484
16582
  if (!newR.hasEvenY()) {
16485
16583
  throw new Error("calculated R y-value is odd");
16486
16584
  }
16487
- const rNum = (0, import_utils.bytesToNumberBE)(r);
16585
+ const rNum = (0, import_utils2.bytesToNumberBE)(r);
16488
16586
  if (newR.toAffine().x !== rNum) {
16489
16587
  throw new Error("calculated R point was not given R");
16490
16588
  }
@@ -16505,15 +16603,15 @@ function parseSignature(signature) {
16505
16603
  }
16506
16604
  const r = signature.slice(0, 32);
16507
16605
  const s = signature.slice(32, 64);
16508
- if ((0, import_utils.bytesToNumberBE)(r) >= import_secp256k1.secp256k1.CURVE.Fp.ORDER) {
16606
+ if ((0, import_utils2.bytesToNumberBE)(r) >= import_secp256k1.secp256k1.CURVE.Fp.ORDER) {
16509
16607
  throw new ValidationError("Invalid signature: r >= field prime", {
16510
- rValue: (0, import_utils.bytesToNumberBE)(r),
16608
+ rValue: (0, import_utils2.bytesToNumberBE)(r),
16511
16609
  fieldPrime: import_secp256k1.secp256k1.CURVE.Fp.ORDER
16512
16610
  });
16513
16611
  }
16514
- if ((0, import_utils.bytesToNumberBE)(s) >= import_secp256k1.secp256k1.CURVE.n) {
16612
+ if ((0, import_utils2.bytesToNumberBE)(s) >= import_secp256k1.secp256k1.CURVE.n) {
16515
16613
  throw new ValidationError("Invalid signature: s >= group order", {
16516
- sValue: (0, import_utils.bytesToNumberBE)(s),
16614
+ sValue: (0, import_utils2.bytesToNumberBE)(s),
16517
16615
  groupOrder: import_secp256k1.secp256k1.CURVE.n
16518
16616
  });
16519
16617
  }
@@ -16522,7 +16620,7 @@ function parseSignature(signature) {
16522
16620
 
16523
16621
  // src/utils/keys.ts
16524
16622
  init_buffer();
16525
- var import_utils2 = require("@noble/curves/abstract/utils");
16623
+ var import_utils3 = require("@noble/curves/abstract/utils");
16526
16624
  var import_secp256k12 = require("@noble/curves/secp256k1");
16527
16625
  function addPublicKeys(a, b) {
16528
16626
  if (a.length !== 33 || b.length !== 33) {
@@ -16580,7 +16678,7 @@ function addPrivateKeys(a, b) {
16580
16678
  const privA = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(a);
16581
16679
  const privB = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(b);
16582
16680
  const sum = (privA + privB) % import_secp256k12.secp256k1.CURVE.n;
16583
- return (0, import_utils2.numberToBytesBE)(sum, 32);
16681
+ return (0, import_utils3.numberToBytesBE)(sum, 32);
16584
16682
  }
16585
16683
  function subtractPrivateKeys(a, b) {
16586
16684
  if (a.length !== 32 || b.length !== 32) {
@@ -16593,7 +16691,7 @@ function subtractPrivateKeys(a, b) {
16593
16691
  const privA = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(a);
16594
16692
  const privB = import_secp256k12.secp256k1.utils.normPrivateKeyToScalar(b);
16595
16693
  const sum = (import_secp256k12.secp256k1.CURVE.n - privB + privA) % import_secp256k12.secp256k1.CURVE.n;
16596
- return (0, import_utils2.numberToBytesBE)(sum, 32);
16694
+ return (0, import_utils3.numberToBytesBE)(sum, 32);
16597
16695
  }
16598
16696
  function sumOfPrivateKeys(keys) {
16599
16697
  return keys.reduce((sum, key) => {
@@ -16621,7 +16719,7 @@ function lastKeyWithTarget(target, keys) {
16621
16719
 
16622
16720
  // src/utils/secret-sharing.ts
16623
16721
  init_buffer();
16624
- var import_utils3 = require("@noble/curves/abstract/utils");
16722
+ var import_utils4 = require("@noble/curves/abstract/utils");
16625
16723
  var import_secp256k13 = require("@noble/curves/secp256k1");
16626
16724
 
16627
16725
  // src/utils/crypto.ts
@@ -16640,7 +16738,7 @@ function getRandomBigInt(max) {
16640
16738
  const mask = (1n << BigInt(max.toString(2).length)) - 1n;
16641
16739
  while (true) {
16642
16740
  const randBytes = crypto.getRandomValues(new Uint8Array(byteLength + 1));
16643
- const randValue = BigInt("0x" + (0, import_utils3.bytesToHex)(randBytes)) & mask;
16741
+ const randValue = BigInt("0x" + (0, import_utils4.bytesToHex)(randBytes)) & mask;
16644
16742
  if (randValue < maxBigInt) {
16645
16743
  return randValue;
16646
16744
  }
@@ -16818,7 +16916,7 @@ function validateShare(share) {
16818
16916
  const scaledPoint = import_secp256k13.secp256k1.ProjectivePoint.fromHex(pubkey).multiply(value);
16819
16917
  resultPubkey = import_secp256k13.secp256k1.ProjectivePoint.fromHex(resultPubkey).add(scaledPoint).toRawBytes(true);
16820
16918
  }
16821
- if (!(0, import_utils3.equalBytes)(resultPubkey, targetPubkey)) {
16919
+ if (!(0, import_utils4.equalBytes)(resultPubkey, targetPubkey)) {
16822
16920
  throw new ValidationError("Share is not valid", {
16823
16921
  field: "share",
16824
16922
  value: "Invalid proof",
@@ -16921,7 +17019,9 @@ function decodeBytesToSigningCommitment(bytes2) {
16921
17019
  var import_secp256k16 = require("@bitcoinerlab/secp256k1");
16922
17020
  var import_lrc20_sdk = require("@buildonspark/lrc20-sdk");
16923
17021
  var import_sha22 = require("@noble/hashes/sha2");
16924
- var import_utils5 = require("@scure/btc-signer/utils");
17022
+ var import_utils6 = require("@scure/btc-signer/utils");
17023
+ var import_lrc20_sdk2 = require("@buildonspark/lrc20-sdk");
17024
+ var import_types2 = require("@buildonspark/lrc20-sdk/lrc/types");
16925
17025
  var sparkFrostModule = void 0;
16926
17026
  var getSparkFrostModule = async () => {
16927
17027
  if (isReactNative) {
@@ -17020,28 +17120,28 @@ var DefaultSparkSigner = class {
17020
17120
  const privateKey = this.deriveSigningKey(hash);
17021
17121
  const publicKey = import_secp256k15.secp256k1.getPublicKey(privateKey);
17022
17122
  this.publicKeyToPrivateKeyMap.set(
17023
- (0, import_utils4.bytesToHex)(publicKey),
17024
- (0, import_utils4.bytesToHex)(privateKey)
17123
+ (0, import_utils5.bytesToHex)(publicKey),
17124
+ (0, import_utils5.bytesToHex)(privateKey)
17025
17125
  );
17026
17126
  }
17027
17127
  }
17028
17128
  async getSchnorrPublicKey(publicKey) {
17029
- const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey));
17129
+ const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey));
17030
17130
  if (!privateKey) {
17031
17131
  throw new ValidationError("Private key is not set", {
17032
17132
  field: "privateKey"
17033
17133
  });
17034
17134
  }
17035
- return import_secp256k15.schnorr.getPublicKey((0, import_utils4.hexToBytes)(privateKey));
17135
+ return import_secp256k15.schnorr.getPublicKey((0, import_utils5.hexToBytes)(privateKey));
17036
17136
  }
17037
17137
  async signSchnorr(message, publicKey) {
17038
- const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey));
17138
+ const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey));
17039
17139
  if (!privateKey) {
17040
17140
  throw new ValidationError("Private key is not set", {
17041
17141
  field: "privateKey"
17042
17142
  });
17043
17143
  }
17044
- return import_secp256k15.schnorr.sign(message, (0, import_utils4.hexToBytes)(privateKey));
17144
+ return import_secp256k15.schnorr.sign(message, (0, import_utils5.hexToBytes)(privateKey));
17045
17145
  }
17046
17146
  async signSchnorrWithIdentityKey(message) {
17047
17147
  if (!this.identityKey?.privateKey) {
@@ -17083,8 +17183,8 @@ var DefaultSparkSigner = class {
17083
17183
  );
17084
17184
  this.staticDepositKeyMap.set(idx, staticDepositKey);
17085
17185
  this.publicKeyToPrivateKeyMap.set(
17086
- (0, import_utils4.bytesToHex)(staticDepositKey.publicKey),
17087
- (0, import_utils4.bytesToHex)(staticDepositKey.privateKey)
17186
+ (0, import_utils5.bytesToHex)(staticDepositKey.publicKey),
17187
+ (0, import_utils5.bytesToHex)(staticDepositKey.privateKey)
17088
17188
  );
17089
17189
  return staticDepositKey.publicKey;
17090
17190
  }
@@ -17129,7 +17229,7 @@ var DefaultSparkSigner = class {
17129
17229
  return await (0, import_bip39.mnemonicToSeed)(mnemonic);
17130
17230
  }
17131
17231
  async getTrackedPublicKeys() {
17132
- return Array.from(this.publicKeyToPrivateKeyMap.keys()).map(import_utils4.hexToBytes);
17232
+ return Array.from(this.publicKeyToPrivateKeyMap.keys()).map(import_utils5.hexToBytes);
17133
17233
  }
17134
17234
  async generatePublicKey(hash) {
17135
17235
  if (!this.signingKey) {
@@ -17149,31 +17249,31 @@ var DefaultSparkSigner = class {
17149
17249
  });
17150
17250
  }
17151
17251
  const publicKey = import_secp256k15.secp256k1.getPublicKey(newPrivateKey);
17152
- const pubKeyHex = (0, import_utils4.bytesToHex)(publicKey);
17153
- const privKeyHex = (0, import_utils4.bytesToHex)(newPrivateKey);
17252
+ const pubKeyHex = (0, import_utils5.bytesToHex)(publicKey);
17253
+ const privKeyHex = (0, import_utils5.bytesToHex)(newPrivateKey);
17154
17254
  this.publicKeyToPrivateKeyMap.set(pubKeyHex, privKeyHex);
17155
17255
  return publicKey;
17156
17256
  }
17157
17257
  async removePublicKey(publicKey) {
17158
- this.publicKeyToPrivateKeyMap.delete((0, import_utils4.bytesToHex)(publicKey));
17258
+ this.publicKeyToPrivateKeyMap.delete((0, import_utils5.bytesToHex)(publicKey));
17159
17259
  }
17160
17260
  async subtractPrivateKeysGivenPublicKeys(first, second) {
17161
- const firstPubKeyHex = (0, import_utils4.bytesToHex)(first);
17162
- const secondPubKeyHex = (0, import_utils4.bytesToHex)(second);
17261
+ const firstPubKeyHex = (0, import_utils5.bytesToHex)(first);
17262
+ const secondPubKeyHex = (0, import_utils5.bytesToHex)(second);
17163
17263
  const firstPrivateKeyHex = this.publicKeyToPrivateKeyMap.get(firstPubKeyHex);
17164
17264
  const secondPrivateKeyHex = this.publicKeyToPrivateKeyMap.get(secondPubKeyHex);
17165
17265
  if (!firstPrivateKeyHex || !secondPrivateKeyHex) {
17166
17266
  throw new Error("Private key is not set");
17167
17267
  }
17168
- const firstPrivateKey = (0, import_utils4.hexToBytes)(firstPrivateKeyHex);
17169
- const secondPrivateKey = (0, import_utils4.hexToBytes)(secondPrivateKeyHex);
17268
+ const firstPrivateKey = (0, import_utils5.hexToBytes)(firstPrivateKeyHex);
17269
+ const secondPrivateKey = (0, import_utils5.hexToBytes)(secondPrivateKeyHex);
17170
17270
  const resultPrivKey = subtractPrivateKeys(
17171
17271
  firstPrivateKey,
17172
17272
  secondPrivateKey
17173
17273
  );
17174
17274
  const resultPubKey = import_secp256k15.secp256k1.getPublicKey(resultPrivKey);
17175
- const resultPrivKeyHex = (0, import_utils4.bytesToHex)(resultPrivKey);
17176
- const resultPubKeyHex = (0, import_utils4.bytesToHex)(resultPubKey);
17275
+ const resultPrivKeyHex = (0, import_utils5.bytesToHex)(resultPrivKey);
17276
+ const resultPubKeyHex = (0, import_utils5.bytesToHex)(resultPubKey);
17177
17277
  this.publicKeyToPrivateKeyMap.set(resultPubKeyHex, resultPrivKeyHex);
17178
17278
  return resultPubKey;
17179
17279
  }
@@ -17185,14 +17285,14 @@ var DefaultSparkSigner = class {
17185
17285
  isSecretPubkey = false
17186
17286
  }) {
17187
17287
  if (isSecretPubkey) {
17188
- const pubKeyHex = (0, import_utils4.bytesToHex)(secret);
17288
+ const pubKeyHex = (0, import_utils5.bytesToHex)(secret);
17189
17289
  const privateKey = this.publicKeyToPrivateKeyMap.get(pubKeyHex);
17190
17290
  if (!privateKey) {
17191
17291
  throw new Error("Private key is not set");
17192
17292
  }
17193
- secret = (0, import_utils4.hexToBytes)(privateKey);
17293
+ secret = (0, import_utils5.hexToBytes)(privateKey);
17194
17294
  }
17195
- const secretAsInt = (0, import_utils4.bytesToNumberBE)(secret);
17295
+ const secretAsInt = (0, import_utils5.bytesToNumberBE)(secret);
17196
17296
  return splitSecretWithProofs(secretAsInt, curveOrder, threshold, numShares);
17197
17297
  }
17198
17298
  async signFrost({
@@ -17210,7 +17310,7 @@ var DefaultSparkSigner = class {
17210
17310
  field: "SparkFrost"
17211
17311
  });
17212
17312
  }
17213
- const privateAsPubKeyHex = (0, import_utils4.bytesToHex)(privateAsPubKey);
17313
+ const privateAsPubKeyHex = (0, import_utils5.bytesToHex)(privateAsPubKey);
17214
17314
  const signingPrivateKey = this.publicKeyToPrivateKeyMap.get(privateAsPubKeyHex);
17215
17315
  if (!signingPrivateKey) {
17216
17316
  throw new ValidationError("Private key not found for public key", {
@@ -17224,7 +17324,7 @@ var DefaultSparkSigner = class {
17224
17324
  });
17225
17325
  }
17226
17326
  const keyPackage = {
17227
- secretKey: (0, import_utils4.hexToBytes)(signingPrivateKey),
17327
+ secretKey: (0, import_utils5.hexToBytes)(signingPrivateKey),
17228
17328
  publicKey,
17229
17329
  verifyingKey
17230
17330
  };
@@ -17268,7 +17368,7 @@ var DefaultSparkSigner = class {
17268
17368
  }
17269
17369
  async createSparkWalletFromSeed(seed, accountNumber) {
17270
17370
  if (typeof seed === "string") {
17271
- seed = (0, import_utils4.hexToBytes)(seed);
17371
+ seed = (0, import_utils5.hexToBytes)(seed);
17272
17372
  }
17273
17373
  const {
17274
17374
  masterPublicKey,
@@ -17283,28 +17383,28 @@ var DefaultSparkSigner = class {
17283
17383
  this.signingKey = signingKey.hdKey;
17284
17384
  this.staticDepositKey = staticDepositKey.hdKey;
17285
17385
  this.publicKeyToPrivateKeyMap.set(
17286
- (0, import_utils4.bytesToHex)(identityKey.publicKey),
17287
- (0, import_utils4.bytesToHex)(identityKey.privateKey)
17386
+ (0, import_utils5.bytesToHex)(identityKey.publicKey),
17387
+ (0, import_utils5.bytesToHex)(identityKey.privateKey)
17288
17388
  );
17289
17389
  this.publicKeyToPrivateKeyMap.set(
17290
- (0, import_utils4.bytesToHex)(depositKey.publicKey),
17291
- (0, import_utils4.bytesToHex)(depositKey.privateKey)
17390
+ (0, import_utils5.bytesToHex)(depositKey.publicKey),
17391
+ (0, import_utils5.bytesToHex)(depositKey.privateKey)
17292
17392
  );
17293
17393
  this.publicKeyToPrivateKeyMap.set(
17294
- (0, import_utils4.bytesToHex)(staticDepositKey.publicKey),
17295
- (0, import_utils4.bytesToHex)(staticDepositKey.privateKey)
17394
+ (0, import_utils5.bytesToHex)(staticDepositKey.publicKey),
17395
+ (0, import_utils5.bytesToHex)(staticDepositKey.privateKey)
17296
17396
  );
17297
- return (0, import_utils4.bytesToHex)(identityKey.publicKey);
17397
+ return (0, import_utils5.bytesToHex)(identityKey.publicKey);
17298
17398
  }
17299
17399
  async signMessageWithPublicKey(message, publicKey, compact) {
17300
- const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey));
17400
+ const privateKey = this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey));
17301
17401
  if (!privateKey) {
17302
17402
  throw new ValidationError("Private key not found for public key", {
17303
17403
  field: "privateKey",
17304
- value: (0, import_utils4.bytesToHex)(publicKey)
17404
+ value: (0, import_utils5.bytesToHex)(publicKey)
17305
17405
  });
17306
17406
  }
17307
- const signature = import_secp256k15.secp256k1.sign(message, (0, import_utils4.hexToBytes)(privateKey));
17407
+ const signature = import_secp256k15.secp256k1.sign(message, (0, import_utils5.hexToBytes)(privateKey));
17308
17408
  if (compact) {
17309
17409
  return signature.toCompactRawBytes();
17310
17410
  }
@@ -17323,12 +17423,12 @@ var DefaultSparkSigner = class {
17323
17423
  return signature.toDERRawBytes();
17324
17424
  }
17325
17425
  async encryptLeafPrivateKeyEcies(receiverPublicKey, publicKey) {
17326
- const publicKeyHex = (0, import_utils4.bytesToHex)(publicKey);
17426
+ const publicKeyHex = (0, import_utils5.bytesToHex)(publicKey);
17327
17427
  const privateKey = this.publicKeyToPrivateKeyMap.get(publicKeyHex);
17328
17428
  if (!privateKey) {
17329
17429
  throw new Error("Private key is not set");
17330
17430
  }
17331
- return ecies.encrypt(receiverPublicKey, (0, import_utils4.hexToBytes)(privateKey));
17431
+ return ecies.encrypt(receiverPublicKey, (0, import_utils5.hexToBytes)(privateKey));
17332
17432
  }
17333
17433
  async decryptEcies(ciphertext) {
17334
17434
  if (!this.identityKey?.privateKey) {
@@ -17337,12 +17437,12 @@ var DefaultSparkSigner = class {
17337
17437
  });
17338
17438
  }
17339
17439
  const receiverEciesPrivKey = ecies.PrivateKey.fromHex(
17340
- (0, import_utils4.bytesToHex)(this.identityKey.privateKey)
17440
+ (0, import_utils5.bytesToHex)(this.identityKey.privateKey)
17341
17441
  );
17342
17442
  const privateKey = ecies.decrypt(receiverEciesPrivKey.toHex(), ciphertext);
17343
17443
  const publicKey = import_secp256k15.secp256k1.getPublicKey(privateKey);
17344
- const publicKeyHex = (0, import_utils4.bytesToHex)(publicKey);
17345
- const privateKeyHex = (0, import_utils4.bytesToHex)(privateKey);
17444
+ const publicKeyHex = (0, import_utils5.bytesToHex)(publicKey);
17445
+ const privateKeyHex = (0, import_utils5.bytesToHex)(privateKey);
17346
17446
  this.publicKeyToPrivateKeyMap.set(publicKeyHex, privateKeyHex);
17347
17447
  return publicKey;
17348
17448
  }
@@ -17359,8 +17459,8 @@ var DefaultSparkSigner = class {
17359
17459
  const adaptor = generateAdaptorFromSignature(signature);
17360
17460
  const adaptorPublicKey = import_secp256k15.secp256k1.getPublicKey(adaptor.adaptorPrivateKey);
17361
17461
  this.publicKeyToPrivateKeyMap.set(
17362
- (0, import_utils4.bytesToHex)(adaptorPublicKey),
17363
- (0, import_utils4.bytesToHex)(adaptor.adaptorPrivateKey)
17462
+ (0, import_utils5.bytesToHex)(adaptorPublicKey),
17463
+ (0, import_utils5.bytesToHex)(adaptor.adaptorPrivateKey)
17364
17464
  );
17365
17465
  return {
17366
17466
  adaptorSignature: signature,
@@ -17411,19 +17511,19 @@ var DefaultSparkSigner = class {
17411
17511
  }
17412
17512
  signTransactionIndex(tx, index, publicKey) {
17413
17513
  let privateKey;
17414
- if ((0, import_utils4.equalBytes)(publicKey, this.identityKey?.publicKey ?? new Uint8Array())) {
17514
+ if ((0, import_utils5.equalBytes)(publicKey, this.identityKey?.publicKey ?? new Uint8Array())) {
17415
17515
  privateKey = this.identityKey?.privateKey;
17416
- } else if ((0, import_utils4.equalBytes)(publicKey, this.depositKey?.publicKey ?? new Uint8Array())) {
17516
+ } else if ((0, import_utils5.equalBytes)(publicKey, this.depositKey?.publicKey ?? new Uint8Array())) {
17417
17517
  privateKey = this.depositKey?.privateKey;
17418
17518
  } else {
17419
- privateKey = (0, import_utils4.hexToBytes)(
17420
- this.publicKeyToPrivateKeyMap.get((0, import_utils4.bytesToHex)(publicKey)) ?? ""
17519
+ privateKey = (0, import_utils5.hexToBytes)(
17520
+ this.publicKeyToPrivateKeyMap.get((0, import_utils5.bytesToHex)(publicKey)) ?? ""
17421
17521
  );
17422
17522
  }
17423
17523
  if (!privateKey) {
17424
17524
  throw new ValidationError("Private key not found for public key", {
17425
17525
  field: "privateKey",
17426
- value: (0, import_utils4.bytesToHex)(publicKey)
17526
+ value: (0, import_utils5.bytesToHex)(publicKey)
17427
17527
  });
17428
17528
  }
17429
17529
  tx.signIdx(privateKey, index);
@@ -17432,7 +17532,7 @@ var DefaultSparkSigner = class {
17432
17532
 
17433
17533
  // src/utils/network.ts
17434
17534
  init_buffer();
17435
- var import_lrc20_sdk2 = require("@buildonspark/lrc20-sdk");
17535
+ var import_lrc20_sdk3 = require("@buildonspark/lrc20-sdk");
17436
17536
  var btc = __toESM(require("@scure/btc-signer"), 1);
17437
17537
  var bitcoin = __toESM(require("bitcoinjs-lib"), 1);
17438
17538
  var Network2 = /* @__PURE__ */ ((Network6) => {
@@ -17466,11 +17566,11 @@ var LRC_WALLET_NETWORK = Object.freeze({
17466
17566
  [4 /* LOCAL */]: bitcoin.networks.regtest
17467
17567
  });
17468
17568
  var LRC_WALLET_NETWORK_TYPE = Object.freeze({
17469
- [0 /* MAINNET */]: import_lrc20_sdk2.NetworkType.MAINNET,
17470
- [1 /* TESTNET */]: import_lrc20_sdk2.NetworkType.TESTNET,
17471
- [2 /* SIGNET */]: import_lrc20_sdk2.NetworkType.TESTNET,
17472
- [3 /* REGTEST */]: import_lrc20_sdk2.NetworkType.REGTEST,
17473
- [4 /* LOCAL */]: import_lrc20_sdk2.NetworkType.LOCAL
17569
+ [0 /* MAINNET */]: import_lrc20_sdk3.NetworkType.MAINNET,
17570
+ [1 /* TESTNET */]: import_lrc20_sdk3.NetworkType.TESTNET,
17571
+ [2 /* SIGNET */]: import_lrc20_sdk3.NetworkType.TESTNET,
17572
+ [3 /* REGTEST */]: import_lrc20_sdk3.NetworkType.REGTEST,
17573
+ [4 /* LOCAL */]: import_lrc20_sdk3.NetworkType.LOCAL
17474
17574
  });
17475
17575
  function getNetworkFromAddress(address2) {
17476
17576
  try {
@@ -17507,10 +17607,10 @@ init_buffer();
17507
17607
 
17508
17608
  // src/tests/isHermeticTest.ts
17509
17609
  init_buffer();
17510
- var import_core9 = require("@lightsparkdev/core");
17610
+ var import_core11 = require("@lightsparkdev/core");
17511
17611
  var import_fs = __toESM(require("fs"), 1);
17512
17612
  function isHermeticTest() {
17513
- if (import_core9.isNode) {
17613
+ if (import_core11.isNode) {
17514
17614
  return (import_fs.default?.existsSync?.("/tmp/spark_hermetic") ?? false) || process.env.HERMETIC_TEST === "true";
17515
17615
  }
17516
17616
  return typeof process !== "undefined" && process.env?.HERMETIC_TEST === "true" || false;
@@ -17638,6 +17738,7 @@ var BASE_CONFIG = {
17638
17738
  signingOperators: getLocalSigningOperators(),
17639
17739
  tokenSignatures: "SCHNORR",
17640
17740
  tokenTransactionVersion: "V0",
17741
+ tokenValidityDurationSeconds: 180,
17641
17742
  electrsUrl: getElectrsUrl("LOCAL"),
17642
17743
  expectedWithdrawBondSats: 1e4,
17643
17744
  expectedWithdrawRelativeBlockLocktime: 1e3,
@@ -17848,6 +17949,9 @@ var WalletConfigService = class {
17848
17949
  getTokenTransactionVersion() {
17849
17950
  return this.config.tokenTransactionVersion;
17850
17951
  }
17952
+ getTokenValidityDurationSeconds() {
17953
+ return this.config.tokenValidityDurationSeconds;
17954
+ }
17851
17955
  getElectrsUrl() {
17852
17956
  return this.config.electrsUrl;
17853
17957
  }
@@ -17858,7 +17962,7 @@ var WalletConfigService = class {
17858
17962
 
17859
17963
  // src/services/connection.ts
17860
17964
  init_buffer();
17861
- var import_core10 = require("@lightsparkdev/core");
17965
+ var import_core12 = require("@lightsparkdev/core");
17862
17966
  var import_sha23 = require("@noble/hashes/sha2");
17863
17967
  var import_nice_grpc_client_middleware_retry = require("nice-grpc-client-middleware-retry");
17864
17968
  var import_nice_grpc_common2 = require("nice-grpc-common");
@@ -19707,7 +19811,7 @@ var ConnectionManager = class {
19707
19811
  async createMockClient(address2) {
19708
19812
  const channel = await this.createChannelWithTLS(address2);
19709
19813
  const isNodeChannel = "close" in channel;
19710
- if (import_core10.isNode && isNodeChannel && !isBun) {
19814
+ if (import_core12.isNode && isNodeChannel && !isBun) {
19711
19815
  const grpcModule = await import("nice-grpc");
19712
19816
  const { createClient } = "default" in grpcModule ? grpcModule.default : grpcModule;
19713
19817
  const client = createClient(MockServiceDefinition, channel);
@@ -19724,7 +19828,7 @@ var ConnectionManager = class {
19724
19828
  }
19725
19829
  async createChannelWithTLS(address2, certPath) {
19726
19830
  try {
19727
- if (import_core10.isNode && !isBun) {
19831
+ if (import_core12.isNode && !isBun) {
19728
19832
  const grpcModule = await import("nice-grpc");
19729
19833
  const { ChannelCredentials, createChannel } = "default" in grpcModule ? grpcModule.default : grpcModule;
19730
19834
  if (certPath) {
@@ -19865,14 +19969,38 @@ var ConnectionManager = class {
19865
19969
  }
19866
19970
  async createSparkAuthnGrpcConnection(address2, certPath) {
19867
19971
  const channel = await this.createChannelWithTLS(address2, certPath);
19972
+ const authnMiddleware = this.createAuthnMiddleware();
19868
19973
  return this.createGrpcClient(
19869
19974
  SparkAuthnServiceDefinition,
19870
19975
  channel,
19871
- false
19976
+ false,
19977
+ authnMiddleware
19872
19978
  );
19873
19979
  }
19980
+ createAuthnMiddleware() {
19981
+ if (import_core12.isNode) {
19982
+ return async function* (call, options) {
19983
+ const metadata = (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
19984
+ "X-Client-Env",
19985
+ clientEnv
19986
+ );
19987
+ return yield* call.next(call.request, {
19988
+ ...options,
19989
+ metadata
19990
+ });
19991
+ }.bind(this);
19992
+ } else {
19993
+ return async function* (call, options) {
19994
+ 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");
19995
+ return yield* call.next(call.request, {
19996
+ ...options,
19997
+ metadata
19998
+ });
19999
+ }.bind(this);
20000
+ }
20001
+ }
19874
20002
  createMiddleware(address2, authToken) {
19875
- if (import_core10.isNode) {
20003
+ if (import_core12.isNode) {
19876
20004
  return this.createNodeMiddleware(address2, authToken);
19877
20005
  } else {
19878
20006
  return this.createBrowserMiddleware(address2, authToken);
@@ -19880,21 +20008,29 @@ var ConnectionManager = class {
19880
20008
  }
19881
20009
  createNodeMiddleware(address2, initialAuthToken) {
19882
20010
  return async function* (call, options) {
20011
+ const metadata = (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
20012
+ "X-Client-Env",
20013
+ clientEnv
20014
+ );
19883
20015
  try {
19884
20016
  return yield* call.next(call.request, {
19885
20017
  ...options,
19886
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
20018
+ metadata: metadata.set(
19887
20019
  "Authorization",
19888
20020
  `Bearer ${this.clients.get(address2)?.authToken || initialAuthToken}`
19889
- ).set("User-Agent", "spark-js-sdk")
20021
+ )
19890
20022
  });
19891
20023
  } catch (error) {
19892
20024
  if (error.message?.includes("token has expired")) {
19893
20025
  const newAuthToken = await this.authenticate(address2);
19894
- this.clients.get(address2).authToken = newAuthToken;
20026
+ const clientData = this.clients.get(address2);
20027
+ if (!clientData) {
20028
+ throw new Error(`No client found for address: ${address2}`);
20029
+ }
20030
+ clientData.authToken = newAuthToken;
19895
20031
  return yield* call.next(call.request, {
19896
20032
  ...options,
19897
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set("Authorization", `Bearer ${newAuthToken}`).set("User-Agent", "spark-js-sdk")
20033
+ metadata: metadata.set("Authorization", `Bearer ${newAuthToken}`)
19898
20034
  });
19899
20035
  }
19900
20036
  throw error;
@@ -19903,21 +20039,26 @@ var ConnectionManager = class {
19903
20039
  }
19904
20040
  createBrowserMiddleware(address2, initialAuthToken) {
19905
20041
  return async function* (call, options) {
20042
+ 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");
19906
20043
  try {
19907
20044
  return yield* call.next(call.request, {
19908
20045
  ...options,
19909
- metadata: (0, import_nice_grpc_common2.Metadata)(options.metadata).set(
20046
+ metadata: metadata.set(
19910
20047
  "Authorization",
19911
20048
  `Bearer ${this.clients.get(address2)?.authToken || initialAuthToken}`
19912
- ).set("X-Requested-With", "XMLHttpRequest").set("X-Grpc-Web", "1").set("Content-Type", "application/grpc-web+proto").set("User-Agent", "spark-js-sdk")
20049
+ )
19913
20050
  });
19914
20051
  } catch (error) {
19915
20052
  if (error.message?.includes("token has expired")) {
19916
20053
  const newAuthToken = await this.authenticate(address2);
19917
- this.clients.get(address2).authToken = newAuthToken;
20054
+ const clientData = this.clients.get(address2);
20055
+ if (!clientData) {
20056
+ throw new Error(`No client found for address: ${address2}`);
20057
+ }
20058
+ clientData.authToken = newAuthToken;
19918
20059
  return yield* call.next(call.request, {
19919
20060
  ...options,
19920
- 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")
20061
+ metadata: metadata.set("Authorization", `Bearer ${newAuthToken}`)
19921
20062
  });
19922
20063
  }
19923
20064
  throw error;
@@ -19932,7 +20073,7 @@ var ConnectionManager = class {
19932
20073
  };
19933
20074
  let options = {};
19934
20075
  const isNodeChannel = "close" in channel;
19935
- if (import_core10.isNode && isNodeChannel && !isBun) {
20076
+ if (import_core12.isNode && isNodeChannel && !isBun) {
19936
20077
  const grpcModule = await import("nice-grpc");
19937
20078
  const { openTelemetryClientMiddleware } = await import("nice-grpc-opentelemetry");
19938
20079
  const { createClientFactory } = "default" in grpcModule ? grpcModule.default : grpcModule;
@@ -19982,7 +20123,7 @@ var import_uuidv72 = require("uuidv7");
19982
20123
 
19983
20124
  // src/utils/bitcoin.ts
19984
20125
  init_buffer();
19985
- var import_utils6 = require("@noble/curves/abstract/utils");
20126
+ var import_utils7 = require("@noble/curves/abstract/utils");
19986
20127
  var import_secp256k17 = require("@noble/curves/secp256k1");
19987
20128
  var import_sha24 = require("@noble/hashes/sha2");
19988
20129
  var btc2 = __toESM(require("@scure/btc-signer"), 1);
@@ -19995,7 +20136,7 @@ function computeTaprootKeyNoScript(pubkey) {
19995
20136
  });
19996
20137
  }
19997
20138
  const taggedHash = import_secp256k17.schnorr.utils.taggedHash("TapTweak", pubkey);
19998
- const tweak = (0, import_utils6.bytesToNumberBE)(taggedHash);
20139
+ const tweak = (0, import_utils7.bytesToNumberBE)(taggedHash);
19999
20140
  const P = import_secp256k17.schnorr.utils.lift_x(import_secp256k17.schnorr.utils.bytesToNumberBE(pubkey));
20000
20141
  const Q = P.add(import_secp256k17.secp256k1.ProjectivePoint.fromPrivateKey(tweak));
20001
20142
  return Q.toRawBytes();
@@ -20048,7 +20189,7 @@ function getP2TRAddressFromPkScript(pkScript, network) {
20048
20189
  if (pkScript.length !== 34 || pkScript[0] !== 81 || pkScript[1] !== 32) {
20049
20190
  throw new ValidationError("Invalid pkscript", {
20050
20191
  field: "pkScript",
20051
- value: (0, import_utils6.bytesToHex)(pkScript),
20192
+ value: (0, import_utils7.bytesToHex)(pkScript),
20052
20193
  expected: "34 bytes starting with 0x51 0x20"
20053
20194
  });
20054
20195
  }
@@ -20073,7 +20214,7 @@ function getP2WPKHAddressFromPublicKey(pubKey, network) {
20073
20214
  return address2;
20074
20215
  }
20075
20216
  function getTxFromRawTxHex(rawTxHex) {
20076
- const txBytes = (0, import_utils6.hexToBytes)(rawTxHex);
20217
+ const txBytes = (0, import_utils7.hexToBytes)(rawTxHex);
20077
20218
  const tx = btc2.Transaction.fromRaw(txBytes, {
20078
20219
  allowUnknownOutputs: true
20079
20220
  });
@@ -20120,10 +20261,10 @@ function getSigHashFromTx(tx, inputIndex, prevOutput) {
20120
20261
  );
20121
20262
  }
20122
20263
  function getTxId(tx) {
20123
- return (0, import_utils6.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))).reverse());
20264
+ return (0, import_utils7.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))).reverse());
20124
20265
  }
20125
20266
  function getTxIdNoReverse(tx) {
20126
- return (0, import_utils6.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))));
20267
+ return (0, import_utils7.bytesToHex)((0, import_sha24.sha256)((0, import_sha24.sha256)(tx.toBytes(true))));
20127
20268
  }
20128
20269
 
20129
20270
  // src/utils/transaction.ts
@@ -20211,7 +20352,7 @@ function getEphemeralAnchorOutput() {
20211
20352
 
20212
20353
  // src/services/transfer.ts
20213
20354
  init_buffer();
20214
- var import_utils8 = require("@noble/curves/abstract/utils");
20355
+ var import_utils9 = require("@noble/curves/abstract/utils");
20215
20356
  var import_secp256k18 = require("@noble/curves/secp256k1");
20216
20357
  var import_sha26 = require("@noble/hashes/sha2");
20217
20358
  var import_btc_signer2 = require("@scure/btc-signer");
@@ -20220,7 +20361,7 @@ var import_uuidv7 = require("uuidv7");
20220
20361
 
20221
20362
  // src/utils/transfer_package.ts
20222
20363
  init_buffer();
20223
- var import_utils7 = require("@noble/curves/abstract/utils");
20364
+ var import_utils8 = require("@noble/curves/abstract/utils");
20224
20365
  var import_sha25 = require("@noble/hashes/sha2");
20225
20366
  function getTransferPackageSigningPayload(transferID, transferPackage) {
20226
20367
  const encryptedPayload = transferPackage.keyTweakPackage;
@@ -20229,7 +20370,7 @@ function getTransferPackageSigningPayload(transferID, transferPackage) {
20229
20370
  ).map(([key, value]) => ({ key, value }));
20230
20371
  pairs.sort((a, b) => a.key.localeCompare(b.key));
20231
20372
  const encoder = new TextEncoder();
20232
- let message = (0, import_utils7.hexToBytes)(transferID.replaceAll("-", ""));
20373
+ let message = (0, import_utils8.hexToBytes)(transferID.replaceAll("-", ""));
20233
20374
  for (const pair of pairs) {
20234
20375
  const keyPart = encoder.encode(pair.key + ":");
20235
20376
  const separator = encoder.encode(";");
@@ -20508,7 +20649,7 @@ var BaseTransferService = class {
20508
20649
  }
20509
20650
  async prepareSendTransferKeyTweaks(transferID, receiverIdentityPubkey, leaves, refundSignatureMap) {
20510
20651
  const receiverEciesPubKey = ecies2.PublicKey.fromHex(
20511
- (0, import_utils8.bytesToHex)(receiverIdentityPubkey)
20652
+ (0, import_utils9.bytesToHex)(receiverIdentityPubkey)
20512
20653
  );
20513
20654
  const leavesTweaksMap = /* @__PURE__ */ new Map();
20514
20655
  for (const leaf of leaves) {
@@ -20548,7 +20689,7 @@ var BaseTransferService = class {
20548
20689
  throw new Error(`Share not found for operator ${operator.id}`);
20549
20690
  }
20550
20691
  const pubkeyTweak = import_secp256k18.secp256k1.getPublicKey(
20551
- (0, import_utils8.numberToBytesBE)(share.share, 32),
20692
+ (0, import_utils9.numberToBytesBE)(share.share, 32),
20552
20693
  true
20553
20694
  );
20554
20695
  pubkeySharesTweak.set(identifier, pubkeyTweak);
@@ -20577,7 +20718,7 @@ var BaseTransferService = class {
20577
20718
  leafTweaksMap.set(identifier, {
20578
20719
  leafId: leaf.leaf.id,
20579
20720
  secretShareTweak: {
20580
- secretShare: (0, import_utils8.numberToBytesBE)(share.share, 32),
20721
+ secretShare: (0, import_utils9.numberToBytesBE)(share.share, 32),
20581
20722
  proofs: share.proofs
20582
20723
  },
20583
20724
  pubkeySharesTweak: Object.fromEntries(pubkeySharesTweak),
@@ -20598,7 +20739,7 @@ var BaseTransferService = class {
20598
20739
  return void 0;
20599
20740
  }
20600
20741
  compareTransfers(transfer1, transfer2) {
20601
- return transfer1.id === transfer2.id && (0, import_utils8.equalBytes)(
20742
+ return transfer1.id === transfer2.id && (0, import_utils9.equalBytes)(
20602
20743
  transfer1.senderIdentityPublicKey,
20603
20744
  transfer2.senderIdentityPublicKey
20604
20745
  ) && transfer1.status === transfer2.status && transfer1.totalValue === transfer2.totalValue && transfer1.expiryTime?.getTime() === transfer2.expiryTime?.getTime() && transfer1.leaves.length === transfer2.leaves.length;
@@ -20841,7 +20982,7 @@ var TransferService = class extends BaseTransferService {
20841
20982
  }
20842
20983
  const nodeTx = getTxFromRawTxBytes(leaf.leaf.nodeTx);
20843
20984
  const nodeOutPoint = {
20844
- txid: (0, import_utils8.hexToBytes)(getTxId(nodeTx)),
20985
+ txid: (0, import_utils9.hexToBytes)(getTxId(nodeTx)),
20845
20986
  index: 0
20846
20987
  };
20847
20988
  const currRefundTx = getTxFromRawTxBytes(leaf.leaf.refundTx);
@@ -20957,7 +21098,7 @@ var TransferService = class extends BaseTransferService {
20957
21098
  throw new Error(`Share not found for operator ${operator.id}`);
20958
21099
  }
20959
21100
  const pubkeyTweak = import_secp256k18.secp256k1.getPublicKey(
20960
- (0, import_utils8.numberToBytesBE)(share.share, 32)
21101
+ (0, import_utils9.numberToBytesBE)(share.share, 32)
20961
21102
  );
20962
21103
  pubkeySharesTweak.set(identifier, pubkeyTweak);
20963
21104
  }
@@ -20970,7 +21111,7 @@ var TransferService = class extends BaseTransferService {
20970
21111
  leafTweaksMap.set(identifier, {
20971
21112
  leafId: leaf.leaf.id,
20972
21113
  secretShareTweak: {
20973
- secretShare: (0, import_utils8.numberToBytesBE)(share.share, 32),
21114
+ secretShare: (0, import_utils9.numberToBytesBE)(share.share, 32),
20974
21115
  proofs: share.proofs
20975
21116
  },
20976
21117
  pubkeySharesTweak: Object.fromEntries(pubkeySharesTweak)
@@ -21260,7 +21401,7 @@ var TransferService = class extends BaseTransferService {
21260
21401
  const refundTx = getTxFromRawTxBytes(node.refundTx);
21261
21402
  const refundSequence = refundTx.getInput(0).sequence || 0;
21262
21403
  const newNodeOutPoint = {
21263
- txid: (0, import_utils8.hexToBytes)(getTxId(nodeTx)),
21404
+ txid: (0, import_utils9.hexToBytes)(getTxId(nodeTx)),
21264
21405
  index: 0
21265
21406
  };
21266
21407
  const { nextSequence: newNodeSequence } = getNextTransactionSequence(refundSequence);
@@ -21280,7 +21421,7 @@ var TransferService = class extends BaseTransferService {
21280
21421
  });
21281
21422
  newNodeTx.addOutput(getEphemeralAnchorOutput());
21282
21423
  const newRefundOutPoint = {
21283
- txid: (0, import_utils8.hexToBytes)(getTxId(newNodeTx)),
21424
+ txid: (0, import_utils9.hexToBytes)(getTxId(newNodeTx)),
21284
21425
  index: 0
21285
21426
  };
21286
21427
  const amountSats = refundTx.getOutput(0).amount;
@@ -21481,7 +21622,7 @@ var CoopExitService = class extends BaseTransferService {
21481
21622
  connectorOutputs,
21482
21623
  receiverPubKey
21483
21624
  );
21484
- const transferTweak = await this.sendTransferTweakKey(
21625
+ const transferTweak = await this.deliverTransferPackage(
21485
21626
  transfer,
21486
21627
  leaves,
21487
21628
  signaturesMap
@@ -21627,10 +21768,10 @@ var CoopExitService = class extends BaseTransferService {
21627
21768
  init_buffer();
21628
21769
  var import_secp256k19 = require("@noble/curves/secp256k1");
21629
21770
  var import_sha28 = require("@noble/hashes/sha2");
21630
- var import_utils9 = require("@noble/hashes/utils");
21771
+ var import_utils10 = require("@noble/hashes/utils");
21631
21772
  var btc3 = __toESM(require("@scure/btc-signer"), 1);
21632
21773
  var import_btc_signer4 = require("@scure/btc-signer");
21633
- var import_utils10 = require("@scure/btc-signer/utils");
21774
+ var import_utils11 = require("@scure/btc-signer/utils");
21634
21775
 
21635
21776
  // src/utils/proof.ts
21636
21777
  init_buffer();
@@ -21698,7 +21839,7 @@ var DepositService = class {
21698
21839
  if (operator.identifier === this.config.getCoordinatorIdentifier()) {
21699
21840
  continue;
21700
21841
  }
21701
- const operatorPubkey2 = (0, import_utils9.hexToBytes)(operator.identityPublicKey);
21842
+ const operatorPubkey2 = (0, import_utils10.hexToBytes)(operator.identityPublicKey);
21702
21843
  const operatorSig = address2.depositAddressProof.addressSignatures[operator.identifier];
21703
21844
  if (!operatorSig) {
21704
21845
  throw new ValidationError("Operator signature not found", {
@@ -21874,7 +22015,7 @@ var DepositService = class {
21874
22015
  }
21875
22016
  );
21876
22017
  }
21877
- if (!(0, import_utils10.equalBytes)(treeResp.rootNodeSignatureShares.verifyingKey, verifyingKey)) {
22018
+ if (!(0, import_utils11.equalBytes)(treeResp.rootNodeSignatureShares.verifyingKey, verifyingKey)) {
21878
22019
  throw new ValidationError("Verifying key mismatch", {
21879
22020
  field: "verifyingKey",
21880
22021
  value: treeResp.rootNodeSignatureShares.verifyingKey,
@@ -21950,7 +22091,7 @@ var DepositService = class {
21950
22091
 
21951
22092
  // src/services/lightning.ts
21952
22093
  init_buffer();
21953
- var import_utils11 = require("@noble/curves/abstract/utils");
22094
+ var import_utils12 = require("@noble/curves/abstract/utils");
21954
22095
  var import_secp256k111 = require("@noble/curves/secp256k1");
21955
22096
  var import_sha210 = require("@noble/hashes/sha2");
21956
22097
  var import_uuidv73 = require("uuidv7");
@@ -22151,8 +22292,8 @@ var LightningService = class {
22151
22292
  descriptionHash
22152
22293
  }) {
22153
22294
  const randBytes = crypto2.getRandomValues(new Uint8Array(32));
22154
- const preimage = (0, import_utils11.numberToBytesBE)(
22155
- (0, import_utils11.bytesToNumberBE)(randBytes) % import_secp256k111.secp256k1.CURVE.n,
22295
+ const preimage = (0, import_utils12.numberToBytesBE)(
22296
+ (0, import_utils12.bytesToNumberBE)(randBytes) % import_secp256k111.secp256k1.CURVE.n,
22156
22297
  32
22157
22298
  );
22158
22299
  return await this.createLightningInvoiceWithPreImage({
@@ -22207,12 +22348,12 @@ var LightningService = class {
22207
22348
  const sparkClient = await this.connectionManager.createSparkClient(
22208
22349
  operator.address
22209
22350
  );
22210
- const userIdentityPublicKey = receiverIdentityPubkey ? (0, import_utils11.hexToBytes)(receiverIdentityPubkey) : await this.config.signer.getIdentityPublicKey();
22351
+ const userIdentityPublicKey = receiverIdentityPubkey ? (0, import_utils12.hexToBytes)(receiverIdentityPubkey) : await this.config.signer.getIdentityPublicKey();
22211
22352
  try {
22212
22353
  await sparkClient.store_preimage_share({
22213
22354
  paymentHash,
22214
22355
  preimageShare: {
22215
- secretShare: (0, import_utils11.numberToBytesBE)(share.share, 32),
22356
+ secretShare: (0, import_utils12.numberToBytesBE)(share.share, 32),
22216
22357
  proofs: share.proofs
22217
22358
  },
22218
22359
  threshold: this.config.getThreshold(),
@@ -22244,7 +22385,8 @@ var LightningService = class {
22244
22385
  paymentHash,
22245
22386
  invoiceString,
22246
22387
  isInboundPayment,
22247
- feeSats = 0
22388
+ feeSats = 0,
22389
+ amountSatsToSend
22248
22390
  }) {
22249
22391
  const sparkClient = await this.connectionManager.createSparkClient(
22250
22392
  this.config.getCoordinatorAddress()
@@ -22281,7 +22423,25 @@ var LightningService = class {
22281
22423
  } catch (error) {
22282
22424
  console.error("Error decoding invoice", error);
22283
22425
  }
22284
- amountSats = amountMsats / 1e3;
22426
+ const isZeroAmountInvoice = !amountMsats;
22427
+ if (isZeroAmountInvoice && amountSatsToSend === void 0) {
22428
+ throw new ValidationError(
22429
+ "Invalid amount. User must specify amountSatsToSend for 0 amount lightning invoice",
22430
+ {
22431
+ field: "amountSatsToSend",
22432
+ value: amountSatsToSend,
22433
+ expected: "positive number"
22434
+ }
22435
+ );
22436
+ }
22437
+ amountSats = isZeroAmountInvoice ? amountSatsToSend : amountMsats / 1e3;
22438
+ if (isNaN(amountSats) || amountSats <= 0) {
22439
+ throw new ValidationError("Invalid amount", {
22440
+ field: "amountSats",
22441
+ value: amountSats,
22442
+ expected: "greater than 0"
22443
+ });
22444
+ }
22285
22445
  bolt11String = invoiceString;
22286
22446
  }
22287
22447
  const reason = isInboundPayment ? 1 /* REASON_RECEIVE */ : 0 /* REASON_SEND */;
@@ -22382,7 +22542,7 @@ var LightningService = class {
22382
22542
 
22383
22543
  // src/services/lrc-connection.ts
22384
22544
  init_buffer();
22385
- var import_core11 = require("@lightsparkdev/core");
22545
+ var import_core13 = require("@lightsparkdev/core");
22386
22546
  var import_nice_grpc_client_middleware_retry2 = require("nice-grpc-client-middleware-retry");
22387
22547
  var import_nice_grpc_common3 = require("nice-grpc-common");
22388
22548
 
@@ -25455,7 +25615,7 @@ var Lrc20ConnectionManager = class {
25455
25615
  }
25456
25616
  async createChannelWithTLS(address2, certPath) {
25457
25617
  try {
25458
- if (import_core11.isNode && !isBun) {
25618
+ if (import_core13.isNode && !isBun) {
25459
25619
  const grpcModule = await import("nice-grpc");
25460
25620
  const { ChannelCredentials, createChannel } = "default" in grpcModule ? grpcModule.default : grpcModule;
25461
25621
  if (certPath) {
@@ -25522,7 +25682,7 @@ var Lrc20ConnectionManager = class {
25522
25682
  return client;
25523
25683
  }
25524
25684
  createMiddleware() {
25525
- if (import_core11.isNode) {
25685
+ if (import_core13.isNode) {
25526
25686
  return this.createNodeMiddleware();
25527
25687
  } else {
25528
25688
  return this.createBrowserMiddleware();
@@ -25532,7 +25692,7 @@ var Lrc20ConnectionManager = class {
25532
25692
  return async function* (call, options) {
25533
25693
  return yield* call.next(call.request, {
25534
25694
  ...options,
25535
- metadata: (0, import_nice_grpc_common3.Metadata)(options.metadata).set("User-Agent", "spark-js-sdk")
25695
+ metadata: (0, import_nice_grpc_common3.Metadata)(options.metadata).set("X-Client-Env", clientEnv)
25536
25696
  });
25537
25697
  }.bind(this);
25538
25698
  }
@@ -25540,7 +25700,7 @@ var Lrc20ConnectionManager = class {
25540
25700
  return async function* (call, options) {
25541
25701
  return yield* call.next(call.request, {
25542
25702
  ...options,
25543
- 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")
25703
+ 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)
25544
25704
  });
25545
25705
  }.bind(this);
25546
25706
  }
@@ -25552,7 +25712,7 @@ var Lrc20ConnectionManager = class {
25552
25712
  };
25553
25713
  let options = {};
25554
25714
  const isNodeChannel = "close" in channel;
25555
- if (import_core11.isNode && isNodeChannel && !isBun) {
25715
+ if (import_core13.isNode && isNodeChannel && !isBun) {
25556
25716
  const grpcModule = await import("nice-grpc");
25557
25717
  const { openTelemetryClientMiddleware } = await import("nice-grpc-opentelemetry");
25558
25718
  const { createClientFactory } = "default" in grpcModule ? grpcModule.default : grpcModule;
@@ -25597,13 +25757,26 @@ var Lrc20ConnectionManager = class {
25597
25757
 
25598
25758
  // src/services/token-transactions.ts
25599
25759
  init_buffer();
25600
- var import_utils15 = require("@noble/curves/abstract/utils");
25760
+ var import_utils16 = require("@noble/curves/abstract/utils");
25601
25761
  var import_secp256k114 = require("@noble/curves/secp256k1");
25602
25762
 
25603
25763
  // src/utils/token-hashing.ts
25604
25764
  init_buffer();
25605
25765
  var import_sha211 = require("@noble/hashes/sha2");
25606
25766
  function hashTokenTransaction(tokenTransaction, partialHash = false) {
25767
+ switch (tokenTransaction.version) {
25768
+ case 0:
25769
+ return hashTokenTransactionV0(tokenTransaction, partialHash);
25770
+ case 1:
25771
+ return hashTokenTransactionV1(tokenTransaction, partialHash);
25772
+ default:
25773
+ throw new ValidationError("invalid token transaction version", {
25774
+ field: "tokenTransaction.version",
25775
+ value: tokenTransaction.version
25776
+ });
25777
+ }
25778
+ }
25779
+ function hashTokenTransactionV0(tokenTransaction, partialHash = false) {
25607
25780
  if (!tokenTransaction) {
25608
25781
  throw new ValidationError("token transaction cannot be nil", {
25609
25782
  field: "tokenTransaction"
@@ -25851,6 +26024,275 @@ function hashTokenTransaction(tokenTransaction, partialHash = false) {
25851
26024
  finalHashObj.update(concatenatedHashes);
25852
26025
  return finalHashObj.digest();
25853
26026
  }
26027
+ function hashTokenTransactionV1(tokenTransaction, partialHash = false) {
26028
+ if (!tokenTransaction) {
26029
+ throw new ValidationError("token transaction cannot be nil", {
26030
+ field: "tokenTransaction"
26031
+ });
26032
+ }
26033
+ let allHashes = [];
26034
+ const versionHashObj = import_sha211.sha256.create();
26035
+ const versionBytes = new Uint8Array(4);
26036
+ new DataView(versionBytes.buffer).setUint32(
26037
+ 0,
26038
+ tokenTransaction.version,
26039
+ false
26040
+ // false for big-endian
26041
+ );
26042
+ versionHashObj.update(versionBytes);
26043
+ allHashes.push(versionHashObj.digest());
26044
+ if (tokenTransaction.tokenInputs?.$case === "transferInput") {
26045
+ if (!tokenTransaction.tokenInputs.transferInput.outputsToSpend) {
26046
+ throw new ValidationError("outputs to spend cannot be null", {
26047
+ field: "tokenInputs.transferInput.outputsToSpend"
26048
+ });
26049
+ }
26050
+ if (tokenTransaction.tokenInputs.transferInput.outputsToSpend.length === 0) {
26051
+ throw new ValidationError("outputs to spend cannot be empty", {
26052
+ field: "tokenInputs.transferInput.outputsToSpend"
26053
+ });
26054
+ }
26055
+ for (const [
26056
+ i,
26057
+ output
26058
+ ] of tokenTransaction.tokenInputs.transferInput.outputsToSpend.entries()) {
26059
+ if (!output) {
26060
+ throw new ValidationError(`output cannot be null at index ${i}`, {
26061
+ field: `tokenInputs.transferInput.outputsToSpend[${i}]`,
26062
+ index: i
26063
+ });
26064
+ }
26065
+ const hashObj2 = import_sha211.sha256.create();
26066
+ if (output.prevTokenTransactionHash) {
26067
+ const prevHash = output.prevTokenTransactionHash;
26068
+ if (output.prevTokenTransactionHash.length !== 32) {
26069
+ throw new ValidationError(
26070
+ `invalid previous transaction hash length at index ${i}`,
26071
+ {
26072
+ field: `tokenInputs.transferInput.outputsToSpend[${i}].prevTokenTransactionHash`,
26073
+ value: prevHash,
26074
+ expectedLength: 32,
26075
+ actualLength: prevHash.length,
26076
+ index: i
26077
+ }
26078
+ );
26079
+ }
26080
+ hashObj2.update(output.prevTokenTransactionHash);
26081
+ }
26082
+ const voutBytes = new Uint8Array(4);
26083
+ new DataView(voutBytes.buffer).setUint32(
26084
+ 0,
26085
+ output.prevTokenTransactionVout,
26086
+ false
26087
+ );
26088
+ hashObj2.update(voutBytes);
26089
+ allHashes.push(hashObj2.digest());
26090
+ }
26091
+ }
26092
+ if (tokenTransaction.tokenInputs?.$case === "mintInput") {
26093
+ const hashObj2 = import_sha211.sha256.create();
26094
+ if (tokenTransaction.tokenInputs.mintInput.issuerPublicKey) {
26095
+ const issuerPubKey = tokenTransaction.tokenInputs.mintInput.issuerPublicKey;
26096
+ if (issuerPubKey.length === 0) {
26097
+ throw new ValidationError("issuer public key cannot be empty", {
26098
+ field: "tokenInputs.mintInput.issuerPublicKey",
26099
+ value: issuerPubKey,
26100
+ expectedLength: 1,
26101
+ actualLength: 0
26102
+ });
26103
+ }
26104
+ hashObj2.update(issuerPubKey);
26105
+ if (tokenTransaction.tokenInputs.mintInput.issuerProvidedTimestamp != 0) {
26106
+ const timestampBytes = new Uint8Array(8);
26107
+ new DataView(timestampBytes.buffer).setBigUint64(
26108
+ 0,
26109
+ BigInt(
26110
+ tokenTransaction.tokenInputs.mintInput.issuerProvidedTimestamp
26111
+ ),
26112
+ true
26113
+ // true for little-endian to match Go implementation
26114
+ );
26115
+ hashObj2.update(timestampBytes);
26116
+ }
26117
+ allHashes.push(hashObj2.digest());
26118
+ }
26119
+ }
26120
+ if (!tokenTransaction.tokenOutputs) {
26121
+ throw new ValidationError("token outputs cannot be null", {
26122
+ field: "tokenOutputs"
26123
+ });
26124
+ }
26125
+ if (tokenTransaction.tokenOutputs.length === 0) {
26126
+ throw new ValidationError("token outputs cannot be empty", {
26127
+ field: "tokenOutputs"
26128
+ });
26129
+ }
26130
+ for (const [i, output] of tokenTransaction.tokenOutputs.entries()) {
26131
+ if (!output) {
26132
+ throw new ValidationError(`output cannot be null at index ${i}`, {
26133
+ field: `tokenOutputs[${i}]`,
26134
+ index: i
26135
+ });
26136
+ }
26137
+ const hashObj2 = import_sha211.sha256.create();
26138
+ if (output.id && !partialHash) {
26139
+ if (output.id.length === 0) {
26140
+ throw new ValidationError(`output ID at index ${i} cannot be empty`, {
26141
+ field: `tokenOutputs[${i}].id`,
26142
+ index: i
26143
+ });
26144
+ }
26145
+ hashObj2.update(new TextEncoder().encode(output.id));
26146
+ }
26147
+ if (output.ownerPublicKey) {
26148
+ if (output.ownerPublicKey.length === 0) {
26149
+ throw new ValidationError(
26150
+ `owner public key at index ${i} cannot be empty`,
26151
+ {
26152
+ field: `tokenOutputs[${i}].ownerPublicKey`,
26153
+ index: i
26154
+ }
26155
+ );
26156
+ }
26157
+ hashObj2.update(output.ownerPublicKey);
26158
+ }
26159
+ if (!partialHash) {
26160
+ const revPubKey = output.revocationCommitment;
26161
+ if (revPubKey) {
26162
+ if (revPubKey.length === 0) {
26163
+ throw new ValidationError(
26164
+ `revocation commitment at index ${i} cannot be empty`,
26165
+ {
26166
+ field: `tokenOutputs[${i}].revocationCommitment`,
26167
+ index: i
26168
+ }
26169
+ );
26170
+ }
26171
+ hashObj2.update(revPubKey);
26172
+ }
26173
+ const bondBytes = new Uint8Array(8);
26174
+ new DataView(bondBytes.buffer).setBigUint64(
26175
+ 0,
26176
+ BigInt(output.withdrawBondSats),
26177
+ false
26178
+ );
26179
+ hashObj2.update(bondBytes);
26180
+ const locktimeBytes = new Uint8Array(8);
26181
+ new DataView(locktimeBytes.buffer).setBigUint64(
26182
+ 0,
26183
+ BigInt(output.withdrawRelativeBlockLocktime),
26184
+ false
26185
+ );
26186
+ hashObj2.update(locktimeBytes);
26187
+ }
26188
+ if (output.tokenPublicKey) {
26189
+ if (output.tokenPublicKey.length === 0) {
26190
+ throw new ValidationError(
26191
+ `token public key at index ${i} cannot be empty`,
26192
+ {
26193
+ field: `tokenOutputs[${i}].tokenPublicKey`,
26194
+ index: i
26195
+ }
26196
+ );
26197
+ }
26198
+ hashObj2.update(output.tokenPublicKey);
26199
+ }
26200
+ if (output.tokenAmount) {
26201
+ if (output.tokenAmount.length === 0) {
26202
+ throw new ValidationError(
26203
+ `token amount at index ${i} cannot be empty`,
26204
+ {
26205
+ field: `tokenOutputs[${i}].tokenAmount`,
26206
+ index: i
26207
+ }
26208
+ );
26209
+ }
26210
+ if (output.tokenAmount.length > 16) {
26211
+ throw new ValidationError(
26212
+ `token amount at index ${i} exceeds maximum length`,
26213
+ {
26214
+ field: `tokenOutputs[${i}].tokenAmount`,
26215
+ value: output.tokenAmount,
26216
+ expectedLength: 16,
26217
+ actualLength: output.tokenAmount.length,
26218
+ index: i
26219
+ }
26220
+ );
26221
+ }
26222
+ hashObj2.update(output.tokenAmount);
26223
+ }
26224
+ allHashes.push(hashObj2.digest());
26225
+ }
26226
+ if (!tokenTransaction.sparkOperatorIdentityPublicKeys) {
26227
+ throw new ValidationError(
26228
+ "spark operator identity public keys cannot be null",
26229
+ {}
26230
+ );
26231
+ }
26232
+ const sortedPubKeys = [
26233
+ ...tokenTransaction.sparkOperatorIdentityPublicKeys || []
26234
+ ].sort((a, b) => {
26235
+ for (let i = 0; i < a.length && i < b.length; i++) {
26236
+ if (a[i] !== b[i]) return a[i] - b[i];
26237
+ }
26238
+ return a.length - b.length;
26239
+ });
26240
+ for (const [i, pubKey] of sortedPubKeys.entries()) {
26241
+ if (!pubKey) {
26242
+ throw new ValidationError(
26243
+ `operator public key at index ${i} cannot be null`,
26244
+ {
26245
+ field: `sparkOperatorIdentityPublicKeys[${i}]`,
26246
+ index: i
26247
+ }
26248
+ );
26249
+ }
26250
+ if (pubKey.length === 0) {
26251
+ throw new ValidationError(
26252
+ `operator public key at index ${i} cannot be empty`,
26253
+ {
26254
+ field: `sparkOperatorIdentityPublicKeys[${i}]`,
26255
+ index: i
26256
+ }
26257
+ );
26258
+ }
26259
+ const hashObj2 = import_sha211.sha256.create();
26260
+ hashObj2.update(pubKey);
26261
+ allHashes.push(hashObj2.digest());
26262
+ }
26263
+ const hashObj = import_sha211.sha256.create();
26264
+ let networkBytes = new Uint8Array(4);
26265
+ new DataView(networkBytes.buffer).setUint32(
26266
+ 0,
26267
+ tokenTransaction.network.valueOf(),
26268
+ false
26269
+ // false for big-endian
26270
+ );
26271
+ hashObj.update(networkBytes);
26272
+ allHashes.push(hashObj.digest());
26273
+ const expiryHashObj = import_sha211.sha256.create();
26274
+ const validityDurationBytes = new Uint8Array(8);
26275
+ const expiryUnixTime = tokenTransaction.expiryTime ? Math.floor(tokenTransaction.expiryTime.getTime() / 1e3) : 0;
26276
+ new DataView(validityDurationBytes.buffer).setBigUint64(
26277
+ 0,
26278
+ BigInt(expiryUnixTime),
26279
+ false
26280
+ // false for big-endian
26281
+ );
26282
+ expiryHashObj.update(validityDurationBytes);
26283
+ allHashes.push(expiryHashObj.digest());
26284
+ const finalHashObj = import_sha211.sha256.create();
26285
+ const concatenatedHashes = new Uint8Array(
26286
+ allHashes.reduce((sum, hash) => sum + hash.length, 0)
26287
+ );
26288
+ let offset = 0;
26289
+ for (const hash of allHashes) {
26290
+ concatenatedHashes.set(hash, offset);
26291
+ offset += hash.length;
26292
+ }
26293
+ finalHashObj.update(concatenatedHashes);
26294
+ return finalHashObj.digest();
26295
+ }
25854
26296
  function hashOperatorSpecificTokenTransactionSignablePayload(payload) {
25855
26297
  if (!payload) {
25856
26298
  throw new ValidationError(
@@ -25902,15 +26344,15 @@ function hashOperatorSpecificTokenTransactionSignablePayload(payload) {
25902
26344
 
25903
26345
  // src/utils/token-transactions.ts
25904
26346
  init_buffer();
25905
- var import_utils12 = require("@noble/curves/abstract/utils");
26347
+ var import_utils13 = require("@noble/curves/abstract/utils");
25906
26348
  function calculateAvailableTokenAmount(outputLeaves) {
25907
26349
  return outputLeaves.reduce(
25908
- (sum, output) => sum + BigInt((0, import_utils12.bytesToNumberBE)(output.output.tokenAmount)),
26350
+ (sum, output) => sum + BigInt((0, import_utils13.bytesToNumberBE)(output.output.tokenAmount)),
25909
26351
  BigInt(0)
25910
26352
  );
25911
26353
  }
25912
26354
  function checkIfSelectedOutputsAreAvailable(selectedOutputs, tokenOutputs, tokenPublicKey) {
25913
- const tokenPubKeyHex = (0, import_utils12.bytesToHex)(tokenPublicKey);
26355
+ const tokenPubKeyHex = (0, import_utils13.bytesToHex)(tokenPublicKey);
25914
26356
  const tokenOutputsAvailable = tokenOutputs.get(tokenPubKeyHex);
25915
26357
  if (!tokenOutputsAvailable) {
25916
26358
  return false;
@@ -26196,7 +26638,7 @@ function validateTokenTransaction(finalTokenTransaction, partialTokenTransaction
26196
26638
  }
26197
26639
 
26198
26640
  // src/services/token-transactions.ts
26199
- var import_utils16 = require("@noble/hashes/utils");
26641
+ var import_utils17 = require("@noble/hashes/utils");
26200
26642
 
26201
26643
  // src/address/index.ts
26202
26644
  init_buffer();
@@ -26204,10 +26646,10 @@ init_buffer();
26204
26646
  // src/address/address.ts
26205
26647
  init_buffer();
26206
26648
  var import_secp256k112 = require("@noble/curves/secp256k1");
26207
- var import_utils13 = require("@noble/hashes/utils");
26649
+ var import_utils14 = require("@noble/hashes/utils");
26208
26650
  var import_base3 = require("@scure/base");
26209
26651
  var import_uuidv74 = require("uuidv7");
26210
- var import_utils14 = require("@noble/curves/abstract/utils");
26652
+ var import_utils15 = require("@noble/curves/abstract/utils");
26211
26653
  var AddressNetwork = {
26212
26654
  MAINNET: "sp",
26213
26655
  TESTNET: "spt",
@@ -26223,7 +26665,7 @@ function encodeSparkAddress(payload) {
26223
26665
  paymentIntentFields = payload.paymentIntentFields;
26224
26666
  }
26225
26667
  const sparkAddressProto = SparkAddress.create({
26226
- identityPublicKey: (0, import_utils13.hexToBytes)(payload.identityPublicKey),
26668
+ identityPublicKey: (0, import_utils14.hexToBytes)(payload.identityPublicKey),
26227
26669
  paymentIntentFields
26228
26670
  });
26229
26671
  const serializedPayload = SparkAddress.encode(sparkAddressProto).finish();
@@ -26255,7 +26697,7 @@ function decodeSparkAddress(address2, network) {
26255
26697
  });
26256
26698
  }
26257
26699
  const payload = SparkAddress.decode(import_base3.bech32m.fromWords(decoded.words));
26258
- const publicKey = (0, import_utils13.bytesToHex)(payload.identityPublicKey);
26700
+ const publicKey = (0, import_utils14.bytesToHex)(payload.identityPublicKey);
26259
26701
  isValidPublicKey(publicKey);
26260
26702
  const paymentIntentFields = payload.paymentIntentFields;
26261
26703
  return {
@@ -26263,8 +26705,8 @@ function decodeSparkAddress(address2, network) {
26263
26705
  network,
26264
26706
  paymentIntentFields: paymentIntentFields && {
26265
26707
  id: import_uuidv74.UUID.ofInner(paymentIntentFields.id).toString(),
26266
- assetIdentifier: paymentIntentFields.assetIdentifier ? (0, import_utils13.bytesToHex)(paymentIntentFields.assetIdentifier) : void 0,
26267
- assetAmount: (0, import_utils14.bytesToNumberBE)(paymentIntentFields.assetAmount),
26708
+ assetIdentifier: paymentIntentFields.assetIdentifier ? (0, import_utils14.bytesToHex)(paymentIntentFields.assetIdentifier) : void 0,
26709
+ assetAmount: (0, import_utils15.bytesToNumberBE)(paymentIntentFields.assetAmount),
26268
26710
  memo: paymentIntentFields.memo
26269
26711
  }
26270
26712
  };
@@ -26365,7 +26807,7 @@ var TokenTransactionService = class {
26365
26807
  if (!checkIfSelectedOutputsAreAvailable(
26366
26808
  outputsToUse,
26367
26809
  tokenOutputs,
26368
- (0, import_utils16.hexToBytes)(receiverOutputs[0].tokenPublicKey)
26810
+ (0, import_utils17.hexToBytes)(receiverOutputs[0].tokenPublicKey)
26369
26811
  )) {
26370
26812
  throw new ValidationError(
26371
26813
  "One or more selected TTXOs are not available",
@@ -26406,8 +26848,8 @@ var TokenTransactionService = class {
26406
26848
  this.config.getNetworkType()
26407
26849
  );
26408
26850
  return {
26409
- receiverSparkAddress: (0, import_utils16.hexToBytes)(receiverAddress.identityPublicKey),
26410
- tokenPublicKey: (0, import_utils16.hexToBytes)(transfer.tokenPublicKey),
26851
+ receiverSparkAddress: (0, import_utils17.hexToBytes)(receiverAddress.identityPublicKey),
26852
+ tokenPublicKey: (0, import_utils17.hexToBytes)(transfer.tokenPublicKey),
26411
26853
  tokenAmount: transfer.tokenAmount
26412
26854
  };
26413
26855
  });
@@ -26439,7 +26881,7 @@ var TokenTransactionService = class {
26439
26881
  const tokenOutputs = tokenOutputData.map((output) => ({
26440
26882
  ownerPublicKey: output.receiverSparkAddress,
26441
26883
  tokenPublicKey: output.tokenPublicKey,
26442
- tokenAmount: (0, import_utils15.numberToBytesBE)(output.tokenAmount, 16)
26884
+ tokenAmount: (0, import_utils16.numberToBytesBE)(output.tokenAmount, 16)
26443
26885
  }));
26444
26886
  if (availableTokenAmount > totalRequestedAmount) {
26445
26887
  const changeAmount = availableTokenAmount - totalRequestedAmount;
@@ -26447,7 +26889,7 @@ var TokenTransactionService = class {
26447
26889
  tokenOutputs.push({
26448
26890
  ownerPublicKey: await this.config.signer.getIdentityPublicKey(),
26449
26891
  tokenPublicKey: firstTokenPublicKey,
26450
- tokenAmount: (0, import_utils15.numberToBytesBE)(changeAmount, 16)
26892
+ tokenAmount: (0, import_utils16.numberToBytesBE)(changeAmount, 16)
26451
26893
  });
26452
26894
  }
26453
26895
  return {
@@ -26474,7 +26916,7 @@ var TokenTransactionService = class {
26474
26916
  const tokenOutputs = tokenOutputData.map((output) => ({
26475
26917
  ownerPublicKey: output.receiverSparkAddress,
26476
26918
  tokenPublicKey: output.tokenPublicKey,
26477
- tokenAmount: (0, import_utils15.numberToBytesBE)(output.tokenAmount, 16)
26919
+ tokenAmount: (0, import_utils16.numberToBytesBE)(output.tokenAmount, 16)
26478
26920
  }));
26479
26921
  if (availableTokenAmount > totalRequestedAmount) {
26480
26922
  const changeAmount = availableTokenAmount - totalRequestedAmount;
@@ -26482,7 +26924,7 @@ var TokenTransactionService = class {
26482
26924
  tokenOutputs.push({
26483
26925
  ownerPublicKey: await this.config.signer.getIdentityPublicKey(),
26484
26926
  tokenPublicKey: firstTokenPublicKey,
26485
- tokenAmount: (0, import_utils15.numberToBytesBE)(changeAmount, 16)
26927
+ tokenAmount: (0, import_utils16.numberToBytesBE)(changeAmount, 16)
26486
26928
  });
26487
26929
  }
26488
26930
  return {
@@ -26507,7 +26949,7 @@ var TokenTransactionService = class {
26507
26949
  for (const [_, operator] of Object.entries(
26508
26950
  this.config.getSigningOperators()
26509
26951
  )) {
26510
- operatorKeys.push((0, import_utils16.hexToBytes)(operator.identityPublicKey));
26952
+ operatorKeys.push((0, import_utils17.hexToBytes)(operator.identityPublicKey));
26511
26953
  }
26512
26954
  return operatorKeys;
26513
26955
  }
@@ -26591,7 +27033,7 @@ var TokenTransactionService = class {
26591
27033
  {
26592
27034
  field: "revocationCommitment",
26593
27035
  value: derivedRevocationCommitment,
26594
- expected: (0, import_utils15.bytesToHex)(outputsToSpendCommitments[outputIndex]),
27036
+ expected: (0, import_utils16.bytesToHex)(outputsToSpendCommitments[outputIndex]),
26595
27037
  outputIndex
26596
27038
  }
26597
27039
  )
@@ -26617,7 +27059,7 @@ var TokenTransactionService = class {
26617
27059
  threshold
26618
27060
  );
26619
27061
  }
26620
- return (0, import_utils15.bytesToHex)(finalTokenTransactionHash);
27062
+ return (0, import_utils16.bytesToHex)(finalTokenTransactionHash);
26621
27063
  }
26622
27064
  async broadcastTokenTransactionV1(tokenTransaction, signingOperators, outputsToSpendSigningPublicKeys, outputsToSpendCommitments) {
26623
27065
  const { finalTokenTransaction, finalTokenTransactionHash, threshold } = await this.startTokenTransaction(
@@ -26631,13 +27073,13 @@ var TokenTransactionService = class {
26631
27073
  finalTokenTransactionHash,
26632
27074
  signingOperators
26633
27075
  );
26634
- return (0, import_utils15.bytesToHex)(finalTokenTransactionHash);
27076
+ return (0, import_utils16.bytesToHex)(finalTokenTransactionHash);
26635
27077
  }
26636
27078
  async startTokenTransactionV0(tokenTransaction, signingOperators, outputsToSpendSigningPublicKeys, outputsToSpendCommitments) {
26637
27079
  const sparkClient = await this.connectionManager.createSparkClient(
26638
27080
  this.config.getCoordinatorAddress()
26639
27081
  );
26640
- const partialTokenTransactionHash = hashTokenTransaction(
27082
+ const partialTokenTransactionHash = hashTokenTransactionV0(
26641
27083
  tokenTransaction,
26642
27084
  true
26643
27085
  );
@@ -26718,7 +27160,7 @@ var TokenTransactionService = class {
26718
27160
  this.config.getThreshold()
26719
27161
  );
26720
27162
  const finalTokenTransaction = startResponse.finalTokenTransaction;
26721
- const finalTokenTransactionHash = hashTokenTransaction(
27163
+ const finalTokenTransactionHash = hashTokenTransactionV0(
26722
27164
  finalTokenTransaction,
26723
27165
  false
26724
27166
  );
@@ -26786,7 +27228,9 @@ var TokenTransactionService = class {
26786
27228
  const startResponse = await sparkClient.start_transaction(
26787
27229
  {
26788
27230
  identityPublicKey: await this.config.signer.getIdentityPublicKey(),
26789
- partialTokenTransaction: tokenTransaction
27231
+ partialTokenTransaction: tokenTransaction,
27232
+ validityDurationSeconds: await this.config.getTokenValidityDurationSeconds(),
27233
+ partialTokenTransactionOwnerSignatures: ownerSignaturesWithIndex
26790
27234
  },
26791
27235
  {
26792
27236
  retry: true,
@@ -26828,7 +27272,7 @@ var TokenTransactionService = class {
26828
27272
  const identityPublicKey = await this.config.signer.getIdentityPublicKey();
26829
27273
  const payload = {
26830
27274
  finalTokenTransactionHash,
26831
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27275
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
26832
27276
  };
26833
27277
  const payloadHash = await hashOperatorSpecificTokenTransactionSignablePayload(payload);
26834
27278
  let operatorSpecificSignatures = [];
@@ -26985,7 +27429,7 @@ var TokenTransactionService = class {
26985
27429
  []
26986
27430
  );
26987
27431
  unsortedTokenOutputs.forEach((output) => {
26988
- const tokenKey = (0, import_utils15.bytesToHex)(output.output.tokenPublicKey);
27432
+ const tokenKey = (0, import_utils16.bytesToHex)(output.output.tokenPublicKey);
26989
27433
  const index = output.previousTransactionVout;
26990
27434
  tokenOutputs.set(tokenKey, [
26991
27435
  { ...output, previousTransactionVout: index }
@@ -27001,7 +27445,7 @@ var TokenTransactionService = class {
27001
27445
  });
27002
27446
  }
27003
27447
  const exactMatch = tokenOutputs.find(
27004
- (item) => (0, import_utils15.bytesToNumberBE)(item.output.tokenAmount) === tokenAmount
27448
+ (item) => (0, import_utils16.bytesToNumberBE)(item.output.tokenAmount) === tokenAmount
27005
27449
  );
27006
27450
  if (exactMatch) {
27007
27451
  return [exactMatch];
@@ -27012,7 +27456,7 @@ var TokenTransactionService = class {
27012
27456
  for (const outputWithPreviousTransactionData of tokenOutputs) {
27013
27457
  if (remainingAmount <= 0n) break;
27014
27458
  selectedOutputs.push(outputWithPreviousTransactionData);
27015
- remainingAmount -= (0, import_utils15.bytesToNumberBE)(
27459
+ remainingAmount -= (0, import_utils16.bytesToNumberBE)(
27016
27460
  outputWithPreviousTransactionData.output.tokenAmount
27017
27461
  );
27018
27462
  }
@@ -27028,13 +27472,13 @@ var TokenTransactionService = class {
27028
27472
  if (strategy === "SMALL_FIRST") {
27029
27473
  tokenOutputs.sort((a, b) => {
27030
27474
  return Number(
27031
- (0, import_utils15.bytesToNumberBE)(a.output.tokenAmount) - (0, import_utils15.bytesToNumberBE)(b.output.tokenAmount)
27475
+ (0, import_utils16.bytesToNumberBE)(a.output.tokenAmount) - (0, import_utils16.bytesToNumberBE)(b.output.tokenAmount)
27032
27476
  );
27033
27477
  });
27034
27478
  } else {
27035
27479
  tokenOutputs.sort((a, b) => {
27036
27480
  return Number(
27037
- (0, import_utils15.bytesToNumberBE)(b.output.tokenAmount) - (0, import_utils15.bytesToNumberBE)(a.output.tokenAmount)
27481
+ (0, import_utils16.bytesToNumberBE)(b.output.tokenAmount) - (0, import_utils16.bytesToNumberBE)(a.output.tokenAmount)
27038
27482
  );
27039
27483
  });
27040
27484
  }
@@ -27042,7 +27486,7 @@ var TokenTransactionService = class {
27042
27486
  // Helper function for deciding if the signer public key is the identity public key
27043
27487
  async signMessageWithKey(message, publicKey) {
27044
27488
  const tokenSignatures = this.config.getTokenSignatures();
27045
- if ((0, import_utils15.bytesToHex)(publicKey) === (0, import_utils15.bytesToHex)(await this.config.signer.getIdentityPublicKey())) {
27489
+ if ((0, import_utils16.bytesToHex)(publicKey) === (0, import_utils16.bytesToHex)(await this.config.signer.getIdentityPublicKey())) {
27046
27490
  if (tokenSignatures === "SCHNORR") {
27047
27491
  return await this.config.signer.signSchnorrWithIdentityKey(message);
27048
27492
  } else {
@@ -27118,7 +27562,7 @@ var TokenTransactionService = class {
27118
27562
  }
27119
27563
  const payload = {
27120
27564
  finalTokenTransactionHash,
27121
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27565
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
27122
27566
  };
27123
27567
  const payloadHash = await hashOperatorSpecificTokenTransactionSignablePayload(payload);
27124
27568
  const ownerSignature = await this.signMessageWithKey(
@@ -27134,7 +27578,7 @@ var TokenTransactionService = class {
27134
27578
  for (let i = 0; i < transferInput.outputsToSpend.length; i++) {
27135
27579
  const payload = {
27136
27580
  finalTokenTransactionHash,
27137
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27581
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
27138
27582
  };
27139
27583
  const payloadHash = await hashOperatorSpecificTokenTransactionSignablePayload(payload);
27140
27584
  let ownerSignature;
@@ -27151,7 +27595,7 @@ var TokenTransactionService = class {
27151
27595
  }
27152
27596
  inputTtxoSignaturesPerOperator.push({
27153
27597
  ttxoSignatures,
27154
- operatorIdentityPublicKey: (0, import_utils16.hexToBytes)(operator.identityPublicKey)
27598
+ operatorIdentityPublicKey: (0, import_utils17.hexToBytes)(operator.identityPublicKey)
27155
27599
  });
27156
27600
  }
27157
27601
  return inputTtxoSignaturesPerOperator;
@@ -27163,7 +27607,7 @@ function isTokenTransaction(tokenTransaction) {
27163
27607
 
27164
27608
  // src/services/tree-creation.ts
27165
27609
  init_buffer();
27166
- var import_utils17 = require("@noble/curves/abstract/utils");
27610
+ var import_utils18 = require("@noble/curves/abstract/utils");
27167
27611
  var import_sha212 = require("@noble/hashes/sha2");
27168
27612
  var import_btc_signer5 = require("@scure/btc-signer");
27169
27613
  var INITIAL_TIME_LOCK3 = 2e3;
@@ -27212,7 +27656,7 @@ var TreeCreationService = class {
27212
27656
  request.source = {
27213
27657
  $case: "onChainUtxo",
27214
27658
  onChainUtxo: {
27215
- txid: (0, import_utils17.hexToBytes)(getTxId(parentTx)),
27659
+ txid: (0, import_utils18.hexToBytes)(getTxId(parentTx)),
27216
27660
  vout,
27217
27661
  rawTx: parentTx.toBytes(),
27218
27662
  network: this.config.getNetworkProto()
@@ -27253,7 +27697,7 @@ var TreeCreationService = class {
27253
27697
  request.source = {
27254
27698
  $case: "onChainUtxo",
27255
27699
  onChainUtxo: {
27256
- txid: (0, import_utils17.hexToBytes)(getTxId(parentTx)),
27700
+ txid: (0, import_utils18.hexToBytes)(getTxId(parentTx)),
27257
27701
  vout,
27258
27702
  rawTx: parentTx.toBytes(),
27259
27703
  network: this.config.getNetworkProto()
@@ -27624,13 +28068,13 @@ var TreeCreationService = class {
27624
28068
  };
27625
28069
 
27626
28070
  // src/spark-wallet/spark-wallet.ts
27627
- var import_lrc20_sdk3 = require("@buildonspark/lrc20-sdk");
28071
+ var import_lrc20_sdk4 = require("@buildonspark/lrc20-sdk");
27628
28072
  var import_sha213 = require("@noble/hashes/sha2");
27629
28073
  var import_eventemitter3 = require("eventemitter3");
27630
28074
 
27631
28075
  // src/services/signing.ts
27632
28076
  init_buffer();
27633
- var import_utils18 = require("@noble/curves/abstract/utils");
28077
+ var import_utils19 = require("@noble/curves/abstract/utils");
27634
28078
  var SigningService = class {
27635
28079
  config;
27636
28080
  constructor(config) {
@@ -27649,7 +28093,7 @@ var SigningService = class {
27649
28093
  }
27650
28094
  const nodeTx = getTxFromRawTxBytes(leaf.leaf.nodeTx);
27651
28095
  const nodeOutPoint = {
27652
- txid: (0, import_utils18.hexToBytes)(getTxId(nodeTx)),
28096
+ txid: (0, import_utils19.hexToBytes)(getTxId(nodeTx)),
27653
28097
  index: 0
27654
28098
  };
27655
28099
  const currRefundTx = getTxFromRawTxBytes(leaf.leaf.refundTx);
@@ -27707,15 +28151,15 @@ var SigningService = class {
27707
28151
 
27708
28152
  // src/tests/utils/test-faucet.ts
27709
28153
  init_buffer();
27710
- var import_utils19 = require("@noble/curves/abstract/utils");
28154
+ var import_utils20 = require("@noble/curves/abstract/utils");
27711
28155
  var import_secp256k115 = require("@noble/curves/secp256k1");
27712
28156
  var btc4 = __toESM(require("@scure/btc-signer"), 1);
27713
28157
  var import_btc_signer6 = require("@scure/btc-signer");
27714
- var import_utils20 = require("@scure/btc-signer/utils");
27715
- var STATIC_FAUCET_KEY = (0, import_utils19.hexToBytes)(
28158
+ var import_utils21 = require("@scure/btc-signer/utils");
28159
+ var STATIC_FAUCET_KEY = (0, import_utils20.hexToBytes)(
27716
28160
  "deadbeef1337cafe4242424242424242deadbeef1337cafe4242424242424242"
27717
28161
  );
27718
- var STATIC_MINING_KEY = (0, import_utils19.hexToBytes)(
28162
+ var STATIC_MINING_KEY = (0, import_utils20.hexToBytes)(
27719
28163
  "1337cafe4242deadbeef4242424242421337cafe4242deadbeef424242424242"
27720
28164
  );
27721
28165
  var SATS_PER_BTC = 1e8;
@@ -27778,7 +28222,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27778
28222
  if (!scanResult.success || scanResult.unspents.length === 0) {
27779
28223
  const blockHash = await this.generateToAddress(1, address2);
27780
28224
  const block = await this.getBlock(blockHash[0]);
27781
- const fundingTx = import_btc_signer6.Transaction.fromRaw((0, import_utils19.hexToBytes)(block.tx[0].hex), {
28225
+ const fundingTx = import_btc_signer6.Transaction.fromRaw((0, import_utils20.hexToBytes)(block.tx[0].hex), {
27782
28226
  allowUnknownOutputs: true
27783
28227
  });
27784
28228
  await this.generateToAddress(100, this.miningAddress);
@@ -27840,13 +28284,13 @@ var BitcoinFaucet = class _BitcoinFaucet {
27840
28284
  },
27841
28285
  STATIC_MINING_KEY
27842
28286
  );
27843
- await this.broadcastTx((0, import_utils19.bytesToHex)(signedSplitTx.extract()));
28287
+ await this.broadcastTx((0, import_utils20.bytesToHex)(signedSplitTx.extract()));
27844
28288
  const splitTxId = signedSplitTx.id;
27845
28289
  for (let i = 0; i < numCoinsToCreate; i++) {
27846
28290
  this.coins.push({
27847
28291
  key: STATIC_FAUCET_KEY,
27848
28292
  outpoint: {
27849
- txid: (0, import_utils19.hexToBytes)(splitTxId),
28293
+ txid: (0, import_utils20.hexToBytes)(splitTxId),
27850
28294
  index: i
27851
28295
  },
27852
28296
  txout: signedSplitTx.getOutput(i)
@@ -27874,7 +28318,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27874
28318
  coinToSend.txout,
27875
28319
  coinToSend.key
27876
28320
  );
27877
- await this.broadcastTx((0, import_utils19.bytesToHex)(signedTx.extract()));
28321
+ await this.broadcastTx((0, import_utils20.bytesToHex)(signedTx.extract()));
27878
28322
  }
27879
28323
  async signFaucetCoin(unsignedTx, fundingTxOut, key) {
27880
28324
  const pubKey = import_secp256k115.secp256k1.getPublicKey(key);
@@ -27894,7 +28338,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27894
28338
  new Array(unsignedTx.inputsLength).fill(fundingTxOut.amount)
27895
28339
  );
27896
28340
  const merkleRoot = new Uint8Array();
27897
- const tweakedKey = (0, import_utils20.taprootTweakPrivKey)(key, merkleRoot);
28341
+ const tweakedKey = (0, import_utils21.taprootTweakPrivKey)(key, merkleRoot);
27898
28342
  if (!tweakedKey)
27899
28343
  throw new Error("Invalid private key for taproot tweaking");
27900
28344
  const signature = import_secp256k115.schnorr.sign(sighash, tweakedKey);
@@ -27993,7 +28437,7 @@ var BitcoinFaucet = class _BitcoinFaucet {
27993
28437
  });
27994
28438
  }
27995
28439
  const signedTx = await this.signFaucetCoin(tx, coin.txout, coin.key);
27996
- const txHex = (0, import_utils19.bytesToHex)(signedTx.extract());
28440
+ const txHex = (0, import_utils20.bytesToHex)(signedTx.extract());
27997
28441
  await this.broadcastTx(txHex);
27998
28442
  const randomKey = import_secp256k115.secp256k1.utils.randomPrivateKey();
27999
28443
  const randomPubKey = import_secp256k115.secp256k1.getPublicKey(randomKey);
@@ -28011,18 +28455,18 @@ var BitcoinFaucet = class _BitcoinFaucet {
28011
28455
 
28012
28456
  // src/types/sdk-types.ts
28013
28457
  init_buffer();
28014
- var import_utils21 = require("@noble/curves/abstract/utils");
28458
+ var import_utils22 = require("@noble/curves/abstract/utils");
28015
28459
  function mapTreeNodeToWalletLeaf(proto) {
28016
28460
  return {
28017
28461
  id: proto.id,
28018
28462
  treeId: proto.treeId,
28019
28463
  value: proto.value,
28020
28464
  parentNodeId: proto.parentNodeId,
28021
- nodeTx: (0, import_utils21.bytesToHex)(proto.nodeTx),
28022
- refundTx: (0, import_utils21.bytesToHex)(proto.refundTx),
28465
+ nodeTx: (0, import_utils22.bytesToHex)(proto.nodeTx),
28466
+ refundTx: (0, import_utils22.bytesToHex)(proto.refundTx),
28023
28467
  vout: proto.vout,
28024
- verifyingPublicKey: (0, import_utils21.bytesToHex)(proto.verifyingPublicKey),
28025
- ownerIdentityPublicKey: (0, import_utils21.bytesToHex)(proto.ownerIdentityPublicKey),
28468
+ verifyingPublicKey: (0, import_utils22.bytesToHex)(proto.verifyingPublicKey),
28469
+ ownerIdentityPublicKey: (0, import_utils22.bytesToHex)(proto.ownerIdentityPublicKey),
28026
28470
  signingKeyshare: proto.signingKeyshare,
28027
28471
  status: proto.status,
28028
28472
  network: Network[proto.network]
@@ -28031,14 +28475,14 @@ function mapTreeNodeToWalletLeaf(proto) {
28031
28475
  function mapTransferLeafToWalletTransferLeaf(proto) {
28032
28476
  return {
28033
28477
  leaf: proto.leaf ? mapTreeNodeToWalletLeaf(proto.leaf) : void 0,
28034
- secretCipher: (0, import_utils21.bytesToHex)(proto.secretCipher),
28035
- signature: (0, import_utils21.bytesToHex)(proto.signature),
28036
- intermediateRefundTx: (0, import_utils21.bytesToHex)(proto.intermediateRefundTx)
28478
+ secretCipher: (0, import_utils22.bytesToHex)(proto.secretCipher),
28479
+ signature: (0, import_utils22.bytesToHex)(proto.signature),
28480
+ intermediateRefundTx: (0, import_utils22.bytesToHex)(proto.intermediateRefundTx)
28037
28481
  };
28038
28482
  }
28039
28483
  function mapTransferToWalletTransfer(proto, identityPublicKey) {
28040
- const receiverIdentityPublicKey = (0, import_utils21.bytesToHex)(proto.receiverIdentityPublicKey);
28041
- const senderIdentityPublicKey = (0, import_utils21.bytesToHex)(proto.senderIdentityPublicKey);
28484
+ const receiverIdentityPublicKey = (0, import_utils22.bytesToHex)(proto.receiverIdentityPublicKey);
28485
+ const senderIdentityPublicKey = (0, import_utils22.bytesToHex)(proto.senderIdentityPublicKey);
28042
28486
  return {
28043
28487
  id: proto.id,
28044
28488
  senderIdentityPublicKey,
@@ -28164,7 +28608,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28164
28608
  try {
28165
28609
  if (event?.$case === "transfer" && event.transfer.transfer && event.transfer.transfer.type !== 40 /* COUNTER_SWAP */) {
28166
28610
  const { senderIdentityPublicKey, receiverIdentityPublicKey } = event.transfer.transfer;
28167
- if (event.transfer.transfer && !(0, import_utils22.equalBytes)(senderIdentityPublicKey, receiverIdentityPublicKey)) {
28611
+ if (event.transfer.transfer && !(0, import_utils23.equalBytes)(senderIdentityPublicKey, receiverIdentityPublicKey)) {
28168
28612
  await this.claimTransfer({
28169
28613
  transfer: event.transfer.transfer,
28170
28614
  emit: true,
@@ -28236,7 +28680,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28236
28680
  setTimeout(maybeUnref, 100);
28237
28681
  }
28238
28682
  };
28239
- if (import_core12.isNode) {
28683
+ if (import_core14.isNode) {
28240
28684
  maybeUnref();
28241
28685
  }
28242
28686
  const claimedTransfersIds = await this.claimTransfers();
@@ -28326,10 +28770,10 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28326
28770
  leavesToIgnore.add(nodeId);
28327
28771
  continue;
28328
28772
  }
28329
- if (leaf.status !== operatorLeaf.status || !leaf.signingKeyshare || !operatorLeaf.signingKeyshare || !(0, import_utils22.equalBytes)(
28773
+ if (leaf.status !== operatorLeaf.status || !leaf.signingKeyshare || !operatorLeaf.signingKeyshare || !(0, import_utils23.equalBytes)(
28330
28774
  leaf.signingKeyshare.publicKey,
28331
28775
  operatorLeaf.signingKeyshare.publicKey
28332
- ) || !(0, import_utils22.equalBytes)(leaf.nodeTx, operatorLeaf.nodeTx) || !(0, import_utils22.equalBytes)(leaf.refundTx, operatorLeaf.refundTx)) {
28776
+ ) || !(0, import_utils23.equalBytes)(leaf.nodeTx, operatorLeaf.nodeTx) || !(0, import_utils23.equalBytes)(leaf.refundTx, operatorLeaf.refundTx)) {
28333
28777
  leavesToIgnore.add(nodeId);
28334
28778
  }
28335
28779
  }
@@ -28337,7 +28781,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28337
28781
  }
28338
28782
  }
28339
28783
  const verifyKey = (pubkey1, pubkey2, verifyingKey) => {
28340
- return (0, import_utils22.equalBytes)(addPublicKeys(pubkey1, pubkey2), verifyingKey);
28784
+ return (0, import_utils23.equalBytes)(addPublicKeys(pubkey1, pubkey2), verifyingKey);
28341
28785
  };
28342
28786
  for (const [id, leaf] of Object.entries(leaves.nodes)) {
28343
28787
  if (!verifyKey(
@@ -28471,7 +28915,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28471
28915
  * @returns {Promise<string>} The identity public key as a hex string.
28472
28916
  */
28473
28917
  async getIdentityPublicKey() {
28474
- return (0, import_utils22.bytesToHex)(await this.config.signer.getIdentityPublicKey());
28918
+ return (0, import_utils23.bytesToHex)(await this.config.signer.getIdentityPublicKey());
28475
28919
  }
28476
28920
  /**
28477
28921
  * Gets the Spark address of the wallet.
@@ -28481,7 +28925,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28481
28925
  async getSparkAddress() {
28482
28926
  if (!this.sparkAddress) {
28483
28927
  this.sparkAddress = encodeSparkAddress({
28484
- identityPublicKey: (0, import_utils22.bytesToHex)(
28928
+ identityPublicKey: (0, import_utils23.bytesToHex)(
28485
28929
  await this.config.signer.getIdentityPublicKey()
28486
28930
  ),
28487
28931
  network: this.config.getNetworkType()
@@ -28518,14 +28962,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28518
28962
  isValidPublicKey(assetIdentifier);
28519
28963
  }
28520
28964
  const paymentRequest = encodeSparkAddress({
28521
- identityPublicKey: (0, import_utils22.bytesToHex)(
28965
+ identityPublicKey: (0, import_utils23.bytesToHex)(
28522
28966
  await this.config.signer.getIdentityPublicKey()
28523
28967
  ),
28524
28968
  network: this.config.getNetworkType(),
28525
28969
  paymentIntentFields: {
28526
28970
  id: (0, import_uuidv75.uuidv7obj)().bytes,
28527
- assetIdentifier: assetIdentifier ? (0, import_utils22.hexToBytes)(assetIdentifier) : void 0,
28528
- assetAmount: (0, import_utils22.numberToVarBytesBE)(assetAmount),
28971
+ assetIdentifier: assetIdentifier ? (0, import_utils23.hexToBytes)(assetIdentifier) : void 0,
28972
+ assetAmount: (0, import_utils23.numberToVarBytesBE)(assetAmount),
28529
28973
  memo
28530
28974
  }
28531
28975
  });
@@ -28570,12 +29014,12 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28570
29014
  mnemonic = mnemonicOrSeed;
28571
29015
  seed = await this.config.signer.mnemonicToSeed(mnemonicOrSeed);
28572
29016
  } else {
28573
- seed = (0, import_utils22.hexToBytes)(mnemonicOrSeed);
29017
+ seed = (0, import_utils23.hexToBytes)(mnemonicOrSeed);
28574
29018
  }
28575
29019
  }
28576
29020
  await this.initWalletFromSeed(seed, accountNumber);
28577
29021
  const network = this.config.getNetwork();
28578
- this.lrc20Wallet = await import_lrc20_sdk3.LRCWallet.create(
29022
+ this.lrc20Wallet = await import_lrc20_sdk4.LRCWallet.create(
28579
29023
  LRC_WALLET_NETWORK[network],
28580
29024
  LRC_WALLET_NETWORK_TYPE[network],
28581
29025
  this.config.lrc20ApiConfig,
@@ -28675,7 +29119,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28675
29119
  );
28676
29120
  const { transfer, signatureMap } = await this.transferService.startSwapSignRefund(
28677
29121
  leafKeyTweaks,
28678
- (0, import_utils22.hexToBytes)(this.config.getSspIdentityPublicKey()),
29122
+ (0, import_utils23.hexToBytes)(this.config.getSspIdentityPublicKey()),
28679
29123
  new Date(Date.now() + 2 * 60 * 1e3)
28680
29124
  );
28681
29125
  try {
@@ -28693,10 +29137,10 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28693
29137
  const userLeaves = [];
28694
29138
  userLeaves.push({
28695
29139
  leaf_id: transfer.leaves[0].leaf.id,
28696
- raw_unsigned_refund_transaction: (0, import_utils22.bytesToHex)(
29140
+ raw_unsigned_refund_transaction: (0, import_utils23.bytesToHex)(
28697
29141
  transfer.leaves[0].intermediateRefundTx
28698
29142
  ),
28699
- adaptor_added_signature: (0, import_utils22.bytesToHex)(adaptorSignature)
29143
+ adaptor_added_signature: (0, import_utils23.bytesToHex)(adaptorSignature)
28700
29144
  });
28701
29145
  for (let i = 1; i < transfer.leaves.length; i++) {
28702
29146
  const leaf = transfer.leaves[i];
@@ -28713,14 +29157,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28713
29157
  );
28714
29158
  userLeaves.push({
28715
29159
  leaf_id: leaf.leaf.id,
28716
- raw_unsigned_refund_transaction: (0, import_utils22.bytesToHex)(
29160
+ raw_unsigned_refund_transaction: (0, import_utils23.bytesToHex)(
28717
29161
  leaf.intermediateRefundTx
28718
29162
  ),
28719
- adaptor_added_signature: (0, import_utils22.bytesToHex)(signature)
29163
+ adaptor_added_signature: (0, import_utils23.bytesToHex)(signature)
28720
29164
  });
28721
29165
  }
28722
29166
  const sspClient = this.getSspClient();
28723
- const adaptorPubkey = (0, import_utils22.bytesToHex)(
29167
+ const adaptorPubkey = (0, import_utils23.bytesToHex)(
28724
29168
  import_secp256k116.secp256k1.getPublicKey(adaptorPrivateKey)
28725
29169
  );
28726
29170
  let request = null;
@@ -28761,12 +29205,12 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28761
29205
  throw new Error(`Leaf not found for node ${nodeId}`);
28762
29206
  }
28763
29207
  const nodeTx = getTxFromRawTxBytes(node.nodeTx);
28764
- const refundTxBytes = (0, import_utils22.hexToBytes)(leaf.rawUnsignedRefundTransaction);
29208
+ const refundTxBytes = (0, import_utils23.hexToBytes)(leaf.rawUnsignedRefundTransaction);
28765
29209
  const refundTx = getTxFromRawTxBytes(refundTxBytes);
28766
29210
  const sighash = getSigHashFromTx(refundTx, 0, nodeTx.getOutput(0));
28767
29211
  const nodePublicKey = node.verifyingPublicKey;
28768
29212
  const taprootKey = computeTaprootKeyNoScript(nodePublicKey.slice(1));
28769
- const adaptorSignatureBytes = (0, import_utils22.hexToBytes)(leaf.adaptorSignedSignature);
29213
+ const adaptorSignatureBytes = (0, import_utils23.hexToBytes)(leaf.adaptorSignedSignature);
28770
29214
  applyAdaptorToSignature(
28771
29215
  taprootKey.slice(1),
28772
29216
  sighash,
@@ -28780,7 +29224,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28780
29224
  signatureMap
28781
29225
  );
28782
29226
  const completeResponse = await sspClient.completeLeaveSwap({
28783
- adaptorSecretKey: (0, import_utils22.bytesToHex)(adaptorPrivateKey),
29227
+ adaptorSecretKey: (0, import_utils23.bytesToHex)(adaptorPrivateKey),
28784
29228
  userOutboundTransferExternalId: transfer.id,
28785
29229
  leavesSwapRequestId: request.id
28786
29230
  });
@@ -28806,7 +29250,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28806
29250
  limit,
28807
29251
  offset
28808
29252
  );
28809
- const identityPublicKey = (0, import_utils22.bytesToHex)(
29253
+ const identityPublicKey = (0, import_utils23.bytesToHex)(
28810
29254
  await this.config.signer.getIdentityPublicKey()
28811
29255
  );
28812
29256
  return {
@@ -28827,14 +29271,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28827
29271
  const lrc20Client = await this.lrc20ConnectionManager.createLrc20Client();
28828
29272
  const { balance, tokenBalances } = await this.getBalance();
28829
29273
  const tokenInfo = await lrc20Client.getTokenPubkeyInfo({
28830
- publicKeys: Array.from(tokenBalances.keys()).map(import_utils22.hexToBytes)
29274
+ publicKeys: Array.from(tokenBalances.keys()).map(import_utils23.hexToBytes)
28831
29275
  });
28832
29276
  return tokenInfo.tokenPubkeyInfos.map((info) => ({
28833
- tokenPublicKey: (0, import_utils22.bytesToHex)(info.announcement.publicKey.publicKey),
29277
+ tokenPublicKey: (0, import_utils23.bytesToHex)(info.announcement.publicKey.publicKey),
28834
29278
  tokenName: info.announcement.name,
28835
29279
  tokenSymbol: info.announcement.symbol,
28836
- tokenDecimals: Number((0, import_utils22.bytesToNumberBE)(info.announcement.decimal)),
28837
- maxSupply: (0, import_utils22.bytesToNumberBE)(info.announcement.maxSupply)
29280
+ tokenDecimals: Number((0, import_utils23.bytesToNumberBE)(info.announcement.decimal)),
29281
+ maxSupply: (0, import_utils23.bytesToNumberBE)(info.announcement.maxSupply)
28838
29282
  }));
28839
29283
  }
28840
29284
  /**
@@ -28863,11 +29307,11 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28863
29307
  async getTokenBalance() {
28864
29308
  const lrc20Client = await this.lrc20ConnectionManager.createLrc20Client();
28865
29309
  const tokenInfo = await lrc20Client.getTokenPubkeyInfo({
28866
- publicKeys: Array.from(this.tokenOutputs.keys()).map(import_utils22.hexToBytes)
29310
+ publicKeys: Array.from(this.tokenOutputs.keys()).map(import_utils23.hexToBytes)
28867
29311
  });
28868
29312
  const result = /* @__PURE__ */ new Map();
28869
29313
  for (const info of tokenInfo.tokenPubkeyInfos) {
28870
- const tokenPublicKey = (0, import_utils22.bytesToHex)(
29314
+ const tokenPublicKey = (0, import_utils23.bytesToHex)(
28871
29315
  info.announcement.publicKey.publicKey
28872
29316
  );
28873
29317
  const leaves = this.tokenOutputs.get(tokenPublicKey);
@@ -28877,8 +29321,8 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
28877
29321
  tokenPublicKey,
28878
29322
  tokenName: info.announcement.name,
28879
29323
  tokenSymbol: info.announcement.symbol,
28880
- tokenDecimals: Number((0, import_utils22.bytesToNumberBE)(info.announcement.decimal)),
28881
- maxSupply: (0, import_utils22.bytesToNumberBE)(info.announcement.maxSupply)
29324
+ tokenDecimals: Number((0, import_utils23.bytesToNumberBE)(info.announcement.decimal)),
29325
+ maxSupply: (0, import_utils23.bytesToNumberBE)(info.announcement.maxSupply)
28882
29326
  }
28883
29327
  });
28884
29328
  }
@@ -29012,7 +29456,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29012
29456
  if (network === BitcoinNetwork_default.FUTURE_VALUE) {
29013
29457
  network = BitcoinNetwork_default.REGTEST;
29014
29458
  }
29015
- const depositSecretKey = (0, import_utils22.bytesToHex)(
29459
+ const depositSecretKey = (0, import_utils23.bytesToHex)(
29016
29460
  await this.config.signer.getStaticDepositSecretKey(0)
29017
29461
  );
29018
29462
  const message = await this.getStaticDepositSigningPayload(
@@ -29025,7 +29469,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29025
29469
  );
29026
29470
  const hashBuffer = (0, import_sha213.sha256)(message);
29027
29471
  const signatureBytes = await this.config.signer.signMessageWithIdentityKey(hashBuffer);
29028
- const signature = (0, import_utils22.bytesToHex)(signatureBytes);
29472
+ const signature = (0, import_utils23.bytesToHex)(signatureBytes);
29029
29473
  const response = await this.sspClient.claimStaticDeposit({
29030
29474
  transactionId,
29031
29475
  outputIndex,
@@ -29110,7 +29554,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29110
29554
  networkJSON.toLowerCase(),
29111
29555
  2 /* Refund */,
29112
29556
  creditAmountSats,
29113
- (0, import_utils22.bytesToHex)(spendTxSighash)
29557
+ (0, import_utils23.bytesToHex)(spendTxSighash)
29114
29558
  );
29115
29559
  const hashBuffer = (0, import_sha213.sha256)(message);
29116
29560
  const swapResponseUserSignature = await this.config.signer.signMessageWithIdentityKey(hashBuffer);
@@ -29120,7 +29564,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29120
29564
  const transferId = (0, import_uuidv75.uuidv7)();
29121
29565
  const swapResponse = await sparkClient.initiate_utxo_swap({
29122
29566
  onChainUtxo: {
29123
- txid: (0, import_utils22.hexToBytes)(depositTransactionId),
29567
+ txid: (0, import_utils23.hexToBytes)(depositTransactionId),
29124
29568
  vout: outputIndex,
29125
29569
  network: networkType
29126
29570
  },
@@ -29197,7 +29641,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29197
29641
  creditAmountView.setUint32(0, lowerHalf, true);
29198
29642
  creditAmountView.setUint32(4, upperHalf, true);
29199
29643
  parts.push(new Uint8Array(creditAmountBuffer));
29200
- parts.push((0, import_utils22.hexToBytes)(sspSignature));
29644
+ parts.push((0, import_utils23.hexToBytes)(sspSignature));
29201
29645
  const totalLength = parts.reduce((sum, part) => sum + part.length, 0);
29202
29646
  const payload = new Uint8Array(totalLength);
29203
29647
  let offset = 0;
@@ -29547,9 +29991,9 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29547
29991
  this.config.getNetworkType()
29548
29992
  );
29549
29993
  const signerIdentityPublicKey = await this.config.signer.getIdentityPublicKey();
29550
- const isSelfTransfer = (0, import_utils22.equalBytes)(
29994
+ const isSelfTransfer = (0, import_utils23.equalBytes)(
29551
29995
  signerIdentityPublicKey,
29552
- (0, import_utils22.hexToBytes)(receiverAddress.identityPublicKey)
29996
+ (0, import_utils23.hexToBytes)(receiverAddress.identityPublicKey)
29553
29997
  );
29554
29998
  return await this.withLeaves(async () => {
29555
29999
  let leavesToSend = await this.selectLeaves(amountSats);
@@ -29566,7 +30010,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29566
30010
  );
29567
30011
  const transfer = await this.transferService.sendTransferWithKeyTweaks(
29568
30012
  leafKeyTweaks,
29569
- (0, import_utils22.hexToBytes)(receiverAddress.identityPublicKey)
30013
+ (0, import_utils23.hexToBytes)(receiverAddress.identityPublicKey)
29570
30014
  );
29571
30015
  const leavesToRemove = new Set(leavesToSend.map((leaf) => leaf.id));
29572
30016
  this.leaves = this.leaves.filter((leaf) => !leavesToRemove.has(leaf.id));
@@ -29582,7 +30026,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29582
30026
  }
29583
30027
  return mapTransferToWalletTransfer(
29584
30028
  transfer,
29585
- (0, import_utils22.bytesToHex)(await this.config.signer.getIdentityPublicKey())
30029
+ (0, import_utils23.bytesToHex)(await this.config.signer.getIdentityPublicKey())
29586
30030
  );
29587
30031
  });
29588
30032
  }
@@ -29906,7 +30350,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29906
30350
  const invoice2 = await sspClient.requestLightningReceive({
29907
30351
  amountSats: amountSats2,
29908
30352
  network: bitcoinNetwork,
29909
- paymentHash: (0, import_utils22.bytesToHex)(paymentHash),
30353
+ paymentHash: (0, import_utils23.bytesToHex)(paymentHash),
29910
30354
  expirySecs: expirySeconds,
29911
30355
  memo: memo2,
29912
30356
  includeSparkAddress,
@@ -29920,7 +30364,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29920
30364
  const sparkFallbackAddress = decodeInvoice(
29921
30365
  invoice2.invoice.encodedInvoice
29922
30366
  ).fallbackAddress;
29923
- if (sparkFallbackAddress && isValidSparkFallback((0, import_utils22.hexToBytes)(sparkFallbackAddress))) {
30367
+ if (sparkFallbackAddress && isValidSparkFallback((0, import_utils23.hexToBytes)(sparkFallbackAddress))) {
29924
30368
  const invoiceIdentityPubkey = sparkFallbackAddress.slice(6);
29925
30369
  const expectedIdentityPubkey = receiverIdentityPubkey2 ?? await this.getIdentityPublicKey();
29926
30370
  if (invoiceIdentityPubkey !== expectedIdentityPubkey) {
@@ -29961,12 +30405,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29961
30405
  * @param {Object} params - Parameters for paying the invoice
29962
30406
  * @param {string} params.invoice - The BOLT11-encoded Lightning invoice to pay
29963
30407
  * @param {boolean} [params.preferSpark] - Whether to prefer a spark transfer over lightning for the payment
30408
+ * @param {number} [params.amountSatsToSend] - The amount in sats to send. This is only valid for 0 amount lightning invoices.
29964
30409
  * @returns {Promise<LightningSendRequest>} The Lightning payment request details
29965
30410
  */
29966
30411
  async payLightningInvoice({
29967
30412
  invoice,
29968
30413
  maxFeeSats,
29969
- preferSpark = false
30414
+ preferSpark = false,
30415
+ amountSatsToSend
29970
30416
  }) {
29971
30417
  const invoiceNetwork = getNetworkFromInvoice(invoice);
29972
30418
  const walletNetwork = this.config.getNetwork();
@@ -29981,11 +30427,40 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
29981
30427
  );
29982
30428
  }
29983
30429
  const decodedInvoice = decodeInvoice(invoice);
29984
- const amountSats = decodedInvoice.amountMSats !== null ? Number(decodedInvoice.amountMSats / 1000n) : 0;
30430
+ const amountMSats = decodedInvoice.amountMSats;
30431
+ const isZeroAmountInvoice = !amountMSats;
30432
+ if (!isZeroAmountInvoice && amountSatsToSend !== void 0) {
30433
+ throw new ValidationError(
30434
+ "Invalid amount. User can only specify amountSatsToSend for 0 amount lightning invoice",
30435
+ {
30436
+ field: "amountMSats",
30437
+ value: Number(amountMSats),
30438
+ expected: "0"
30439
+ }
30440
+ );
30441
+ }
30442
+ if (isZeroAmountInvoice && amountSatsToSend === void 0) {
30443
+ throw new ValidationError(
30444
+ "Invalid amount. User must specify amountSatsToSend for 0 amount lightning invoice",
30445
+ {
30446
+ field: "amountMSats",
30447
+ value: Number(amountMSats),
30448
+ expected: "0"
30449
+ }
30450
+ );
30451
+ }
30452
+ const amountSats = isZeroAmountInvoice ? amountSatsToSend : Number(amountMSats / 1000n);
30453
+ if (isNaN(amountSats) || amountSats <= 0) {
30454
+ throw new ValidationError("Invalid amount", {
30455
+ field: "amountSats",
30456
+ value: amountSats,
30457
+ expected: "greater than 0"
30458
+ });
30459
+ }
29985
30460
  const sparkFallbackAddress = decodedInvoice.fallbackAddress;
29986
30461
  const paymentHash = decodedInvoice.paymentHash;
29987
30462
  if (preferSpark) {
29988
- if (sparkFallbackAddress === void 0 || isValidSparkFallback((0, import_utils22.hexToBytes)(sparkFallbackAddress)) === false) {
30463
+ if (sparkFallbackAddress === void 0 || isValidSparkFallback((0, import_utils23.hexToBytes)(sparkFallbackAddress)) === false) {
29989
30464
  console.warn(
29990
30465
  "No valid spark address found in invoice. Defaulting to lightning."
29991
30466
  );
@@ -30003,15 +30478,9 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30003
30478
  }
30004
30479
  return await this.withLeaves(async () => {
30005
30480
  const sspClient = this.getSspClient();
30006
- if (isNaN(amountSats) || amountSats <= 0) {
30007
- throw new ValidationError("Invalid amount", {
30008
- field: "amountSats",
30009
- value: amountSats,
30010
- expected: "positive number"
30011
- });
30012
- }
30013
30481
  const feeEstimate = await this.getLightningSendFeeEstimate({
30014
- encodedInvoice: invoice
30482
+ encodedInvoice: invoice,
30483
+ amountSats: isZeroAmountInvoice ? amountSatsToSend : void 0
30015
30484
  });
30016
30485
  if (maxFeeSats < feeEstimate) {
30017
30486
  throw new ValidationError("maxFeeSats does not cover fee estimate", {
@@ -30043,25 +30512,27 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30043
30512
  );
30044
30513
  const swapResponse = await this.lightningService.swapNodesForPreimage({
30045
30514
  leaves: leavesToSend,
30046
- receiverIdentityPubkey: (0, import_utils22.hexToBytes)(
30515
+ receiverIdentityPubkey: (0, import_utils23.hexToBytes)(
30047
30516
  this.config.getSspIdentityPublicKey()
30048
30517
  ),
30049
- paymentHash: (0, import_utils22.hexToBytes)(paymentHash),
30518
+ paymentHash: (0, import_utils23.hexToBytes)(paymentHash),
30050
30519
  isInboundPayment: false,
30051
30520
  invoiceString: invoice,
30052
- feeSats: feeEstimate
30521
+ feeSats: feeEstimate,
30522
+ amountSatsToSend
30053
30523
  });
30054
30524
  if (!swapResponse.transfer) {
30055
30525
  throw new Error("Failed to swap nodes for preimage");
30056
30526
  }
30057
- const transfer = await this.transferService.sendTransferTweakKey(
30527
+ await this.transferService.deliverTransferPackage(
30058
30528
  swapResponse.transfer,
30059
30529
  leavesToSend,
30060
30530
  /* @__PURE__ */ new Map()
30061
30531
  );
30062
30532
  const sspResponse = await sspClient.requestLightningSend({
30063
30533
  encodedInvoice: invoice,
30064
- idempotencyKey: paymentHash
30534
+ idempotencyKey: paymentHash,
30535
+ amountSats: isZeroAmountInvoice ? amountSatsToSend : void 0
30065
30536
  });
30066
30537
  if (!sspResponse) {
30067
30538
  throw new Error("Failed to contact SSP");
@@ -30078,14 +30549,18 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30078
30549
  * @returns {Promise<number>} Fee estimate for sending Lightning payments
30079
30550
  */
30080
30551
  async getLightningSendFeeEstimate({
30081
- encodedInvoice
30552
+ encodedInvoice,
30553
+ amountSats
30082
30554
  }) {
30083
30555
  const sspClient = this.getSspClient();
30084
- const feeEstimate = await sspClient.getLightningSendFeeEstimate(encodedInvoice);
30556
+ const feeEstimate = await sspClient.getLightningSendFeeEstimate(
30557
+ encodedInvoice,
30558
+ amountSats
30559
+ );
30085
30560
  if (!feeEstimate) {
30086
30561
  throw new Error("Failed to get lightning send fee estimate");
30087
30562
  }
30088
- const satsFeeEstimate = (0, import_core12.mapCurrencyAmount)(feeEstimate.feeEstimate);
30563
+ const satsFeeEstimate = (0, import_core14.mapCurrencyAmount)(feeEstimate.feeEstimate);
30089
30564
  return Math.ceil(satsFeeEstimate.sats);
30090
30565
  }
30091
30566
  // ***** Tree Creation Flow *****
@@ -30243,11 +30718,11 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30243
30718
  const connectorOutputs = [];
30244
30719
  for (let i = 0; i < connectorTx.outputsLength - 1; i++) {
30245
30720
  connectorOutputs.push({
30246
- txid: (0, import_utils22.hexToBytes)(connectorTxId),
30721
+ txid: (0, import_utils23.hexToBytes)(connectorTxId),
30247
30722
  index: i
30248
30723
  });
30249
30724
  }
30250
- const sspPubIdentityKey = (0, import_utils22.hexToBytes)(this.config.getSspIdentityPublicKey());
30725
+ const sspPubIdentityKey = (0, import_utils23.hexToBytes)(this.config.getSspIdentityPublicKey());
30251
30726
  const transfer = await this.coopExitService.getConnectorRefundSignatures({
30252
30727
  leaves: leafKeyTweaks,
30253
30728
  exitTxId: coopExitTxId,
@@ -30334,7 +30809,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30334
30809
  );
30335
30810
  const groupedOutputs = /* @__PURE__ */ new Map();
30336
30811
  filteredTokenOutputs.forEach((output) => {
30337
- const tokenKey = (0, import_utils22.bytesToHex)(output.output.tokenPublicKey);
30812
+ const tokenKey = (0, import_utils23.bytesToHex)(output.output.tokenPublicKey);
30338
30813
  const index = output.previousTransactionVout;
30339
30814
  if (!groupedOutputs.has(tokenKey)) {
30340
30815
  groupedOutputs.set(tokenKey, []);
@@ -30432,14 +30907,14 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30432
30907
  let queryParams;
30433
30908
  if (tokenTransactionHashes?.length) {
30434
30909
  queryParams = {
30435
- tokenPublicKeys: tokenPublicKeys?.map(import_utils22.hexToBytes),
30436
- ownerPublicKeys: [(0, import_utils22.hexToBytes)(await this.getIdentityPublicKey())],
30437
- tokenTransactionHashes: tokenTransactionHashes.map(import_utils22.hexToBytes)
30910
+ tokenPublicKeys: tokenPublicKeys?.map(import_utils23.hexToBytes),
30911
+ ownerPublicKeys: [(0, import_utils23.hexToBytes)(await this.getIdentityPublicKey())],
30912
+ tokenTransactionHashes: tokenTransactionHashes.map(import_utils23.hexToBytes)
30438
30913
  };
30439
30914
  } else {
30440
30915
  queryParams = {
30441
- tokenPublicKeys: tokenPublicKeys?.map(import_utils22.hexToBytes),
30442
- ownerPublicKeys: [(0, import_utils22.hexToBytes)(await this.getIdentityPublicKey())]
30916
+ tokenPublicKeys: tokenPublicKeys?.map(import_utils23.hexToBytes),
30917
+ ownerPublicKeys: [(0, import_utils23.hexToBytes)(await this.getIdentityPublicKey())]
30443
30918
  };
30444
30919
  }
30445
30920
  const response = await sparkClient.query_token_transactions(queryParams);
@@ -30464,7 +30939,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30464
30939
  hash,
30465
30940
  compact
30466
30941
  );
30467
- return (0, import_utils22.bytesToHex)(signature);
30942
+ return (0, import_utils23.bytesToHex)(signature);
30468
30943
  }
30469
30944
  /**
30470
30945
  * Validates a message with the identity key.
@@ -30476,7 +30951,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30476
30951
  async validateMessageWithIdentityKey(message, signature) {
30477
30952
  const hash = (0, import_sha213.sha256)(message);
30478
30953
  if (typeof signature === "string") {
30479
- signature = (0, import_utils22.hexToBytes)(signature);
30954
+ signature = (0, import_utils23.hexToBytes)(signature);
30480
30955
  }
30481
30956
  return this.config.signer.validateMessageWithIdentityKey(hash, signature);
30482
30957
  }
@@ -30489,7 +30964,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30489
30964
  */
30490
30965
  async signTransaction(txHex, keyType = "auto-detect") {
30491
30966
  try {
30492
- const tx = import_btc_signer7.Transaction.fromRaw((0, import_utils22.hexToBytes)(txHex));
30967
+ const tx = import_btc_signer7.Transaction.fromRaw((0, import_utils23.hexToBytes)(txHex));
30493
30968
  let publicKey;
30494
30969
  switch (keyType.toLowerCase()) {
30495
30970
  case "identity":
@@ -30522,7 +30997,7 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30522
30997
  publicKey,
30523
30998
  this.config.getNetwork()
30524
30999
  );
30525
- if ((0, import_utils22.bytesToHex)(script) === (0, import_utils22.bytesToHex)(identityScript)) {
31000
+ if ((0, import_utils23.bytesToHex)(script) === (0, import_utils23.bytesToHex)(identityScript)) {
30526
31001
  try {
30527
31002
  this.config.signer.signTransactionIndex(tx, i, publicKey);
30528
31003
  inputsSigned++;
@@ -30566,13 +31041,13 @@ var SparkWallet = class _SparkWallet extends import_eventemitter3.EventEmitter {
30566
31041
  depositPubKey,
30567
31042
  this.config.getNetwork()
30568
31043
  );
30569
- if ((0, import_utils22.bytesToHex)(script) === (0, import_utils22.bytesToHex)(identityScript)) {
31044
+ if ((0, import_utils23.bytesToHex)(script) === (0, import_utils23.bytesToHex)(identityScript)) {
30570
31045
  return {
30571
31046
  publicKey: identityPubKey,
30572
31047
  keyType: "identity"
30573
31048
  };
30574
31049
  }
30575
- if ((0, import_utils22.bytesToHex)(script) === (0, import_utils22.bytesToHex)(depositScript)) {
31050
+ if ((0, import_utils23.bytesToHex)(script) === (0, import_utils23.bytesToHex)(depositScript)) {
30576
31051
  return {
30577
31052
  publicKey: depositPubKey,
30578
31053
  keyType: "deposit"
@@ -31082,7 +31557,7 @@ async function isTxBroadcast(txid, baseUrl, network) {
31082
31557
 
31083
31558
  // src/utils/unilateral-exit.ts
31084
31559
  init_buffer();
31085
- var import_utils23 = require("@noble/curves/abstract/utils");
31560
+ var import_utils24 = require("@noble/curves/abstract/utils");
31086
31561
  var import_legacy = require("@noble/hashes/legacy");
31087
31562
  var import_sha214 = require("@noble/hashes/sha2");
31088
31563
  var btc5 = __toESM(require("@scure/btc-signer"), 1);
@@ -31097,7 +31572,7 @@ function isEphemeralAnchorOutput(script, amount) {
31097
31572
  }
31098
31573
  async function constructUnilateralExitTxs(nodeHexStrings, sparkClient, network) {
31099
31574
  const result = [];
31100
- const nodes = nodeHexStrings.map((hex) => TreeNode.decode((0, import_utils23.hexToBytes)(hex)));
31575
+ const nodes = nodeHexStrings.map((hex) => TreeNode.decode((0, import_utils24.hexToBytes)(hex)));
31101
31576
  const nodeMap = /* @__PURE__ */ new Map();
31102
31577
  for (const node of nodes) {
31103
31578
  nodeMap.set(node.id, node);
@@ -31153,10 +31628,10 @@ async function constructUnilateralExitTxs(nodeHexStrings, sparkClient, network)
31153
31628
  }
31154
31629
  }
31155
31630
  for (const chainNode of chain) {
31156
- const nodeTx = (0, import_utils23.bytesToHex)(chainNode.nodeTx);
31631
+ const nodeTx = (0, import_utils24.bytesToHex)(chainNode.nodeTx);
31157
31632
  transactions.push(nodeTx);
31158
31633
  if (chainNode.id === node.id) {
31159
- const refundTx = (0, import_utils23.bytesToHex)(chainNode.refundTx);
31634
+ const refundTx = (0, import_utils24.bytesToHex)(chainNode.refundTx);
31160
31635
  transactions.push(refundTx);
31161
31636
  }
31162
31637
  }
@@ -31186,7 +31661,7 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31186
31661
  `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.`
31187
31662
  );
31188
31663
  }
31189
- const nodeBytes = (0, import_utils23.hexToBytes)(hex);
31664
+ const nodeBytes = (0, import_utils24.hexToBytes)(hex);
31190
31665
  const node = TreeNode.decode(nodeBytes);
31191
31666
  if (!node.id) {
31192
31667
  throw new Error(
@@ -31262,7 +31737,7 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31262
31737
  }
31263
31738
  }
31264
31739
  for (const chainNode of chain) {
31265
- let nodeTxHex = (0, import_utils23.bytesToHex)(chainNode.nodeTx);
31740
+ let nodeTxHex = (0, import_utils24.bytesToHex)(chainNode.nodeTx);
31266
31741
  try {
31267
31742
  const txObj = getTxFromRawTxHex(nodeTxHex);
31268
31743
  const txid = getTxId(txObj);
@@ -31279,7 +31754,7 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31279
31754
  for (let i = txObj.outputsLength - 1; i >= 0; i--) {
31280
31755
  const output = txObj.getOutput(i);
31281
31756
  if (output?.amount === 0n && output.script) {
31282
- anchorOutputScriptHex = (0, import_utils23.bytesToHex)(output.script);
31757
+ anchorOutputScriptHex = (0, import_utils24.bytesToHex)(output.script);
31283
31758
  break;
31284
31759
  }
31285
31760
  }
@@ -31300,11 +31775,11 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31300
31775
  usedUtxos,
31301
31776
  correctedParentTx
31302
31777
  } = constructFeeBumpTx(nodeTxHex, availableUtxos, feeRate, void 0);
31303
- const feeBumpTx = btc5.Transaction.fromPSBT((0, import_utils23.hexToBytes)(nodeFeeBumpPsbt));
31778
+ const feeBumpTx = btc5.Transaction.fromPSBT((0, import_utils24.hexToBytes)(nodeFeeBumpPsbt));
31304
31779
  var feeBumpOut = feeBumpTx.outputsLength === 1 ? feeBumpTx.getOutput(0) : null;
31305
31780
  var feeBumpOutPubKey = null;
31306
31781
  for (const usedUtxo of usedUtxos) {
31307
- if (feeBumpOut && (0, import_utils23.bytesToHex)(feeBumpOut.script) == usedUtxo.script) {
31782
+ if (feeBumpOut && (0, import_utils24.bytesToHex)(feeBumpOut.script) == usedUtxo.script) {
31308
31783
  feeBumpOutPubKey = usedUtxo.publicKey;
31309
31784
  }
31310
31785
  const index = availableUtxos.findIndex(
@@ -31319,20 +31794,20 @@ async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, fee
31319
31794
  txid: getTxId(feeBumpTx),
31320
31795
  vout: 0,
31321
31796
  value: feeBumpOut.amount,
31322
- script: (0, import_utils23.bytesToHex)(feeBumpOut.script),
31797
+ script: (0, import_utils24.bytesToHex)(feeBumpOut.script),
31323
31798
  publicKey: feeBumpOutPubKey
31324
31799
  });
31325
31800
  const finalNodeTx = correctedParentTx || nodeTxHex;
31326
31801
  txPackages.push({ tx: finalNodeTx, feeBumpPsbt: nodeFeeBumpPsbt });
31327
31802
  if (chainNode.id === node.id) {
31328
- let refundTxHex = (0, import_utils23.bytesToHex)(chainNode.refundTx);
31803
+ let refundTxHex = (0, import_utils24.bytesToHex)(chainNode.refundTx);
31329
31804
  try {
31330
31805
  const txObj = getTxFromRawTxHex(refundTxHex);
31331
31806
  let anchorOutputScriptHex;
31332
31807
  for (let i = txObj.outputsLength - 1; i >= 0; i--) {
31333
31808
  const output = txObj.getOutput(i);
31334
31809
  if (output?.amount === 0n && output.script) {
31335
- anchorOutputScriptHex = (0, import_utils23.bytesToHex)(output.script);
31810
+ anchorOutputScriptHex = (0, import_utils24.bytesToHex)(output.script);
31336
31811
  break;
31337
31812
  }
31338
31813
  }
@@ -31446,10 +31921,10 @@ function constructFeeBumpTx(txHex, utxos, feeRate, previousFeeBumpTx) {
31446
31921
  if (!fundingUtxo) {
31447
31922
  throw new Error(`UTXO at index ${i} is undefined`);
31448
31923
  }
31449
- const pubKeyHash = hash160((0, import_utils23.hexToBytes)(fundingUtxo.publicKey));
31924
+ const pubKeyHash = hash160((0, import_utils24.hexToBytes)(fundingUtxo.publicKey));
31450
31925
  const scriptToUse = new Uint8Array([0, 20, ...pubKeyHash]);
31451
- const providedScript = (0, import_utils23.hexToBytes)(fundingUtxo.script);
31452
- if ((0, import_utils23.bytesToHex)(scriptToUse) !== (0, import_utils23.bytesToHex)(providedScript)) {
31926
+ const providedScript = (0, import_utils24.hexToBytes)(fundingUtxo.script);
31927
+ if ((0, import_utils24.bytesToHex)(scriptToUse) !== (0, import_utils24.bytesToHex)(providedScript)) {
31453
31928
  throw new Error(
31454
31929
  `\u274C Derived script doesn't match provided script for UTXO ${i + 1}.`
31455
31930
  );
@@ -31514,7 +31989,7 @@ function constructFeeBumpTx(txHex, utxos, feeRate, previousFeeBumpTx) {
31514
31989
  }
31515
31990
  let psbtHex;
31516
31991
  try {
31517
- psbtHex = (0, import_utils23.bytesToHex)(builder.toPSBT());
31992
+ psbtHex = (0, import_utils24.bytesToHex)(builder.toPSBT());
31518
31993
  } catch (error) {
31519
31994
  throw new Error(`Failed to extract transaction: ${error}`);
31520
31995
  }