@buildonspark/spark-sdk 0.1.46 → 0.1.47

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 (146) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{chunk-I54FARY2.js → chunk-EAP3U3CW.js} +14 -14
  3. package/dist/chunk-GWFQ7EBA.js +3773 -0
  4. package/dist/{chunk-JB64OQES.js → chunk-NNX4OK44.js} +3488 -935
  5. package/dist/{RequestLightningSendInput-CN6BNg_g.d.ts → client-CvpTRpcw.d.cts} +422 -212
  6. package/dist/{RequestLightningSendInput-2cSh_In4.d.cts → client-D7KgLN44.d.ts} +422 -212
  7. package/dist/graphql/objects/index.d.cts +5 -9
  8. package/dist/graphql/objects/index.d.ts +5 -9
  9. package/dist/graphql/objects/index.js +1 -1
  10. package/dist/index.cjs +20460 -23376
  11. package/dist/index.d.cts +15 -769
  12. package/dist/index.d.ts +15 -769
  13. package/dist/index.js +83 -73
  14. package/dist/index.node.cjs +21994 -25018
  15. package/dist/index.node.d.cts +312 -34
  16. package/dist/index.node.d.ts +312 -34
  17. package/dist/index.node.js +84 -178
  18. package/dist/native/index.cjs +17112 -20106
  19. package/dist/native/index.d.cts +974 -1138
  20. package/dist/native/index.d.ts +974 -1138
  21. package/dist/native/index.js +10604 -13592
  22. package/dist/proto/lrc20.d.cts +2 -2
  23. package/dist/proto/lrc20.d.ts +2 -2
  24. package/dist/proto/lrc20.js +3098 -46
  25. package/dist/proto/spark.d.cts +1 -1
  26. package/dist/proto/spark.d.ts +1 -1
  27. package/dist/proto/spark_token.d.cts +1 -1
  28. package/dist/proto/spark_token.d.ts +1 -1
  29. package/dist/{sdk-types-CKBsylfW.d.ts → sdk-types-BGCeea0G.d.ts} +1 -1
  30. package/dist/{sdk-types-Ct8xmN7l.d.cts → sdk-types-XUeQMLFP.d.cts} +1 -1
  31. package/dist/{spark-DbzGfse6.d.cts → spark-BbUrbvZz.d.cts} +1 -1
  32. package/dist/{spark-DbzGfse6.d.ts → spark-BbUrbvZz.d.ts} +1 -1
  33. package/dist/spark-wallet-BAFPpPtY.d.cts +923 -0
  34. package/dist/spark-wallet-CJkQW8pK.d.ts +923 -0
  35. package/dist/spark_bindings/native/index.d.cts +1 -1
  36. package/dist/spark_bindings/native/index.d.ts +1 -1
  37. package/dist/spark_bindings/wasm/index.d.cts +1 -1
  38. package/dist/spark_bindings/wasm/index.d.ts +1 -1
  39. package/dist/{services/index.cjs → tests/test-utils.cjs} +2511 -4379
  40. package/dist/tests/test-utils.d.cts +79 -0
  41. package/dist/tests/test-utils.d.ts +79 -0
  42. package/dist/tests/test-utils.js +85 -0
  43. package/dist/types/index.d.cts +5 -9
  44. package/dist/types/index.d.ts +5 -9
  45. package/dist/types/index.js +5 -5
  46. package/dist/{types-C-Rp0Oo7.d.cts → types-BADxR3bm.d.cts} +1 -1
  47. package/dist/{types-C-Rp0Oo7.d.ts → types-BADxR3bm.d.ts} +1 -1
  48. package/package.json +6 -34
  49. package/src/graphql/client.ts +59 -20
  50. package/src/index.node.ts +28 -2
  51. package/src/index.ts +31 -1
  52. package/src/native/index.ts +16 -2
  53. package/src/services/config.ts +4 -6
  54. package/src/services/connection.ts +131 -64
  55. package/src/services/lightning.ts +1 -2
  56. package/src/services/token-transactions.ts +7 -7
  57. package/src/services/transfer.ts +1 -1
  58. package/src/services/tree-creation.ts +1 -1
  59. package/src/services/wallet-config.ts +17 -9
  60. package/src/signer/signer.react-native.ts +2 -5
  61. package/src/signer/signer.ts +138 -64
  62. package/src/signer/types.ts +52 -0
  63. package/src/spark-wallet/spark-wallet.ts +79 -36
  64. package/src/spark-wallet/types.ts +4 -4
  65. package/src/tests/integration/coop-exit.test.ts +2 -1
  66. package/src/tests/integration/lightning.test.ts +2 -2
  67. package/src/tests/integration/swap.test.ts +1 -1
  68. package/src/tests/integration/transfer.test.ts +5 -5
  69. package/src/tests/integration/tree-creation.test.ts +1 -1
  70. package/src/tests/integration/wallet.test.ts +1 -0
  71. package/src/tests/isHermeticTest.ts +3 -24
  72. package/src/tests/{test-util.ts → test-utils.ts} +3 -7
  73. package/src/tests/wrapWithOtelSpan.test.ts +1 -1
  74. package/src/{address → utils}/address.ts +1 -1
  75. package/src/utils/crypto.ts +19 -9
  76. package/src/utils/index.ts +2 -0
  77. package/src/utils/network.ts +17 -0
  78. package/src/utils/secret-sharing.ts +1 -2
  79. package/src/utils/signing.ts +1 -1
  80. package/src/utils/token-transactions.ts +3 -3
  81. package/src/utils/unilateral-exit.ts +32 -0
  82. package/src/utils/xchain-address.ts +1 -1
  83. package/dist/BitcoinNetwork-TnABML0T.d.cts +0 -18
  84. package/dist/BitcoinNetwork-TnABML0T.d.ts +0 -18
  85. package/dist/LightningSendFeeEstimateInput-BgOhEAI-.d.cts +0 -10
  86. package/dist/LightningSendFeeEstimateInput-BgOhEAI-.d.ts +0 -10
  87. package/dist/address/index.cjs +0 -458
  88. package/dist/address/index.d.cts +0 -32
  89. package/dist/address/index.d.ts +0 -32
  90. package/dist/address/index.js +0 -17
  91. package/dist/chunk-4EMV7HHW.js +0 -277
  92. package/dist/chunk-C2S227QR.js +0 -2336
  93. package/dist/chunk-DXR2PXJU.js +0 -1122
  94. package/dist/chunk-GSI4OLXZ.js +0 -117
  95. package/dist/chunk-HHNQ3ZHC.js +0 -170
  96. package/dist/chunk-HSCLBJEL.js +0 -113
  97. package/dist/chunk-HWJWKEIU.js +0 -75
  98. package/dist/chunk-KMUMFYFX.js +0 -137
  99. package/dist/chunk-L3EHBOUX.js +0 -0
  100. package/dist/chunk-N5VZVCGJ.js +0 -622
  101. package/dist/chunk-NSJF5F5O.js +0 -325
  102. package/dist/chunk-NTFKFRQ2.js +0 -3146
  103. package/dist/chunk-OFCJFZ4I.js +0 -24
  104. package/dist/chunk-QNNSEJ4P.js +0 -232
  105. package/dist/chunk-UXDODSDT.js +0 -838
  106. package/dist/chunk-VTUGIIWI.js +0 -0
  107. package/dist/chunk-Z5HIAYFT.js +0 -84
  108. package/dist/index-CKL5DodV.d.cts +0 -214
  109. package/dist/index-COm59SPw.d.ts +0 -214
  110. package/dist/network-Css46DAz.d.cts +0 -46
  111. package/dist/network-hynb7iTZ.d.ts +0 -46
  112. package/dist/services/config.cjs +0 -2354
  113. package/dist/services/config.d.cts +0 -42
  114. package/dist/services/config.d.ts +0 -42
  115. package/dist/services/config.js +0 -17
  116. package/dist/services/connection.cjs +0 -17691
  117. package/dist/services/connection.d.cts +0 -95
  118. package/dist/services/connection.d.ts +0 -95
  119. package/dist/services/connection.js +0 -11
  120. package/dist/services/index.d.cts +0 -21
  121. package/dist/services/index.d.ts +0 -21
  122. package/dist/services/index.js +0 -58
  123. package/dist/services/lrc-connection.cjs +0 -4713
  124. package/dist/services/lrc-connection.d.cts +0 -34
  125. package/dist/services/lrc-connection.d.ts +0 -34
  126. package/dist/services/lrc-connection.js +0 -11
  127. package/dist/services/token-transactions.cjs +0 -2877
  128. package/dist/services/token-transactions.d.cts +0 -75
  129. package/dist/services/token-transactions.d.ts +0 -75
  130. package/dist/services/token-transactions.js +0 -15
  131. package/dist/services/wallet-config.cjs +0 -340
  132. package/dist/services/wallet-config.d.cts +0 -56
  133. package/dist/services/wallet-config.d.ts +0 -56
  134. package/dist/services/wallet-config.js +0 -33
  135. package/dist/signer/signer.cjs +0 -2004
  136. package/dist/signer/signer.d.cts +0 -10
  137. package/dist/signer/signer.d.ts +0 -10
  138. package/dist/signer/signer.js +0 -24
  139. package/dist/signer-BP6F__oR.d.cts +0 -187
  140. package/dist/signer-BVZJXcq7.d.ts +0 -187
  141. package/dist/utils/index.cjs +0 -2947
  142. package/dist/utils/index.d.cts +0 -18
  143. package/dist/utils/index.d.ts +0 -18
  144. package/dist/utils/index.js +0 -157
  145. package/src/address/index.ts +0 -1
  146. package/src/services/lrc-connection.ts +0 -215
@@ -1,2947 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
26
- mod2
27
- ));
28
- var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
29
-
30
- // src/utils/index.ts
31
- var utils_exports = {};
32
- __export(utils_exports, {
33
- DEFAULT_FEE_SATS: () => DEFAULT_FEE_SATS,
34
- LRC_WALLET_NETWORK: () => LRC_WALLET_NETWORK,
35
- LRC_WALLET_NETWORK_TYPE: () => LRC_WALLET_NETWORK_TYPE,
36
- Network: () => Network2,
37
- NetworkToProto: () => NetworkToProto,
38
- addPrivateKeys: () => addPrivateKeys,
39
- addPublicKeys: () => addPublicKeys,
40
- applyAdaptorToSignature: () => applyAdaptorToSignature,
41
- applyAdditiveTweakToPublicKey: () => applyAdditiveTweakToPublicKey,
42
- bigIntToPrivateKey: () => bigIntToPrivateKey,
43
- calculateAvailableTokenAmount: () => calculateAvailableTokenAmount,
44
- checkIfSelectedOutputsAreAvailable: () => checkIfSelectedOutputsAreAvailable,
45
- checkIfValidSequence: () => checkIfValidSequence,
46
- collectResponses: () => collectResponses,
47
- computeTaprootKeyNoScript: () => computeTaprootKeyNoScript,
48
- computerLagrangeCoefficients: () => computerLagrangeCoefficients,
49
- constructFeeBumpTx: () => constructFeeBumpTx,
50
- constructUnilateralExitFeeBumpPackages: () => constructUnilateralExitFeeBumpPackages,
51
- constructUnilateralExitTxs: () => constructUnilateralExitTxs,
52
- createRefundTx: () => createRefundTx,
53
- createSigningCommitment: () => createSigningCommitment,
54
- createSigningNonce: () => createSigningNonce,
55
- decodeBytesToSigningCommitment: () => decodeBytesToSigningCommitment,
56
- decodeBytesToSigningNonce: () => decodeBytesToSigningNonce,
57
- encodeSigningCommitmentToBytes: () => encodeSigningCommitmentToBytes,
58
- encodeSigningNonceToBytes: () => encodeSigningNonceToBytes,
59
- evaluatePolynomial: () => evaluatePolynomial,
60
- fieldDiv: () => fieldDiv,
61
- filterTokenBalanceForTokenPublicKey: () => filterTokenBalanceForTokenPublicKey,
62
- generateAdaptorFromSignature: () => generateAdaptorFromSignature,
63
- generatePolynomialForSecretSharing: () => generatePolynomialForSecretSharing,
64
- generateSignatureFromExistingAdaptor: () => generateSignatureFromExistingAdaptor,
65
- getCurrentTimelock: () => getCurrentTimelock,
66
- getEphemeralAnchorOutput: () => getEphemeralAnchorOutput,
67
- getLatestDepositTxId: () => getLatestDepositTxId,
68
- getNetwork: () => getNetwork,
69
- getNetworkFromAddress: () => getNetworkFromAddress,
70
- getNetworkFromString: () => getNetworkFromString,
71
- getNextTransactionSequence: () => getNextTransactionSequence,
72
- getP2TRAddressFromPkScript: () => getP2TRAddressFromPkScript,
73
- getP2TRAddressFromPublicKey: () => getP2TRAddressFromPublicKey,
74
- getP2TRScriptFromPublicKey: () => getP2TRScriptFromPublicKey,
75
- getP2WPKHAddressFromPublicKey: () => getP2WPKHAddressFromPublicKey,
76
- getRandomBigInt: () => getRandomBigInt,
77
- getRandomSigningNonce: () => getRandomSigningNonce,
78
- getSigHashFromTx: () => getSigHashFromTx,
79
- getSigningCommitmentFromNonce: () => getSigningCommitmentFromNonce,
80
- getSparkAddressFromTaproot: () => getSparkAddressFromTaproot,
81
- getTransactionSequence: () => getTransactionSequence,
82
- getTransferPackageSigningPayload: () => getTransferPackageSigningPayload,
83
- getTxFromRawTxBytes: () => getTxFromRawTxBytes,
84
- getTxFromRawTxHex: () => getTxFromRawTxHex,
85
- getTxId: () => getTxId,
86
- getTxIdNoReverse: () => getTxIdNoReverse,
87
- isEphemeralAnchorOutput: () => isEphemeralAnchorOutput,
88
- isTxBroadcast: () => isTxBroadcast,
89
- lastKeyWithTarget: () => lastKeyWithTarget,
90
- maybeApplyFee: () => maybeApplyFee,
91
- modInverse: () => modInverse,
92
- proofOfPossessionMessageHashForDepositAddress: () => proofOfPossessionMessageHashForDepositAddress,
93
- recoverSecret: () => recoverSecret,
94
- splitSecret: () => splitSecret,
95
- splitSecretWithProofs: () => splitSecretWithProofs,
96
- subtractPrivateKeys: () => subtractPrivateKeys,
97
- subtractPublicKeys: () => subtractPublicKeys,
98
- sumOfPrivateKeys: () => sumOfPrivateKeys,
99
- validateOutboundAdaptorSignature: () => validateOutboundAdaptorSignature,
100
- validateShare: () => validateShare
101
- });
102
- module.exports = __toCommonJS(utils_exports);
103
-
104
- // buffer.js
105
- var import_buffer = require("buffer");
106
- if (typeof globalThis.Buffer === "undefined") {
107
- globalThis.Buffer = import_buffer.Buffer;
108
- }
109
- if (typeof window !== "undefined") {
110
- if (typeof window.global === "undefined") {
111
- window.global = window;
112
- }
113
- if (typeof window.globalThis === "undefined") {
114
- window.globalThis = window;
115
- }
116
- }
117
-
118
- // src/utils/adaptor-signature.ts
119
- var import_modular = require("@noble/curves/abstract/modular");
120
- var import_utils2 = require("@noble/curves/abstract/utils");
121
- var import_secp256k1 = require("@noble/curves/secp256k1");
122
-
123
- // src/errors/base.ts
124
- var import_utils = require("@noble/hashes/utils");
125
- var SparkSDKError = class extends Error {
126
- context;
127
- originalError;
128
- constructor(message, context = {}, originalError) {
129
- const msg = getMessage(message, context, originalError);
130
- super(msg);
131
- this.name = this.constructor.name;
132
- this.context = context;
133
- this.originalError = originalError;
134
- if (Error.captureStackTrace) {
135
- Error.captureStackTrace(this, this.constructor);
136
- }
137
- }
138
- toString() {
139
- return this.message;
140
- }
141
- toJSON() {
142
- return {
143
- name: this.name,
144
- message: this.message,
145
- context: this.context,
146
- originalError: this.originalError ? {
147
- name: this.originalError.name,
148
- message: this.originalError.message,
149
- stack: this.originalError.stack
150
- } : void 0,
151
- stack: this.stack
152
- };
153
- }
154
- };
155
- function getMessage(message, context = {}, originalError) {
156
- const contextStr = Object.entries(context).map(([key, value]) => `${key}: ${safeStringify(value)}`).join(", ");
157
- const originalErrorStr = originalError ? `
158
- Original Error: ${originalError.message}` : "";
159
- return `SparkSDKError: ${message}${contextStr ? `
160
- Context: ${contextStr}` : ""}${originalErrorStr}`;
161
- }
162
- function safeStringify(value) {
163
- const replacer = (_, v) => {
164
- if (typeof v === "bigint") {
165
- return v.toString();
166
- }
167
- if (v instanceof Uint8Array) {
168
- return formatUint8Array(v);
169
- }
170
- return v;
171
- };
172
- if (typeof value === "bigint") {
173
- return `"${value.toString()}"`;
174
- }
175
- if (value instanceof Uint8Array) {
176
- return `"${formatUint8Array(value)}"`;
177
- }
178
- try {
179
- const result = JSON.stringify(value, replacer);
180
- return result === void 0 ? String(value) : result;
181
- } catch {
182
- try {
183
- return String(value);
184
- } catch {
185
- return "[Unserializable]";
186
- }
187
- }
188
- }
189
- function formatUint8Array(arr) {
190
- return `Uint8Array(0x${(0, import_utils.bytesToHex)(arr)})`;
191
- }
192
-
193
- // src/errors/types.ts
194
- var NetworkError = class extends SparkSDKError {
195
- constructor(message, context = {}, originalError) {
196
- super(message, context, originalError);
197
- }
198
- };
199
- var ValidationError = class extends SparkSDKError {
200
- constructor(message, context = {}, originalError) {
201
- super(message, context, originalError);
202
- }
203
- };
204
-
205
- // src/utils/adaptor-signature.ts
206
- function generateSignatureFromExistingAdaptor(signature, adaptorPrivateKeyBytes) {
207
- const { r, s } = parseSignature(signature);
208
- const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
209
- const tBigInt = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKeyBytes);
210
- const newS = (0, import_modular.mod)(sBigInt - tBigInt, import_secp256k1.secp256k1.CURVE.n);
211
- const newSignature = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
212
- return newSignature;
213
- }
214
- function generateAdaptorFromSignature(signature) {
215
- const adaptorPrivateKey = import_secp256k1.secp256k1.utils.randomPrivateKey();
216
- const { r, s } = parseSignature(signature);
217
- const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
218
- const tBigInt = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKey);
219
- const newS = (0, import_modular.mod)(sBigInt - tBigInt, import_secp256k1.secp256k1.CURVE.n);
220
- const newSignature = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
221
- return {
222
- adaptorSignature: newSignature,
223
- adaptorPrivateKey
224
- };
225
- }
226
- function validateOutboundAdaptorSignature(pubkey, hash, signature, adaptorPubkey) {
227
- return schnorrVerifyWithAdaptor(
228
- signature,
229
- hash,
230
- pubkey,
231
- adaptorPubkey,
232
- false
233
- );
234
- }
235
- function applyAdaptorToSignature(pubkey, hash, signature, adaptorPrivateKeyBytes) {
236
- const { r, s } = parseSignature(signature);
237
- const sBigInt = (0, import_utils2.bytesToNumberBE)(s);
238
- const adaptorPrivateKey = (0, import_utils2.bytesToNumberBE)(adaptorPrivateKeyBytes);
239
- const newS = (0, import_modular.mod)(sBigInt + adaptorPrivateKey, import_secp256k1.secp256k1.CURVE.n);
240
- const newSig = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(newS, 32)]);
241
- if (import_secp256k1.schnorr.verify(newSig, hash, pubkey)) {
242
- return newSig;
243
- }
244
- const altS = (0, import_modular.mod)(sBigInt - adaptorPrivateKey, import_secp256k1.secp256k1.CURVE.n);
245
- const altSig = new Uint8Array([...r, ...(0, import_utils2.numberToBytesBE)(altS, 32)]);
246
- if (import_secp256k1.schnorr.verify(altSig, hash, pubkey)) {
247
- return altSig;
248
- }
249
- throw new Error("Cannot apply adaptor to signature");
250
- }
251
- function schnorrVerifyWithAdaptor(signature, hash, pubKeyBytes, adaptorPubkey, inbound) {
252
- if (hash.length !== 32) {
253
- throw new Error(`wrong size for message (got ${hash.length}, want 32)`);
254
- }
255
- const pubKey = import_secp256k1.schnorr.utils.lift_x((0, import_utils2.bytesToNumberBE)(pubKeyBytes));
256
- pubKey.assertValidity();
257
- const { r, s } = parseSignature(signature);
258
- const commitmenet = import_secp256k1.schnorr.utils.taggedHash(
259
- "BIP0340/challenge",
260
- r,
261
- pubKey.toRawBytes().slice(1),
262
- hash
263
- );
264
- if (commitmenet.length > 32) {
265
- throw new Error("hash of (r || P || m) too big");
266
- }
267
- const e = (0, import_modular.mod)((0, import_utils2.bytesToNumberBE)(commitmenet), import_secp256k1.secp256k1.CURVE.n);
268
- const negE = (0, import_modular.mod)(-e, import_secp256k1.secp256k1.CURVE.n);
269
- const R = import_secp256k1.secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(
270
- pubKey,
271
- (0, import_utils2.bytesToNumberBE)(s),
272
- negE
273
- );
274
- if (!R) {
275
- throw new Error("R is undefined");
276
- }
277
- R.assertValidity();
278
- const adaptorPoint = import_secp256k1.secp256k1.ProjectivePoint.fromHex(adaptorPubkey);
279
- const newR = R.add(adaptorPoint);
280
- if (!inbound && newR.equals(import_secp256k1.secp256k1.ProjectivePoint.ZERO)) {
281
- throw new Error("calculated R point is the point at infinity");
282
- }
283
- newR.assertValidity();
284
- if (!newR.hasEvenY()) {
285
- throw new Error("calculated R y-value is odd");
286
- }
287
- const rNum = (0, import_utils2.bytesToNumberBE)(r);
288
- if (newR.toAffine().x !== rNum) {
289
- throw new Error("calculated R point was not given R");
290
- }
291
- return true;
292
- }
293
- function parseSignature(signature) {
294
- if (signature.length < 64) {
295
- throw new ValidationError("Signature too short", {
296
- expectedLength: 64,
297
- actualLength: signature.length
298
- });
299
- }
300
- if (signature.length > 64) {
301
- throw new ValidationError("Signature too long", {
302
- expectedLength: 64,
303
- actualLength: signature.length
304
- });
305
- }
306
- const r = signature.slice(0, 32);
307
- const s = signature.slice(32, 64);
308
- if ((0, import_utils2.bytesToNumberBE)(r) >= import_secp256k1.secp256k1.CURVE.Fp.ORDER) {
309
- throw new ValidationError("Invalid signature: r >= field prime", {
310
- rValue: (0, import_utils2.bytesToNumberBE)(r),
311
- fieldPrime: import_secp256k1.secp256k1.CURVE.Fp.ORDER
312
- });
313
- }
314
- if ((0, import_utils2.bytesToNumberBE)(s) >= import_secp256k1.secp256k1.CURVE.n) {
315
- throw new ValidationError("Invalid signature: s >= group order", {
316
- sValue: (0, import_utils2.bytesToNumberBE)(s),
317
- groupOrder: import_secp256k1.secp256k1.CURVE.n
318
- });
319
- }
320
- return { r, s };
321
- }
322
-
323
- // src/utils/bitcoin.ts
324
- var import_utils3 = require("@noble/curves/abstract/utils");
325
- var import_secp256k12 = require("@noble/curves/secp256k1");
326
- var import_sha2 = require("@noble/hashes/sha2");
327
- var btc2 = __toESM(require("@scure/btc-signer"), 1);
328
-
329
- // src/utils/network.ts
330
- var import_lrc20_sdk = require("@buildonspark/lrc20-sdk");
331
- var btc = __toESM(require("@scure/btc-signer"), 1);
332
- var bitcoin = __toESM(require("bitcoinjs-lib"), 1);
333
-
334
- // src/proto/spark.ts
335
- var import_wire4 = require("@bufbuild/protobuf/wire");
336
-
337
- // src/proto/common.ts
338
- var import_wire = require("@bufbuild/protobuf/wire");
339
-
340
- // src/proto/google/protobuf/empty.ts
341
- var import_wire2 = require("@bufbuild/protobuf/wire");
342
-
343
- // src/proto/google/protobuf/timestamp.ts
344
- var import_wire3 = require("@bufbuild/protobuf/wire");
345
- function createBaseTimestamp() {
346
- return { seconds: 0, nanos: 0 };
347
- }
348
- var Timestamp = {
349
- encode(message, writer = new import_wire3.BinaryWriter()) {
350
- if (message.seconds !== 0) {
351
- writer.uint32(8).int64(message.seconds);
352
- }
353
- if (message.nanos !== 0) {
354
- writer.uint32(16).int32(message.nanos);
355
- }
356
- return writer;
357
- },
358
- decode(input, length) {
359
- const reader = input instanceof import_wire3.BinaryReader ? input : new import_wire3.BinaryReader(input);
360
- const end = length === void 0 ? reader.len : reader.pos + length;
361
- const message = createBaseTimestamp();
362
- while (reader.pos < end) {
363
- const tag = reader.uint32();
364
- switch (tag >>> 3) {
365
- case 1: {
366
- if (tag !== 8) {
367
- break;
368
- }
369
- message.seconds = longToNumber(reader.int64());
370
- continue;
371
- }
372
- case 2: {
373
- if (tag !== 16) {
374
- break;
375
- }
376
- message.nanos = reader.int32();
377
- continue;
378
- }
379
- }
380
- if ((tag & 7) === 4 || tag === 0) {
381
- break;
382
- }
383
- reader.skip(tag & 7);
384
- }
385
- return message;
386
- },
387
- fromJSON(object) {
388
- return {
389
- seconds: isSet(object.seconds) ? globalThis.Number(object.seconds) : 0,
390
- nanos: isSet(object.nanos) ? globalThis.Number(object.nanos) : 0
391
- };
392
- },
393
- toJSON(message) {
394
- const obj = {};
395
- if (message.seconds !== 0) {
396
- obj.seconds = Math.round(message.seconds);
397
- }
398
- if (message.nanos !== 0) {
399
- obj.nanos = Math.round(message.nanos);
400
- }
401
- return obj;
402
- },
403
- create(base) {
404
- return Timestamp.fromPartial(base ?? {});
405
- },
406
- fromPartial(object) {
407
- const message = createBaseTimestamp();
408
- message.seconds = object.seconds ?? 0;
409
- message.nanos = object.nanos ?? 0;
410
- return message;
411
- }
412
- };
413
- function longToNumber(int64) {
414
- const num = globalThis.Number(int64.toString());
415
- if (num > globalThis.Number.MAX_SAFE_INTEGER) {
416
- throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
417
- }
418
- if (num < globalThis.Number.MIN_SAFE_INTEGER) {
419
- throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
420
- }
421
- return num;
422
- }
423
- function isSet(value) {
424
- return value !== null && value !== void 0;
425
- }
426
-
427
- // src/proto/spark.ts
428
- function networkFromJSON(object) {
429
- switch (object) {
430
- case 0:
431
- case "UNSPECIFIED":
432
- return 0 /* UNSPECIFIED */;
433
- case 1:
434
- case "MAINNET":
435
- return 1 /* MAINNET */;
436
- case 2:
437
- case "REGTEST":
438
- return 2 /* REGTEST */;
439
- case 3:
440
- case "TESTNET":
441
- return 3 /* TESTNET */;
442
- case 4:
443
- case "SIGNET":
444
- return 4 /* SIGNET */;
445
- case -1:
446
- case "UNRECOGNIZED":
447
- default:
448
- return -1 /* UNRECOGNIZED */;
449
- }
450
- }
451
- function networkToJSON(object) {
452
- switch (object) {
453
- case 0 /* UNSPECIFIED */:
454
- return "UNSPECIFIED";
455
- case 1 /* MAINNET */:
456
- return "MAINNET";
457
- case 2 /* REGTEST */:
458
- return "REGTEST";
459
- case 3 /* TESTNET */:
460
- return "TESTNET";
461
- case 4 /* SIGNET */:
462
- return "SIGNET";
463
- case -1 /* UNRECOGNIZED */:
464
- default:
465
- return "UNRECOGNIZED";
466
- }
467
- }
468
- function createBaseSigningKeyshare() {
469
- return { ownerIdentifiers: [], threshold: 0, publicKey: new Uint8Array(0), publicShares: {}, updatedTime: void 0 };
470
- }
471
- var SigningKeyshare = {
472
- encode(message, writer = new import_wire4.BinaryWriter()) {
473
- for (const v of message.ownerIdentifiers) {
474
- writer.uint32(10).string(v);
475
- }
476
- if (message.threshold !== 0) {
477
- writer.uint32(16).uint32(message.threshold);
478
- }
479
- if (message.publicKey.length !== 0) {
480
- writer.uint32(26).bytes(message.publicKey);
481
- }
482
- Object.entries(message.publicShares).forEach(([key, value]) => {
483
- SigningKeyshare_PublicSharesEntry.encode({ key, value }, writer.uint32(34).fork()).join();
484
- });
485
- if (message.updatedTime !== void 0) {
486
- Timestamp.encode(toTimestamp(message.updatedTime), writer.uint32(42).fork()).join();
487
- }
488
- return writer;
489
- },
490
- decode(input, length) {
491
- const reader = input instanceof import_wire4.BinaryReader ? input : new import_wire4.BinaryReader(input);
492
- const end = length === void 0 ? reader.len : reader.pos + length;
493
- const message = createBaseSigningKeyshare();
494
- while (reader.pos < end) {
495
- const tag = reader.uint32();
496
- switch (tag >>> 3) {
497
- case 1: {
498
- if (tag !== 10) {
499
- break;
500
- }
501
- message.ownerIdentifiers.push(reader.string());
502
- continue;
503
- }
504
- case 2: {
505
- if (tag !== 16) {
506
- break;
507
- }
508
- message.threshold = reader.uint32();
509
- continue;
510
- }
511
- case 3: {
512
- if (tag !== 26) {
513
- break;
514
- }
515
- message.publicKey = reader.bytes();
516
- continue;
517
- }
518
- case 4: {
519
- if (tag !== 34) {
520
- break;
521
- }
522
- const entry4 = SigningKeyshare_PublicSharesEntry.decode(reader, reader.uint32());
523
- if (entry4.value !== void 0) {
524
- message.publicShares[entry4.key] = entry4.value;
525
- }
526
- continue;
527
- }
528
- case 5: {
529
- if (tag !== 42) {
530
- break;
531
- }
532
- message.updatedTime = fromTimestamp(Timestamp.decode(reader, reader.uint32()));
533
- continue;
534
- }
535
- }
536
- if ((tag & 7) === 4 || tag === 0) {
537
- break;
538
- }
539
- reader.skip(tag & 7);
540
- }
541
- return message;
542
- },
543
- fromJSON(object) {
544
- return {
545
- ownerIdentifiers: globalThis.Array.isArray(object?.ownerIdentifiers) ? object.ownerIdentifiers.map((e) => globalThis.String(e)) : [],
546
- threshold: isSet2(object.threshold) ? globalThis.Number(object.threshold) : 0,
547
- publicKey: isSet2(object.publicKey) ? bytesFromBase64(object.publicKey) : new Uint8Array(0),
548
- publicShares: isObject(object.publicShares) ? Object.entries(object.publicShares).reduce((acc, [key, value]) => {
549
- acc[key] = bytesFromBase64(value);
550
- return acc;
551
- }, {}) : {},
552
- updatedTime: isSet2(object.updatedTime) ? fromJsonTimestamp(object.updatedTime) : void 0
553
- };
554
- },
555
- toJSON(message) {
556
- const obj = {};
557
- if (message.ownerIdentifiers?.length) {
558
- obj.ownerIdentifiers = message.ownerIdentifiers;
559
- }
560
- if (message.threshold !== 0) {
561
- obj.threshold = Math.round(message.threshold);
562
- }
563
- if (message.publicKey.length !== 0) {
564
- obj.publicKey = base64FromBytes(message.publicKey);
565
- }
566
- if (message.publicShares) {
567
- const entries = Object.entries(message.publicShares);
568
- if (entries.length > 0) {
569
- obj.publicShares = {};
570
- entries.forEach(([k, v]) => {
571
- obj.publicShares[k] = base64FromBytes(v);
572
- });
573
- }
574
- }
575
- if (message.updatedTime !== void 0) {
576
- obj.updatedTime = message.updatedTime.toISOString();
577
- }
578
- return obj;
579
- },
580
- create(base) {
581
- return SigningKeyshare.fromPartial(base ?? {});
582
- },
583
- fromPartial(object) {
584
- const message = createBaseSigningKeyshare();
585
- message.ownerIdentifiers = object.ownerIdentifiers?.map((e) => e) || [];
586
- message.threshold = object.threshold ?? 0;
587
- message.publicKey = object.publicKey ?? new Uint8Array(0);
588
- message.publicShares = Object.entries(object.publicShares ?? {}).reduce(
589
- (acc, [key, value]) => {
590
- if (value !== void 0) {
591
- acc[key] = value;
592
- }
593
- return acc;
594
- },
595
- {}
596
- );
597
- message.updatedTime = object.updatedTime ?? void 0;
598
- return message;
599
- }
600
- };
601
- function createBaseSigningKeyshare_PublicSharesEntry() {
602
- return { key: "", value: new Uint8Array(0) };
603
- }
604
- var SigningKeyshare_PublicSharesEntry = {
605
- encode(message, writer = new import_wire4.BinaryWriter()) {
606
- if (message.key !== "") {
607
- writer.uint32(10).string(message.key);
608
- }
609
- if (message.value.length !== 0) {
610
- writer.uint32(18).bytes(message.value);
611
- }
612
- return writer;
613
- },
614
- decode(input, length) {
615
- const reader = input instanceof import_wire4.BinaryReader ? input : new import_wire4.BinaryReader(input);
616
- const end = length === void 0 ? reader.len : reader.pos + length;
617
- const message = createBaseSigningKeyshare_PublicSharesEntry();
618
- while (reader.pos < end) {
619
- const tag = reader.uint32();
620
- switch (tag >>> 3) {
621
- case 1: {
622
- if (tag !== 10) {
623
- break;
624
- }
625
- message.key = reader.string();
626
- continue;
627
- }
628
- case 2: {
629
- if (tag !== 18) {
630
- break;
631
- }
632
- message.value = reader.bytes();
633
- continue;
634
- }
635
- }
636
- if ((tag & 7) === 4 || tag === 0) {
637
- break;
638
- }
639
- reader.skip(tag & 7);
640
- }
641
- return message;
642
- },
643
- fromJSON(object) {
644
- return {
645
- key: isSet2(object.key) ? globalThis.String(object.key) : "",
646
- value: isSet2(object.value) ? bytesFromBase64(object.value) : new Uint8Array(0)
647
- };
648
- },
649
- toJSON(message) {
650
- const obj = {};
651
- if (message.key !== "") {
652
- obj.key = message.key;
653
- }
654
- if (message.value.length !== 0) {
655
- obj.value = base64FromBytes(message.value);
656
- }
657
- return obj;
658
- },
659
- create(base) {
660
- return SigningKeyshare_PublicSharesEntry.fromPartial(base ?? {});
661
- },
662
- fromPartial(object) {
663
- const message = createBaseSigningKeyshare_PublicSharesEntry();
664
- message.key = object.key ?? "";
665
- message.value = object.value ?? new Uint8Array(0);
666
- return message;
667
- }
668
- };
669
- function createBaseTreeNode() {
670
- return {
671
- id: "",
672
- treeId: "",
673
- value: 0,
674
- parentNodeId: void 0,
675
- nodeTx: new Uint8Array(0),
676
- refundTx: new Uint8Array(0),
677
- vout: 0,
678
- verifyingPublicKey: new Uint8Array(0),
679
- ownerIdentityPublicKey: new Uint8Array(0),
680
- signingKeyshare: void 0,
681
- status: "",
682
- network: 0,
683
- createdTime: void 0,
684
- updatedTime: void 0,
685
- ownerSigningPublicKey: new Uint8Array(0),
686
- directTx: new Uint8Array(0),
687
- directRefundTx: new Uint8Array(0),
688
- directFromCpfpRefundTx: new Uint8Array(0)
689
- };
690
- }
691
- var TreeNode = {
692
- encode(message, writer = new import_wire4.BinaryWriter()) {
693
- if (message.id !== "") {
694
- writer.uint32(10).string(message.id);
695
- }
696
- if (message.treeId !== "") {
697
- writer.uint32(18).string(message.treeId);
698
- }
699
- if (message.value !== 0) {
700
- writer.uint32(24).uint64(message.value);
701
- }
702
- if (message.parentNodeId !== void 0) {
703
- writer.uint32(34).string(message.parentNodeId);
704
- }
705
- if (message.nodeTx.length !== 0) {
706
- writer.uint32(42).bytes(message.nodeTx);
707
- }
708
- if (message.refundTx.length !== 0) {
709
- writer.uint32(50).bytes(message.refundTx);
710
- }
711
- if (message.vout !== 0) {
712
- writer.uint32(56).uint32(message.vout);
713
- }
714
- if (message.verifyingPublicKey.length !== 0) {
715
- writer.uint32(66).bytes(message.verifyingPublicKey);
716
- }
717
- if (message.ownerIdentityPublicKey.length !== 0) {
718
- writer.uint32(74).bytes(message.ownerIdentityPublicKey);
719
- }
720
- if (message.signingKeyshare !== void 0) {
721
- SigningKeyshare.encode(message.signingKeyshare, writer.uint32(82).fork()).join();
722
- }
723
- if (message.status !== "") {
724
- writer.uint32(90).string(message.status);
725
- }
726
- if (message.network !== 0) {
727
- writer.uint32(96).int32(message.network);
728
- }
729
- if (message.createdTime !== void 0) {
730
- Timestamp.encode(toTimestamp(message.createdTime), writer.uint32(106).fork()).join();
731
- }
732
- if (message.updatedTime !== void 0) {
733
- Timestamp.encode(toTimestamp(message.updatedTime), writer.uint32(114).fork()).join();
734
- }
735
- if (message.ownerSigningPublicKey.length !== 0) {
736
- writer.uint32(122).bytes(message.ownerSigningPublicKey);
737
- }
738
- if (message.directTx.length !== 0) {
739
- writer.uint32(130).bytes(message.directTx);
740
- }
741
- if (message.directRefundTx.length !== 0) {
742
- writer.uint32(138).bytes(message.directRefundTx);
743
- }
744
- if (message.directFromCpfpRefundTx.length !== 0) {
745
- writer.uint32(146).bytes(message.directFromCpfpRefundTx);
746
- }
747
- return writer;
748
- },
749
- decode(input, length) {
750
- const reader = input instanceof import_wire4.BinaryReader ? input : new import_wire4.BinaryReader(input);
751
- const end = length === void 0 ? reader.len : reader.pos + length;
752
- const message = createBaseTreeNode();
753
- while (reader.pos < end) {
754
- const tag = reader.uint32();
755
- switch (tag >>> 3) {
756
- case 1: {
757
- if (tag !== 10) {
758
- break;
759
- }
760
- message.id = reader.string();
761
- continue;
762
- }
763
- case 2: {
764
- if (tag !== 18) {
765
- break;
766
- }
767
- message.treeId = reader.string();
768
- continue;
769
- }
770
- case 3: {
771
- if (tag !== 24) {
772
- break;
773
- }
774
- message.value = longToNumber2(reader.uint64());
775
- continue;
776
- }
777
- case 4: {
778
- if (tag !== 34) {
779
- break;
780
- }
781
- message.parentNodeId = reader.string();
782
- continue;
783
- }
784
- case 5: {
785
- if (tag !== 42) {
786
- break;
787
- }
788
- message.nodeTx = reader.bytes();
789
- continue;
790
- }
791
- case 6: {
792
- if (tag !== 50) {
793
- break;
794
- }
795
- message.refundTx = reader.bytes();
796
- continue;
797
- }
798
- case 7: {
799
- if (tag !== 56) {
800
- break;
801
- }
802
- message.vout = reader.uint32();
803
- continue;
804
- }
805
- case 8: {
806
- if (tag !== 66) {
807
- break;
808
- }
809
- message.verifyingPublicKey = reader.bytes();
810
- continue;
811
- }
812
- case 9: {
813
- if (tag !== 74) {
814
- break;
815
- }
816
- message.ownerIdentityPublicKey = reader.bytes();
817
- continue;
818
- }
819
- case 10: {
820
- if (tag !== 82) {
821
- break;
822
- }
823
- message.signingKeyshare = SigningKeyshare.decode(reader, reader.uint32());
824
- continue;
825
- }
826
- case 11: {
827
- if (tag !== 90) {
828
- break;
829
- }
830
- message.status = reader.string();
831
- continue;
832
- }
833
- case 12: {
834
- if (tag !== 96) {
835
- break;
836
- }
837
- message.network = reader.int32();
838
- continue;
839
- }
840
- case 13: {
841
- if (tag !== 106) {
842
- break;
843
- }
844
- message.createdTime = fromTimestamp(Timestamp.decode(reader, reader.uint32()));
845
- continue;
846
- }
847
- case 14: {
848
- if (tag !== 114) {
849
- break;
850
- }
851
- message.updatedTime = fromTimestamp(Timestamp.decode(reader, reader.uint32()));
852
- continue;
853
- }
854
- case 15: {
855
- if (tag !== 122) {
856
- break;
857
- }
858
- message.ownerSigningPublicKey = reader.bytes();
859
- continue;
860
- }
861
- case 16: {
862
- if (tag !== 130) {
863
- break;
864
- }
865
- message.directTx = reader.bytes();
866
- continue;
867
- }
868
- case 17: {
869
- if (tag !== 138) {
870
- break;
871
- }
872
- message.directRefundTx = reader.bytes();
873
- continue;
874
- }
875
- case 18: {
876
- if (tag !== 146) {
877
- break;
878
- }
879
- message.directFromCpfpRefundTx = reader.bytes();
880
- continue;
881
- }
882
- }
883
- if ((tag & 7) === 4 || tag === 0) {
884
- break;
885
- }
886
- reader.skip(tag & 7);
887
- }
888
- return message;
889
- },
890
- fromJSON(object) {
891
- return {
892
- id: isSet2(object.id) ? globalThis.String(object.id) : "",
893
- treeId: isSet2(object.treeId) ? globalThis.String(object.treeId) : "",
894
- value: isSet2(object.value) ? globalThis.Number(object.value) : 0,
895
- parentNodeId: isSet2(object.parentNodeId) ? globalThis.String(object.parentNodeId) : void 0,
896
- nodeTx: isSet2(object.nodeTx) ? bytesFromBase64(object.nodeTx) : new Uint8Array(0),
897
- refundTx: isSet2(object.refundTx) ? bytesFromBase64(object.refundTx) : new Uint8Array(0),
898
- vout: isSet2(object.vout) ? globalThis.Number(object.vout) : 0,
899
- verifyingPublicKey: isSet2(object.verifyingPublicKey) ? bytesFromBase64(object.verifyingPublicKey) : new Uint8Array(0),
900
- ownerIdentityPublicKey: isSet2(object.ownerIdentityPublicKey) ? bytesFromBase64(object.ownerIdentityPublicKey) : new Uint8Array(0),
901
- signingKeyshare: isSet2(object.signingKeyshare) ? SigningKeyshare.fromJSON(object.signingKeyshare) : void 0,
902
- status: isSet2(object.status) ? globalThis.String(object.status) : "",
903
- network: isSet2(object.network) ? networkFromJSON(object.network) : 0,
904
- createdTime: isSet2(object.createdTime) ? fromJsonTimestamp(object.createdTime) : void 0,
905
- updatedTime: isSet2(object.updatedTime) ? fromJsonTimestamp(object.updatedTime) : void 0,
906
- ownerSigningPublicKey: isSet2(object.ownerSigningPublicKey) ? bytesFromBase64(object.ownerSigningPublicKey) : new Uint8Array(0),
907
- directTx: isSet2(object.directTx) ? bytesFromBase64(object.directTx) : new Uint8Array(0),
908
- directRefundTx: isSet2(object.directRefundTx) ? bytesFromBase64(object.directRefundTx) : new Uint8Array(0),
909
- directFromCpfpRefundTx: isSet2(object.directFromCpfpRefundTx) ? bytesFromBase64(object.directFromCpfpRefundTx) : new Uint8Array(0)
910
- };
911
- },
912
- toJSON(message) {
913
- const obj = {};
914
- if (message.id !== "") {
915
- obj.id = message.id;
916
- }
917
- if (message.treeId !== "") {
918
- obj.treeId = message.treeId;
919
- }
920
- if (message.value !== 0) {
921
- obj.value = Math.round(message.value);
922
- }
923
- if (message.parentNodeId !== void 0) {
924
- obj.parentNodeId = message.parentNodeId;
925
- }
926
- if (message.nodeTx.length !== 0) {
927
- obj.nodeTx = base64FromBytes(message.nodeTx);
928
- }
929
- if (message.refundTx.length !== 0) {
930
- obj.refundTx = base64FromBytes(message.refundTx);
931
- }
932
- if (message.vout !== 0) {
933
- obj.vout = Math.round(message.vout);
934
- }
935
- if (message.verifyingPublicKey.length !== 0) {
936
- obj.verifyingPublicKey = base64FromBytes(message.verifyingPublicKey);
937
- }
938
- if (message.ownerIdentityPublicKey.length !== 0) {
939
- obj.ownerIdentityPublicKey = base64FromBytes(message.ownerIdentityPublicKey);
940
- }
941
- if (message.signingKeyshare !== void 0) {
942
- obj.signingKeyshare = SigningKeyshare.toJSON(message.signingKeyshare);
943
- }
944
- if (message.status !== "") {
945
- obj.status = message.status;
946
- }
947
- if (message.network !== 0) {
948
- obj.network = networkToJSON(message.network);
949
- }
950
- if (message.createdTime !== void 0) {
951
- obj.createdTime = message.createdTime.toISOString();
952
- }
953
- if (message.updatedTime !== void 0) {
954
- obj.updatedTime = message.updatedTime.toISOString();
955
- }
956
- if (message.ownerSigningPublicKey.length !== 0) {
957
- obj.ownerSigningPublicKey = base64FromBytes(message.ownerSigningPublicKey);
958
- }
959
- if (message.directTx.length !== 0) {
960
- obj.directTx = base64FromBytes(message.directTx);
961
- }
962
- if (message.directRefundTx.length !== 0) {
963
- obj.directRefundTx = base64FromBytes(message.directRefundTx);
964
- }
965
- if (message.directFromCpfpRefundTx.length !== 0) {
966
- obj.directFromCpfpRefundTx = base64FromBytes(message.directFromCpfpRefundTx);
967
- }
968
- return obj;
969
- },
970
- create(base) {
971
- return TreeNode.fromPartial(base ?? {});
972
- },
973
- fromPartial(object) {
974
- const message = createBaseTreeNode();
975
- message.id = object.id ?? "";
976
- message.treeId = object.treeId ?? "";
977
- message.value = object.value ?? 0;
978
- message.parentNodeId = object.parentNodeId ?? void 0;
979
- message.nodeTx = object.nodeTx ?? new Uint8Array(0);
980
- message.refundTx = object.refundTx ?? new Uint8Array(0);
981
- message.vout = object.vout ?? 0;
982
- message.verifyingPublicKey = object.verifyingPublicKey ?? new Uint8Array(0);
983
- message.ownerIdentityPublicKey = object.ownerIdentityPublicKey ?? new Uint8Array(0);
984
- message.signingKeyshare = object.signingKeyshare !== void 0 && object.signingKeyshare !== null ? SigningKeyshare.fromPartial(object.signingKeyshare) : void 0;
985
- message.status = object.status ?? "";
986
- message.network = object.network ?? 0;
987
- message.createdTime = object.createdTime ?? void 0;
988
- message.updatedTime = object.updatedTime ?? void 0;
989
- message.ownerSigningPublicKey = object.ownerSigningPublicKey ?? new Uint8Array(0);
990
- message.directTx = object.directTx ?? new Uint8Array(0);
991
- message.directRefundTx = object.directRefundTx ?? new Uint8Array(0);
992
- message.directFromCpfpRefundTx = object.directFromCpfpRefundTx ?? new Uint8Array(0);
993
- return message;
994
- }
995
- };
996
- function createBaseSparkAddress() {
997
- return { identityPublicKey: new Uint8Array(0), paymentIntentFields: void 0 };
998
- }
999
- var SparkAddress = {
1000
- encode(message, writer = new import_wire4.BinaryWriter()) {
1001
- if (message.identityPublicKey.length !== 0) {
1002
- writer.uint32(10).bytes(message.identityPublicKey);
1003
- }
1004
- if (message.paymentIntentFields !== void 0) {
1005
- PaymentIntentFields.encode(message.paymentIntentFields, writer.uint32(18).fork()).join();
1006
- }
1007
- return writer;
1008
- },
1009
- decode(input, length) {
1010
- const reader = input instanceof import_wire4.BinaryReader ? input : new import_wire4.BinaryReader(input);
1011
- const end = length === void 0 ? reader.len : reader.pos + length;
1012
- const message = createBaseSparkAddress();
1013
- while (reader.pos < end) {
1014
- const tag = reader.uint32();
1015
- switch (tag >>> 3) {
1016
- case 1: {
1017
- if (tag !== 10) {
1018
- break;
1019
- }
1020
- message.identityPublicKey = reader.bytes();
1021
- continue;
1022
- }
1023
- case 2: {
1024
- if (tag !== 18) {
1025
- break;
1026
- }
1027
- message.paymentIntentFields = PaymentIntentFields.decode(reader, reader.uint32());
1028
- continue;
1029
- }
1030
- }
1031
- if ((tag & 7) === 4 || tag === 0) {
1032
- break;
1033
- }
1034
- reader.skip(tag & 7);
1035
- }
1036
- return message;
1037
- },
1038
- fromJSON(object) {
1039
- return {
1040
- identityPublicKey: isSet2(object.identityPublicKey) ? bytesFromBase64(object.identityPublicKey) : new Uint8Array(0),
1041
- paymentIntentFields: isSet2(object.paymentIntentFields) ? PaymentIntentFields.fromJSON(object.paymentIntentFields) : void 0
1042
- };
1043
- },
1044
- toJSON(message) {
1045
- const obj = {};
1046
- if (message.identityPublicKey.length !== 0) {
1047
- obj.identityPublicKey = base64FromBytes(message.identityPublicKey);
1048
- }
1049
- if (message.paymentIntentFields !== void 0) {
1050
- obj.paymentIntentFields = PaymentIntentFields.toJSON(message.paymentIntentFields);
1051
- }
1052
- return obj;
1053
- },
1054
- create(base) {
1055
- return SparkAddress.fromPartial(base ?? {});
1056
- },
1057
- fromPartial(object) {
1058
- const message = createBaseSparkAddress();
1059
- message.identityPublicKey = object.identityPublicKey ?? new Uint8Array(0);
1060
- message.paymentIntentFields = object.paymentIntentFields !== void 0 && object.paymentIntentFields !== null ? PaymentIntentFields.fromPartial(object.paymentIntentFields) : void 0;
1061
- return message;
1062
- }
1063
- };
1064
- function createBasePaymentIntentFields() {
1065
- return { id: new Uint8Array(0), assetIdentifier: void 0, assetAmount: new Uint8Array(0), memo: void 0 };
1066
- }
1067
- var PaymentIntentFields = {
1068
- encode(message, writer = new import_wire4.BinaryWriter()) {
1069
- if (message.id.length !== 0) {
1070
- writer.uint32(10).bytes(message.id);
1071
- }
1072
- if (message.assetIdentifier !== void 0) {
1073
- writer.uint32(18).bytes(message.assetIdentifier);
1074
- }
1075
- if (message.assetAmount.length !== 0) {
1076
- writer.uint32(26).bytes(message.assetAmount);
1077
- }
1078
- if (message.memo !== void 0) {
1079
- writer.uint32(34).string(message.memo);
1080
- }
1081
- return writer;
1082
- },
1083
- decode(input, length) {
1084
- const reader = input instanceof import_wire4.BinaryReader ? input : new import_wire4.BinaryReader(input);
1085
- const end = length === void 0 ? reader.len : reader.pos + length;
1086
- const message = createBasePaymentIntentFields();
1087
- while (reader.pos < end) {
1088
- const tag = reader.uint32();
1089
- switch (tag >>> 3) {
1090
- case 1: {
1091
- if (tag !== 10) {
1092
- break;
1093
- }
1094
- message.id = reader.bytes();
1095
- continue;
1096
- }
1097
- case 2: {
1098
- if (tag !== 18) {
1099
- break;
1100
- }
1101
- message.assetIdentifier = reader.bytes();
1102
- continue;
1103
- }
1104
- case 3: {
1105
- if (tag !== 26) {
1106
- break;
1107
- }
1108
- message.assetAmount = reader.bytes();
1109
- continue;
1110
- }
1111
- case 4: {
1112
- if (tag !== 34) {
1113
- break;
1114
- }
1115
- message.memo = reader.string();
1116
- continue;
1117
- }
1118
- }
1119
- if ((tag & 7) === 4 || tag === 0) {
1120
- break;
1121
- }
1122
- reader.skip(tag & 7);
1123
- }
1124
- return message;
1125
- },
1126
- fromJSON(object) {
1127
- return {
1128
- id: isSet2(object.id) ? bytesFromBase64(object.id) : new Uint8Array(0),
1129
- assetIdentifier: isSet2(object.assetIdentifier) ? bytesFromBase64(object.assetIdentifier) : void 0,
1130
- assetAmount: isSet2(object.assetAmount) ? bytesFromBase64(object.assetAmount) : new Uint8Array(0),
1131
- memo: isSet2(object.memo) ? globalThis.String(object.memo) : void 0
1132
- };
1133
- },
1134
- toJSON(message) {
1135
- const obj = {};
1136
- if (message.id.length !== 0) {
1137
- obj.id = base64FromBytes(message.id);
1138
- }
1139
- if (message.assetIdentifier !== void 0) {
1140
- obj.assetIdentifier = base64FromBytes(message.assetIdentifier);
1141
- }
1142
- if (message.assetAmount.length !== 0) {
1143
- obj.assetAmount = base64FromBytes(message.assetAmount);
1144
- }
1145
- if (message.memo !== void 0) {
1146
- obj.memo = message.memo;
1147
- }
1148
- return obj;
1149
- },
1150
- create(base) {
1151
- return PaymentIntentFields.fromPartial(base ?? {});
1152
- },
1153
- fromPartial(object) {
1154
- const message = createBasePaymentIntentFields();
1155
- message.id = object.id ?? new Uint8Array(0);
1156
- message.assetIdentifier = object.assetIdentifier ?? void 0;
1157
- message.assetAmount = object.assetAmount ?? new Uint8Array(0);
1158
- message.memo = object.memo ?? void 0;
1159
- return message;
1160
- }
1161
- };
1162
- function bytesFromBase64(b64) {
1163
- if (globalThis.Buffer) {
1164
- return Uint8Array.from(globalThis.Buffer.from(b64, "base64"));
1165
- } else {
1166
- const bin = globalThis.atob(b64);
1167
- const arr = new Uint8Array(bin.length);
1168
- for (let i = 0; i < bin.length; ++i) {
1169
- arr[i] = bin.charCodeAt(i);
1170
- }
1171
- return arr;
1172
- }
1173
- }
1174
- function base64FromBytes(arr) {
1175
- if (globalThis.Buffer) {
1176
- return globalThis.Buffer.from(arr).toString("base64");
1177
- } else {
1178
- const bin = [];
1179
- arr.forEach((byte) => {
1180
- bin.push(globalThis.String.fromCharCode(byte));
1181
- });
1182
- return globalThis.btoa(bin.join(""));
1183
- }
1184
- }
1185
- function toTimestamp(date) {
1186
- const seconds = Math.trunc(date.getTime() / 1e3);
1187
- const nanos = date.getTime() % 1e3 * 1e6;
1188
- return { seconds, nanos };
1189
- }
1190
- function fromTimestamp(t) {
1191
- let millis = (t.seconds || 0) * 1e3;
1192
- millis += (t.nanos || 0) / 1e6;
1193
- return new globalThis.Date(millis);
1194
- }
1195
- function fromJsonTimestamp(o) {
1196
- if (o instanceof globalThis.Date) {
1197
- return o;
1198
- } else if (typeof o === "string") {
1199
- return new globalThis.Date(o);
1200
- } else {
1201
- return fromTimestamp(Timestamp.fromJSON(o));
1202
- }
1203
- }
1204
- function longToNumber2(int64) {
1205
- const num = globalThis.Number(int64.toString());
1206
- if (num > globalThis.Number.MAX_SAFE_INTEGER) {
1207
- throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
1208
- }
1209
- if (num < globalThis.Number.MIN_SAFE_INTEGER) {
1210
- throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
1211
- }
1212
- return num;
1213
- }
1214
- function isObject(value) {
1215
- return typeof value === "object" && value !== null;
1216
- }
1217
- function isSet2(value) {
1218
- return value !== null && value !== void 0;
1219
- }
1220
-
1221
- // src/graphql/objects/BitcoinNetwork.ts
1222
- var BitcoinNetwork = /* @__PURE__ */ ((BitcoinNetwork2) => {
1223
- BitcoinNetwork2["FUTURE_VALUE"] = "FUTURE_VALUE";
1224
- BitcoinNetwork2["MAINNET"] = "MAINNET";
1225
- BitcoinNetwork2["REGTEST"] = "REGTEST";
1226
- BitcoinNetwork2["SIGNET"] = "SIGNET";
1227
- BitcoinNetwork2["TESTNET"] = "TESTNET";
1228
- return BitcoinNetwork2;
1229
- })(BitcoinNetwork || {});
1230
- var BitcoinNetwork_default = BitcoinNetwork;
1231
-
1232
- // src/utils/network.ts
1233
- var Network2 = /* @__PURE__ */ ((Network4) => {
1234
- Network4[Network4["MAINNET"] = 0] = "MAINNET";
1235
- Network4[Network4["TESTNET"] = 1] = "TESTNET";
1236
- Network4[Network4["SIGNET"] = 2] = "SIGNET";
1237
- Network4[Network4["REGTEST"] = 3] = "REGTEST";
1238
- Network4[Network4["LOCAL"] = 4] = "LOCAL";
1239
- return Network4;
1240
- })(Network2 || {});
1241
- var NetworkToProto = {
1242
- [0 /* MAINNET */]: 1 /* MAINNET */,
1243
- [1 /* TESTNET */]: 3 /* TESTNET */,
1244
- [2 /* SIGNET */]: 4 /* SIGNET */,
1245
- [3 /* REGTEST */]: 2 /* REGTEST */,
1246
- [4 /* LOCAL */]: 2 /* REGTEST */
1247
- };
1248
- var NetworkConfig = {
1249
- [0 /* MAINNET */]: btc.NETWORK,
1250
- [1 /* TESTNET */]: btc.TEST_NETWORK,
1251
- [2 /* SIGNET */]: btc.TEST_NETWORK,
1252
- [3 /* REGTEST */]: { ...btc.TEST_NETWORK, bech32: "bcrt" },
1253
- [4 /* LOCAL */]: { ...btc.TEST_NETWORK, bech32: "bcrt" }
1254
- };
1255
- var getNetwork = (network) => NetworkConfig[network];
1256
- var LRC_WALLET_NETWORK = Object.freeze({
1257
- [0 /* MAINNET */]: bitcoin.networks.bitcoin,
1258
- [1 /* TESTNET */]: bitcoin.networks.testnet,
1259
- [2 /* SIGNET */]: bitcoin.networks.testnet,
1260
- [3 /* REGTEST */]: bitcoin.networks.regtest,
1261
- [4 /* LOCAL */]: bitcoin.networks.regtest
1262
- });
1263
- var LRC_WALLET_NETWORK_TYPE = Object.freeze({
1264
- [0 /* MAINNET */]: import_lrc20_sdk.NetworkType.MAINNET,
1265
- [1 /* TESTNET */]: import_lrc20_sdk.NetworkType.TESTNET,
1266
- [2 /* SIGNET */]: import_lrc20_sdk.NetworkType.TESTNET,
1267
- [3 /* REGTEST */]: import_lrc20_sdk.NetworkType.REGTEST,
1268
- [4 /* LOCAL */]: import_lrc20_sdk.NetworkType.LOCAL
1269
- });
1270
- function getNetworkFromAddress(address2) {
1271
- try {
1272
- const decoded = bitcoin.address.fromBech32(address2);
1273
- if (decoded.prefix === "bc") {
1274
- return "MAINNET" /* MAINNET */;
1275
- } else if (decoded.prefix === "bcrt") {
1276
- return "REGTEST" /* REGTEST */;
1277
- }
1278
- } catch (err) {
1279
- throw new ValidationError(
1280
- "Invalid Bitcoin address",
1281
- {
1282
- field: "address",
1283
- value: address2,
1284
- expected: "Valid Bech32 address with prefix 'bc' or 'bcrt'"
1285
- },
1286
- err instanceof Error ? err : void 0
1287
- );
1288
- }
1289
- return null;
1290
- }
1291
- function getNetworkFromString(network) {
1292
- const net = (network ?? "REGTEST").toUpperCase();
1293
- if (net === "MAINNET") return 0 /* MAINNET */;
1294
- if (net === "TESTNET") return 1 /* TESTNET */;
1295
- if (net === "SIGNET") return 2 /* SIGNET */;
1296
- if (net === "LOCAL") return 4 /* LOCAL */;
1297
- return 3 /* REGTEST */;
1298
- }
1299
-
1300
- // src/utils/bitcoin.ts
1301
- function computeTaprootKeyNoScript(pubkey) {
1302
- if (pubkey.length !== 32) {
1303
- throw new ValidationError("Public key must be 32 bytes", {
1304
- field: "pubkey",
1305
- value: pubkey.length,
1306
- expected: 32
1307
- });
1308
- }
1309
- const taggedHash = import_secp256k12.schnorr.utils.taggedHash("TapTweak", pubkey);
1310
- const tweak = (0, import_utils3.bytesToNumberBE)(taggedHash);
1311
- const P = import_secp256k12.schnorr.utils.lift_x(import_secp256k12.schnorr.utils.bytesToNumberBE(pubkey));
1312
- const Q = P.add(import_secp256k12.secp256k1.ProjectivePoint.fromPrivateKey(tweak));
1313
- return Q.toRawBytes();
1314
- }
1315
- function getP2TRScriptFromPublicKey(pubKey, network) {
1316
- if (pubKey.length !== 33) {
1317
- throw new ValidationError("Public key must be 33 bytes", {
1318
- field: "pubKey",
1319
- value: pubKey.length,
1320
- expected: 33
1321
- });
1322
- }
1323
- const internalKey = import_secp256k12.secp256k1.ProjectivePoint.fromHex(pubKey);
1324
- const script = btc2.p2tr(
1325
- internalKey.toRawBytes().slice(1, 33),
1326
- void 0,
1327
- getNetwork(network)
1328
- ).script;
1329
- if (!script) {
1330
- throw new ValidationError("Failed to get P2TR script", {
1331
- field: "script",
1332
- value: "null"
1333
- });
1334
- }
1335
- return script;
1336
- }
1337
- function getP2TRAddressFromPublicKey(pubKey, network) {
1338
- if (pubKey.length !== 33) {
1339
- throw new ValidationError("Public key must be 33 bytes", {
1340
- field: "pubKey",
1341
- value: pubKey.length,
1342
- expected: 33
1343
- });
1344
- }
1345
- const internalKey = import_secp256k12.secp256k1.ProjectivePoint.fromHex(pubKey);
1346
- const address2 = btc2.p2tr(
1347
- internalKey.toRawBytes().slice(1, 33),
1348
- void 0,
1349
- getNetwork(network)
1350
- ).address;
1351
- if (!address2) {
1352
- throw new ValidationError("Failed to get P2TR address", {
1353
- field: "address",
1354
- value: "null"
1355
- });
1356
- }
1357
- return address2;
1358
- }
1359
- function getP2TRAddressFromPkScript(pkScript, network) {
1360
- if (pkScript.length !== 34 || pkScript[0] !== 81 || pkScript[1] !== 32) {
1361
- throw new ValidationError("Invalid pkscript", {
1362
- field: "pkScript",
1363
- value: (0, import_utils3.bytesToHex)(pkScript),
1364
- expected: "34 bytes starting with 0x51 0x20"
1365
- });
1366
- }
1367
- const parsedScript = btc2.OutScript.decode(pkScript);
1368
- return btc2.Address(getNetwork(network)).encode(parsedScript);
1369
- }
1370
- function getP2WPKHAddressFromPublicKey(pubKey, network) {
1371
- if (pubKey.length !== 33) {
1372
- throw new ValidationError("Public key must be 33 bytes", {
1373
- field: "pubKey",
1374
- value: pubKey.length,
1375
- expected: 33
1376
- });
1377
- }
1378
- const address2 = btc2.p2wpkh(pubKey, getNetwork(network)).address;
1379
- if (!address2) {
1380
- throw new ValidationError("Failed to get P2WPKH address", {
1381
- field: "address",
1382
- value: "null"
1383
- });
1384
- }
1385
- return address2;
1386
- }
1387
- function getTxFromRawTxHex(rawTxHex) {
1388
- const txBytes = (0, import_utils3.hexToBytes)(rawTxHex);
1389
- const tx = btc2.Transaction.fromRaw(txBytes, {
1390
- allowUnknownOutputs: true
1391
- });
1392
- if (!tx) {
1393
- throw new ValidationError("Failed to parse transaction", {
1394
- field: "tx",
1395
- value: "null"
1396
- });
1397
- }
1398
- return tx;
1399
- }
1400
- function getTxFromRawTxBytes(rawTxBytes) {
1401
- const tx = btc2.Transaction.fromRaw(rawTxBytes, {
1402
- allowUnknownOutputs: true
1403
- });
1404
- if (!tx) {
1405
- throw new ValidationError("Failed to parse transaction", {
1406
- field: "tx",
1407
- value: "null"
1408
- });
1409
- }
1410
- return tx;
1411
- }
1412
- function getSigHashFromTx(tx, inputIndex, prevOutput) {
1413
- const prevScript = prevOutput.script;
1414
- if (!prevScript) {
1415
- throw new ValidationError("No script found in prevOutput", {
1416
- field: "prevScript",
1417
- value: "null"
1418
- });
1419
- }
1420
- const amount = prevOutput.amount;
1421
- if (!amount) {
1422
- throw new ValidationError("No amount found in prevOutput", {
1423
- field: "amount",
1424
- value: "null"
1425
- });
1426
- }
1427
- return tx.preimageWitnessV1(
1428
- inputIndex,
1429
- new Array(tx.inputsLength).fill(prevScript),
1430
- btc2.SigHash.DEFAULT,
1431
- new Array(tx.inputsLength).fill(amount)
1432
- );
1433
- }
1434
- function getTxId(tx) {
1435
- return (0, import_utils3.bytesToHex)((0, import_sha2.sha256)((0, import_sha2.sha256)(tx.toBytes(true))).reverse());
1436
- }
1437
- function getTxIdNoReverse(tx) {
1438
- return (0, import_utils3.bytesToHex)((0, import_sha2.sha256)((0, import_sha2.sha256)(tx.toBytes(true))));
1439
- }
1440
-
1441
- // src/utils/keys.ts
1442
- var import_utils4 = require("@noble/curves/abstract/utils");
1443
- var import_secp256k13 = require("@noble/curves/secp256k1");
1444
- function addPublicKeys(a, b) {
1445
- if (a.length !== 33 || b.length !== 33) {
1446
- throw new ValidationError("Public keys must be 33 bytes", {
1447
- field: "publicKeys",
1448
- value: `a: ${a.length}, b: ${b.length}`,
1449
- expected: 33
1450
- });
1451
- }
1452
- const pubkeyA = import_secp256k13.secp256k1.ProjectivePoint.fromHex(a);
1453
- const pubkeyB = import_secp256k13.secp256k1.ProjectivePoint.fromHex(b);
1454
- return pubkeyA.add(pubkeyB).toRawBytes(true);
1455
- }
1456
- function applyAdditiveTweakToPublicKey(pubkey, tweak) {
1457
- if (pubkey.length !== 33) {
1458
- throw new ValidationError("Public key must be 33 bytes", {
1459
- field: "pubkey",
1460
- value: pubkey.length,
1461
- expected: 33
1462
- });
1463
- }
1464
- if (tweak.length !== 32) {
1465
- throw new ValidationError("Tweak must be 32 bytes", {
1466
- field: "tweak",
1467
- value: tweak.length,
1468
- expected: 32
1469
- });
1470
- }
1471
- const pubkeyPoint = import_secp256k13.secp256k1.ProjectivePoint.fromHex(pubkey);
1472
- const privTweek = import_secp256k13.secp256k1.utils.normPrivateKeyToScalar(tweak);
1473
- const pubTweek = import_secp256k13.secp256k1.getPublicKey(privTweek, true);
1474
- const tweekPoint = import_secp256k13.secp256k1.ProjectivePoint.fromHex(pubTweek);
1475
- return pubkeyPoint.add(tweekPoint).toRawBytes(true);
1476
- }
1477
- function subtractPublicKeys(a, b) {
1478
- if (a.length !== 33 || b.length !== 33) {
1479
- throw new ValidationError("Public keys must be 33 bytes", {
1480
- field: "publicKeys",
1481
- value: `a: ${a.length}, b: ${b.length}`,
1482
- expected: 33
1483
- });
1484
- }
1485
- const pubkeyA = import_secp256k13.secp256k1.ProjectivePoint.fromHex(a);
1486
- const pubkeyB = import_secp256k13.secp256k1.ProjectivePoint.fromHex(b);
1487
- return pubkeyA.subtract(pubkeyB).toRawBytes(true);
1488
- }
1489
- function addPrivateKeys(a, b) {
1490
- if (a.length !== 32 || b.length !== 32) {
1491
- throw new ValidationError("Private keys must be 32 bytes", {
1492
- field: "privateKeys",
1493
- value: `a: ${a.length}, b: ${b.length}`,
1494
- expected: 32
1495
- });
1496
- }
1497
- const privA = import_secp256k13.secp256k1.utils.normPrivateKeyToScalar(a);
1498
- const privB = import_secp256k13.secp256k1.utils.normPrivateKeyToScalar(b);
1499
- const sum = (privA + privB) % import_secp256k13.secp256k1.CURVE.n;
1500
- return (0, import_utils4.numberToBytesBE)(sum, 32);
1501
- }
1502
- function subtractPrivateKeys(a, b) {
1503
- if (a.length !== 32 || b.length !== 32) {
1504
- throw new ValidationError("Private keys must be 32 bytes", {
1505
- field: "privateKeys",
1506
- value: `a: ${a.length}, b: ${b.length}`,
1507
- expected: 32
1508
- });
1509
- }
1510
- const privA = import_secp256k13.secp256k1.utils.normPrivateKeyToScalar(a);
1511
- const privB = import_secp256k13.secp256k1.utils.normPrivateKeyToScalar(b);
1512
- const sum = (import_secp256k13.secp256k1.CURVE.n - privB + privA) % import_secp256k13.secp256k1.CURVE.n;
1513
- return (0, import_utils4.numberToBytesBE)(sum, 32);
1514
- }
1515
- function sumOfPrivateKeys(keys) {
1516
- return keys.reduce((sum, key) => {
1517
- if (key.length !== 32) {
1518
- throw new ValidationError("Private keys must be 32 bytes", {
1519
- field: "privateKey",
1520
- value: key.length,
1521
- expected: 32
1522
- });
1523
- }
1524
- return addPrivateKeys(sum, key);
1525
- });
1526
- }
1527
- function lastKeyWithTarget(target, keys) {
1528
- if (target.length !== 32) {
1529
- throw new ValidationError("Target must be 32 bytes", {
1530
- field: "target",
1531
- value: target.length,
1532
- expected: 32
1533
- });
1534
- }
1535
- const sum = sumOfPrivateKeys(keys);
1536
- return subtractPrivateKeys(target, sum);
1537
- }
1538
-
1539
- // src/tests/isHermeticTest.ts
1540
- var import_core = require("@lightsparkdev/core");
1541
- var import_fs = __toESM(require("fs"), 1);
1542
- function isHermeticTest() {
1543
- if (import_core.isNode) {
1544
- return (import_fs.default?.existsSync?.("/tmp/spark_hermetic") ?? false) || process.env.HERMETIC_TEST === "true";
1545
- }
1546
- return typeof process !== "undefined" && process.env?.HERMETIC_TEST === "true" || false;
1547
- }
1548
-
1549
- // src/services/wallet-config.ts
1550
- var SSP_IDENTITY_PUBLIC_KEYS = {
1551
- LOCAL: "028c094a432d46a0ac95349d792c2e3730bd60c29188db716f56a99e39b95338b4",
1552
- REGTEST: {
1553
- PROD: "022bf283544b16c0622daecb79422007d167eca6ce9f0c98c0c49833b1f7170bfe"
1554
- },
1555
- MAINNET: {
1556
- PROD: "023e33e2920326f64ea31058d44777442d97d7d5cbfcf54e3060bc1695e5261c93"
1557
- }
1558
- };
1559
- var URL_CONFIG = {
1560
- LOCAL: {
1561
- SSP: "http://127.0.0.1:5000",
1562
- ELECTRS: "http://127.0.0.1:30000",
1563
- LRC20: "http://127.0.0.1:18530",
1564
- LRC20_NODE: "http://127.0.0.1:18332"
1565
- },
1566
- REGTEST: {
1567
- PROD: {
1568
- SSP: "https://api.lightspark.com",
1569
- ELECTRS: "https://regtest-mempool.us-west-2.sparkinfra.net/api",
1570
- LRC20: "https://regtest.lrc20.lightspark.com:443",
1571
- LRC20_NODE: "https://regtest.lrc20.lightspark.com"
1572
- }
1573
- },
1574
- MAINNET: {
1575
- PROD: {
1576
- SSP: "https://api.lightspark.com",
1577
- ELECTRS: "https://mempool.space/api",
1578
- LRC20: "https://mainnet.lrc20.lightspark.com:443",
1579
- LRC20_NODE: "https://mainnet.lrc20.lightspark.com"
1580
- }
1581
- }
1582
- };
1583
- var ELECTRS_CREDENTIALS = {
1584
- username: "spark-sdk",
1585
- password: "mCMk1JqlBNtetUNy"
1586
- };
1587
- function getElectrsUrl(network) {
1588
- switch (network) {
1589
- case "LOCAL":
1590
- return isHermeticTest() ? "http://mempool.minikube.local/api" : URL_CONFIG.LOCAL.ELECTRS;
1591
- case "REGTEST":
1592
- return URL_CONFIG.REGTEST.PROD.ELECTRS;
1593
- case "MAINNET":
1594
- return URL_CONFIG.MAINNET.PROD.ELECTRS;
1595
- default:
1596
- return URL_CONFIG.LOCAL.ELECTRS;
1597
- }
1598
- }
1599
- function getLrc20Url(network) {
1600
- switch (network) {
1601
- case "LOCAL":
1602
- return URL_CONFIG.LOCAL.LRC20;
1603
- case "REGTEST":
1604
- return URL_CONFIG.REGTEST.PROD.LRC20;
1605
- case "MAINNET":
1606
- return URL_CONFIG.MAINNET.PROD.LRC20;
1607
- default:
1608
- return URL_CONFIG.LOCAL.LRC20;
1609
- }
1610
- }
1611
- function getLrc20NodeUrl(network) {
1612
- switch (network) {
1613
- case "LOCAL":
1614
- return URL_CONFIG.LOCAL.LRC20_NODE;
1615
- case "REGTEST":
1616
- return URL_CONFIG.REGTEST.PROD.LRC20_NODE;
1617
- case "MAINNET":
1618
- return URL_CONFIG.MAINNET.PROD.LRC20_NODE;
1619
- default:
1620
- return URL_CONFIG.LOCAL.LRC20_NODE;
1621
- }
1622
- }
1623
- function getSspIdentityPublicKey(network) {
1624
- switch (network) {
1625
- case "LOCAL":
1626
- return SSP_IDENTITY_PUBLIC_KEYS.LOCAL;
1627
- case "REGTEST":
1628
- return SSP_IDENTITY_PUBLIC_KEYS.REGTEST.PROD;
1629
- case "MAINNET":
1630
- return SSP_IDENTITY_PUBLIC_KEYS.MAINNET.PROD;
1631
- default:
1632
- return SSP_IDENTITY_PUBLIC_KEYS.LOCAL;
1633
- }
1634
- }
1635
- function getSspUrl(network) {
1636
- switch (network) {
1637
- case "LOCAL":
1638
- return isHermeticTest() ? "http://app.minikube.local" : URL_CONFIG.LOCAL.SSP;
1639
- case "REGTEST":
1640
- return URL_CONFIG.REGTEST.PROD.SSP;
1641
- case "MAINNET":
1642
- return URL_CONFIG.MAINNET.PROD.SSP;
1643
- default:
1644
- return URL_CONFIG.LOCAL.SSP;
1645
- }
1646
- }
1647
- function getSspSchemaEndpoint(network) {
1648
- switch (network) {
1649
- case "LOCAL":
1650
- return "graphql/spark/rc";
1651
- }
1652
- return;
1653
- }
1654
- var PROD_PUBKEYS = [
1655
- "03dfbdff4b6332c220f8fa2ba8ed496c698ceada563fa01b67d9983bfc5c95e763",
1656
- "03e625e9768651c9be268e287245cc33f96a68ce9141b0b4769205db027ee8ed77",
1657
- "022eda13465a59205413086130a65dc0ed1b8f8e51937043161f8be0c369b1a410"
1658
- ];
1659
- function getLocalFrostSignerAddress() {
1660
- return isHermeticTest() ? "localhost:9999" : "unix:///tmp/frost_0.sock";
1661
- }
1662
- var BASE_CONFIG = {
1663
- network: "LOCAL",
1664
- lrc20Address: getLrc20Url("LOCAL"),
1665
- coodinatorIdentifier: "0000000000000000000000000000000000000000000000000000000000000001",
1666
- frostSignerAddress: getLocalFrostSignerAddress(),
1667
- threshold: 2,
1668
- signingOperators: getLocalSigningOperators(),
1669
- tokenSignatures: "SCHNORR",
1670
- tokenTransactionVersion: "V1",
1671
- tokenValidityDurationSeconds: 180,
1672
- electrsUrl: getElectrsUrl("LOCAL"),
1673
- expectedWithdrawBondSats: 1e4,
1674
- expectedWithdrawRelativeBlockLocktime: 1e3,
1675
- lrc20ApiConfig: {
1676
- electrsUrl: getElectrsUrl("LOCAL"),
1677
- lrc20NodeUrl: getLrc20NodeUrl("LOCAL"),
1678
- electrsCredentials: ELECTRS_CREDENTIALS
1679
- },
1680
- sspClientOptions: {
1681
- baseUrl: getSspUrl("LOCAL"),
1682
- identityPublicKey: getSspIdentityPublicKey("LOCAL"),
1683
- schemaEndpoint: getSspSchemaEndpoint("LOCAL")
1684
- }
1685
- };
1686
- var LOCAL_WALLET_CONFIG = {
1687
- ...BASE_CONFIG,
1688
- threshold: 3
1689
- };
1690
- var LOCAL_WALLET_CONFIG_SCHNORR = {
1691
- ...LOCAL_WALLET_CONFIG,
1692
- threshold: 3
1693
- // 3 for issuance tests.
1694
- };
1695
- var LOCAL_WALLET_CONFIG_ECDSA = {
1696
- ...LOCAL_WALLET_CONFIG,
1697
- tokenSignatures: "ECDSA",
1698
- threshold: 3
1699
- // 3 for issuance tests.
1700
- };
1701
- var REGTEST_WALLET_CONFIG = {
1702
- ...BASE_CONFIG,
1703
- network: "REGTEST",
1704
- lrc20Address: getLrc20Url("REGTEST"),
1705
- signingOperators: getSigningOperators(),
1706
- electrsUrl: getElectrsUrl("REGTEST"),
1707
- lrc20ApiConfig: {
1708
- electrsUrl: getElectrsUrl("REGTEST"),
1709
- lrc20NodeUrl: getLrc20NodeUrl("REGTEST"),
1710
- electrsCredentials: ELECTRS_CREDENTIALS
1711
- },
1712
- expectedWithdrawBondSats: 1e4,
1713
- expectedWithdrawRelativeBlockLocktime: 1e3,
1714
- sspClientOptions: {
1715
- baseUrl: getSspUrl("REGTEST"),
1716
- identityPublicKey: getSspIdentityPublicKey("REGTEST")
1717
- }
1718
- };
1719
- var MAINNET_WALLET_CONFIG = {
1720
- ...BASE_CONFIG,
1721
- network: "MAINNET",
1722
- lrc20Address: getLrc20Url("MAINNET"),
1723
- signingOperators: getSigningOperators(),
1724
- electrsUrl: getElectrsUrl("MAINNET"),
1725
- lrc20ApiConfig: {
1726
- electrsUrl: getElectrsUrl("MAINNET"),
1727
- lrc20NodeUrl: getLrc20NodeUrl("MAINNET")
1728
- },
1729
- expectedWithdrawBondSats: 1e4,
1730
- expectedWithdrawRelativeBlockLocktime: 1e3,
1731
- sspClientOptions: {
1732
- baseUrl: getSspUrl("MAINNET"),
1733
- identityPublicKey: getSspIdentityPublicKey("MAINNET")
1734
- }
1735
- };
1736
- function getSigningOperators() {
1737
- return {
1738
- "0000000000000000000000000000000000000000000000000000000000000001": {
1739
- id: 0,
1740
- identifier: "0000000000000000000000000000000000000000000000000000000000000001",
1741
- address: "https://0.spark.lightspark.com",
1742
- identityPublicKey: PROD_PUBKEYS[0]
1743
- },
1744
- "0000000000000000000000000000000000000000000000000000000000000002": {
1745
- id: 1,
1746
- identifier: "0000000000000000000000000000000000000000000000000000000000000002",
1747
- address: "https://1.spark.lightspark.com",
1748
- identityPublicKey: PROD_PUBKEYS[1]
1749
- },
1750
- "0000000000000000000000000000000000000000000000000000000000000003": {
1751
- id: 2,
1752
- identifier: "0000000000000000000000000000000000000000000000000000000000000003",
1753
- address: "https://2.spark.flashnet.xyz",
1754
- identityPublicKey: PROD_PUBKEYS[2]
1755
- }
1756
- };
1757
- }
1758
- function getLocalSigningOperators() {
1759
- const pubkeys = [
1760
- "0322ca18fc489ae25418a0e768273c2c61cabb823edfb14feb891e9bec62016510",
1761
- "0341727a6c41b168f07eb50865ab8c397a53c7eef628ac1020956b705e43b6cb27",
1762
- "0305ab8d485cc752394de4981f8a5ae004f2becfea6f432c9a59d5022d8764f0a6",
1763
- "0352aef4d49439dedd798ac4aef1e7ebef95f569545b647a25338398c1247ffdea",
1764
- "02c05c88cc8fc181b1ba30006df6a4b0597de6490e24514fbdd0266d2b9cd3d0ba"
1765
- ];
1766
- return {
1767
- "0000000000000000000000000000000000000000000000000000000000000001": {
1768
- id: 0,
1769
- identifier: "0000000000000000000000000000000000000000000000000000000000000001",
1770
- address: "https://localhost:8535",
1771
- identityPublicKey: pubkeys[0]
1772
- },
1773
- "0000000000000000000000000000000000000000000000000000000000000002": {
1774
- id: 1,
1775
- identifier: "0000000000000000000000000000000000000000000000000000000000000002",
1776
- address: "https://localhost:8536",
1777
- identityPublicKey: pubkeys[1]
1778
- },
1779
- "0000000000000000000000000000000000000000000000000000000000000003": {
1780
- id: 2,
1781
- identifier: "0000000000000000000000000000000000000000000000000000000000000003",
1782
- address: "https://localhost:8537",
1783
- identityPublicKey: pubkeys[2]
1784
- },
1785
- "0000000000000000000000000000000000000000000000000000000000000004": {
1786
- id: 3,
1787
- identifier: "0000000000000000000000000000000000000000000000000000000000000004",
1788
- address: "https://localhost:8538",
1789
- identityPublicKey: pubkeys[3]
1790
- },
1791
- "0000000000000000000000000000000000000000000000000000000000000005": {
1792
- id: 4,
1793
- identifier: "0000000000000000000000000000000000000000000000000000000000000005",
1794
- address: "https://localhost:8539",
1795
- identityPublicKey: pubkeys[4]
1796
- }
1797
- };
1798
- }
1799
-
1800
- // src/graphql/objects/ClaimStaticDeposit.ts
1801
- var import_core2 = require("@lightsparkdev/core");
1802
-
1803
- // src/graphql/objects/CoopExitFeeQuote.ts
1804
- var import_core3 = require("@lightsparkdev/core");
1805
-
1806
- // src/graphql/objects/LeavesSwapRequest.ts
1807
- var import_core4 = require("@lightsparkdev/core");
1808
-
1809
- // src/graphql/objects/LightningReceiveRequest.ts
1810
- var import_core5 = require("@lightsparkdev/core");
1811
-
1812
- // src/graphql/objects/LightningSendRequest.ts
1813
- var import_core6 = require("@lightsparkdev/core");
1814
-
1815
- // src/graphql/objects/SparkWalletUser.ts
1816
- var import_core8 = require("@lightsparkdev/core");
1817
-
1818
- // src/graphql/objects/UserRequest.ts
1819
- var import_core7 = require("@lightsparkdev/core");
1820
-
1821
- // src/types/sdk-types.ts
1822
- var import_utils5 = require("@noble/curves/abstract/utils");
1823
-
1824
- // src/utils/mempool.ts
1825
- async function getLatestDepositTxId(address2) {
1826
- const network = getNetworkFromAddress(address2);
1827
- const baseUrl = network === BitcoinNetwork_default.REGTEST ? getElectrsUrl("REGTEST") : getElectrsUrl("MAINNET");
1828
- const headers = {};
1829
- if (network === BitcoinNetwork_default.REGTEST) {
1830
- const auth = btoa(
1831
- `${ELECTRS_CREDENTIALS.username}:${ELECTRS_CREDENTIALS.password}`
1832
- );
1833
- headers["Authorization"] = `Basic ${auth}`;
1834
- }
1835
- const response = await fetch(`${baseUrl}/address/${address2}/txs`, {
1836
- headers
1837
- });
1838
- const addressTxs = await response.json();
1839
- if (addressTxs && addressTxs.length > 0) {
1840
- const latestTx = addressTxs[0];
1841
- const outputIndex = latestTx.vout.findIndex(
1842
- (output) => output.scriptpubkey_address === address2
1843
- );
1844
- if (outputIndex === -1) {
1845
- return null;
1846
- }
1847
- return latestTx.txid;
1848
- }
1849
- return null;
1850
- }
1851
- async function isTxBroadcast(txid, baseUrl, network) {
1852
- const headers = {};
1853
- if (network === 3 /* REGTEST */) {
1854
- const auth = btoa(
1855
- `${ELECTRS_CREDENTIALS.username}:${ELECTRS_CREDENTIALS.password}`
1856
- );
1857
- headers["Authorization"] = `Basic ${auth}`;
1858
- }
1859
- const response = await fetch(`${baseUrl}/tx/${txid}`, {
1860
- headers
1861
- });
1862
- const tx = await response.json();
1863
- if (tx.error) {
1864
- return false;
1865
- }
1866
- return true;
1867
- }
1868
-
1869
- // src/utils/proof.ts
1870
- var import_sha22 = require("@noble/hashes/sha2");
1871
- function proofOfPossessionMessageHashForDepositAddress(userPubkey, operatorPubkey, depositAddress) {
1872
- const encoder = new TextEncoder();
1873
- const depositAddressBytes = encoder.encode(depositAddress);
1874
- const proofMsg = new Uint8Array([
1875
- ...userPubkey,
1876
- ...operatorPubkey,
1877
- ...depositAddressBytes
1878
- ]);
1879
- return (0, import_sha22.sha256)(proofMsg);
1880
- }
1881
-
1882
- // src/utils/response-validation.ts
1883
- function collectResponses(responses) {
1884
- const successfulResponses = responses.filter(
1885
- (result) => result.status === "fulfilled"
1886
- ).map((result) => result.value);
1887
- const failedResponses = responses.filter(
1888
- (result) => result.status === "rejected"
1889
- );
1890
- if (failedResponses.length > 0) {
1891
- const errors = failedResponses.map((result) => result.reason).join("\n");
1892
- throw new NetworkError(
1893
- `${failedResponses.length} out of ${responses.length} requests failed, please try again`,
1894
- {
1895
- errorCount: failedResponses.length,
1896
- errors
1897
- }
1898
- );
1899
- }
1900
- return successfulResponses;
1901
- }
1902
-
1903
- // src/utils/secret-sharing.ts
1904
- var import_utils6 = require("@noble/curves/abstract/utils");
1905
- var import_secp256k14 = require("@noble/curves/secp256k1");
1906
-
1907
- // src/utils/crypto.ts
1908
- var import_crypto = __toESM(require("crypto"), 1);
1909
- var getCrypto = () => {
1910
- let cryptoImpl = typeof window !== "undefined" ? window.crypto : typeof global !== "undefined" && global.crypto ? global.crypto : import_crypto.default;
1911
- return cryptoImpl;
1912
- };
1913
-
1914
- // src/utils/secret-sharing.ts
1915
- var crypto = getCrypto();
1916
- function getRandomBigInt(max) {
1917
- const byteLength = max.toString(2).length + 7 >> 3;
1918
- const maxBigInt = max;
1919
- const mask = (1n << BigInt(max.toString(2).length)) - 1n;
1920
- while (true) {
1921
- const randBytes = crypto.getRandomValues(new Uint8Array(byteLength + 1));
1922
- const randValue = BigInt("0x" + (0, import_utils6.bytesToHex)(randBytes)) & mask;
1923
- if (randValue < maxBigInt) {
1924
- return randValue;
1925
- }
1926
- }
1927
- }
1928
- function modInverse(a, m) {
1929
- a = (a % m + m) % m;
1930
- let [old_r, r] = [a, m];
1931
- let [old_s, s] = [1n, 0n];
1932
- let [old_t, t] = [0n, 1n];
1933
- while (r !== 0n) {
1934
- const quotient = old_r / r;
1935
- [old_r, r] = [r, old_r - quotient * r];
1936
- [old_s, s] = [s, old_s - quotient * s];
1937
- [old_t, t] = [t, old_t - quotient * t];
1938
- }
1939
- if (old_r !== 1n) {
1940
- throw new ValidationError("Modular inverse does not exist", {
1941
- field: "modInverse",
1942
- value: `a: ${a}, m: ${m}`,
1943
- expected: "a and m must be coprime"
1944
- });
1945
- }
1946
- return (old_s % m + m) % m;
1947
- }
1948
- function evaluatePolynomial(polynomial, x) {
1949
- let result = 0n;
1950
- for (let i = 0; i < polynomial.coefficients.length; i++) {
1951
- const coeff = polynomial.coefficients[i];
1952
- if (!coeff) {
1953
- throw new ValidationError("Coefficient is undefined", {
1954
- field: "coefficient",
1955
- value: "undefined",
1956
- expected: "A valid bigint coefficient"
1957
- });
1958
- }
1959
- const xPow = x ** BigInt(i) % polynomial.fieldModulus;
1960
- result = (result + xPow * coeff) % polynomial.fieldModulus;
1961
- }
1962
- return result;
1963
- }
1964
- function fieldDiv(numerator, denominator, fieldModulus) {
1965
- if (denominator === 0n) {
1966
- throw new ValidationError("Division by zero", {
1967
- field: "denominator",
1968
- value: "0",
1969
- expected: "Non-zero value"
1970
- });
1971
- }
1972
- const inverse = modInverse(denominator, fieldModulus);
1973
- return numerator * inverse % fieldModulus;
1974
- }
1975
- function computerLagrangeCoefficients(index, points) {
1976
- let numerator = 1n;
1977
- let denominator = 1n;
1978
- let fieldModulus = points[0]?.fieldModulus;
1979
- if (!fieldModulus) {
1980
- throw new ValidationError("Field modulus is undefined", {
1981
- field: "fieldModulus",
1982
- value: "undefined",
1983
- expected: "A valid field modulus"
1984
- });
1985
- }
1986
- for (const point of points) {
1987
- if (point.index === index) {
1988
- continue;
1989
- }
1990
- numerator = numerator * point.index;
1991
- const value = point.index - index;
1992
- denominator = denominator * value;
1993
- }
1994
- return fieldDiv(numerator, denominator, fieldModulus);
1995
- }
1996
- function generatePolynomialForSecretSharing(fieldModulus, secret, degree) {
1997
- const coefficients = new Array(degree);
1998
- const proofs = new Array(degree);
1999
- coefficients[0] = secret;
2000
- proofs[0] = import_secp256k14.secp256k1.ProjectivePoint.fromPrivateKey(secret).toRawBytes(true);
2001
- for (let i = 1; i < degree; i++) {
2002
- const coefficient = getRandomBigInt(fieldModulus);
2003
- coefficients[i] = coefficient;
2004
- proofs[i] = import_secp256k14.secp256k1.ProjectivePoint.fromPrivateKey(coefficient).toRawBytes(true);
2005
- }
2006
- return {
2007
- fieldModulus,
2008
- coefficients,
2009
- proofs
2010
- };
2011
- }
2012
- function splitSecret(fieldModulus, secret, threshold, numberOfShares) {
2013
- const polynomial = generatePolynomialForSecretSharing(
2014
- fieldModulus,
2015
- secret,
2016
- threshold
2017
- );
2018
- const shares = [];
2019
- for (let i = 1; i <= numberOfShares; i++) {
2020
- const share = evaluatePolynomial(polynomial, BigInt(i));
2021
- shares.push({
2022
- fieldModulus,
2023
- threshold,
2024
- index: BigInt(i),
2025
- share
2026
- });
2027
- }
2028
- return shares;
2029
- }
2030
- function splitSecretWithProofs(secret, fieldModulus, threshold, numberOfShares) {
2031
- const polynomial = generatePolynomialForSecretSharing(
2032
- fieldModulus,
2033
- secret,
2034
- threshold
2035
- );
2036
- const shares = [];
2037
- for (let i = 1; i <= numberOfShares; i++) {
2038
- const share = evaluatePolynomial(polynomial, BigInt(i));
2039
- shares.push({
2040
- fieldModulus,
2041
- threshold,
2042
- index: BigInt(i),
2043
- share,
2044
- proofs: polynomial.proofs
2045
- });
2046
- }
2047
- return shares;
2048
- }
2049
- function recoverSecret(shares) {
2050
- if (shares.length === 0) return 0n;
2051
- const threshold = shares[0]?.threshold;
2052
- const fieldModulus = shares[0]?.fieldModulus;
2053
- if (!threshold || !fieldModulus) {
2054
- throw new ValidationError("Shares are not valid", {
2055
- field: "shares",
2056
- value: "Missing threshold or fieldModulus",
2057
- expected: "Valid shares with threshold and fieldModulus"
2058
- });
2059
- }
2060
- if (shares.length < threshold) {
2061
- throw new ValidationError("Not enough shares to recover secret", {
2062
- field: "shares",
2063
- value: shares.length,
2064
- expected: `At least ${threshold} shares`
2065
- });
2066
- }
2067
- let result = 0n;
2068
- for (const share of shares) {
2069
- const coeff = computerLagrangeCoefficients(share.index, shares);
2070
- const item = share.share * coeff % fieldModulus;
2071
- result = (result + item) % fieldModulus;
2072
- }
2073
- return result;
2074
- }
2075
- function validateShare(share) {
2076
- const targetPubkey = import_secp256k14.secp256k1.ProjectivePoint.fromPrivateKey(
2077
- share.share
2078
- ).toRawBytes(true);
2079
- let resultPubkey = share.proofs[0];
2080
- if (!resultPubkey) {
2081
- throw new ValidationError("Result pubkey is not valid", {
2082
- field: "resultPubkey",
2083
- value: "null",
2084
- expected: "Valid public key bytes"
2085
- });
2086
- }
2087
- for (let i = 1; i < share.proofs.length; i++) {
2088
- const pubkey = share.proofs[i];
2089
- if (!pubkey) {
2090
- throw new ValidationError("Pubkey is not valid", {
2091
- field: "pubkey",
2092
- value: "null",
2093
- expected: "Valid public key bytes"
2094
- });
2095
- }
2096
- const value = share.index ** BigInt(i) % share.fieldModulus;
2097
- const scaledPoint = import_secp256k14.secp256k1.ProjectivePoint.fromHex(pubkey).multiply(value);
2098
- resultPubkey = import_secp256k14.secp256k1.ProjectivePoint.fromHex(resultPubkey).add(scaledPoint).toRawBytes(true);
2099
- }
2100
- if (!(0, import_utils6.equalBytes)(resultPubkey, targetPubkey)) {
2101
- throw new ValidationError("Share is not valid", {
2102
- field: "share",
2103
- value: "Invalid proof",
2104
- expected: "Valid share with matching proofs"
2105
- });
2106
- }
2107
- }
2108
- function bigIntToPrivateKey(value) {
2109
- const hex = value.toString(16).padStart(64, "0");
2110
- const bytes = new Uint8Array(32);
2111
- for (let i = 0; i < 32; i++) {
2112
- bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2113
- }
2114
- return bytes;
2115
- }
2116
-
2117
- // src/utils/signing.ts
2118
- var import_secp256k15 = require("@noble/curves/secp256k1");
2119
- function getRandomSigningNonce() {
2120
- const binding = import_secp256k15.secp256k1.utils.randomPrivateKey();
2121
- const hiding = import_secp256k15.secp256k1.utils.randomPrivateKey();
2122
- return createSigningNonce(binding, hiding);
2123
- }
2124
- function createSigningNonce(binding, hiding) {
2125
- if (binding.length !== 32 || hiding.length !== 32) {
2126
- throw new ValidationError("Invalid nonce length", {
2127
- field: "nonce",
2128
- value: `binding: ${binding.length}, hiding: ${hiding.length}`,
2129
- expected: "Both binding and hiding should be 32 bytes"
2130
- });
2131
- }
2132
- return {
2133
- binding,
2134
- hiding
2135
- };
2136
- }
2137
- function getSigningCommitmentFromNonce(nonce) {
2138
- const bindingPubKey = import_secp256k15.secp256k1.getPublicKey(nonce.binding, true);
2139
- const hidingPubKey = import_secp256k15.secp256k1.getPublicKey(nonce.hiding, true);
2140
- return {
2141
- binding: bindingPubKey,
2142
- hiding: hidingPubKey
2143
- };
2144
- }
2145
- function encodeSigningNonceToBytes(nonce) {
2146
- return new Uint8Array([...nonce.binding, ...nonce.hiding]);
2147
- }
2148
- function decodeBytesToSigningNonce(bytes) {
2149
- if (bytes.length !== 64) {
2150
- throw new ValidationError("Invalid nonce length", {
2151
- field: "bytes",
2152
- value: bytes.length,
2153
- expected: "64 bytes (32 bytes for binding + 32 bytes for hiding)"
2154
- });
2155
- }
2156
- return {
2157
- binding: bytes.slice(32, 64),
2158
- hiding: bytes.slice(0, 32)
2159
- };
2160
- }
2161
- function createSigningCommitment(binding, hiding) {
2162
- if (binding.length !== 33 || hiding.length !== 33) {
2163
- throw new ValidationError("Invalid nonce commitment length", {
2164
- field: "commitment",
2165
- value: `binding: ${binding.length}, hiding: ${hiding.length}`,
2166
- expected: "Both binding and hiding should be 33 bytes (compressed public keys)"
2167
- });
2168
- }
2169
- return {
2170
- binding,
2171
- hiding
2172
- };
2173
- }
2174
- function encodeSigningCommitmentToBytes(commitment) {
2175
- if (commitment.binding.length !== 33 || commitment.hiding.length !== 33) {
2176
- throw new ValidationError("Invalid nonce commitment length", {
2177
- field: "commitment",
2178
- value: `binding: ${commitment.binding.length}, hiding: ${commitment.hiding.length}`,
2179
- expected: "Both binding and hiding should be 33 bytes (compressed public keys)"
2180
- });
2181
- }
2182
- return new Uint8Array([...commitment.binding, ...commitment.hiding]);
2183
- }
2184
- function decodeBytesToSigningCommitment(bytes) {
2185
- if (bytes.length !== 66) {
2186
- throw new ValidationError("Invalid nonce commitment length", {
2187
- field: "bytes",
2188
- value: bytes.length,
2189
- expected: "66 bytes (33 bytes for binding + 33 bytes for hiding)"
2190
- });
2191
- }
2192
- return {
2193
- binding: bytes.slice(33, 66),
2194
- hiding: bytes.slice(0, 33)
2195
- };
2196
- }
2197
-
2198
- // src/utils/token-transactions.ts
2199
- var import_utils7 = require("@noble/curves/abstract/utils");
2200
- function calculateAvailableTokenAmount(outputLeaves) {
2201
- return outputLeaves.reduce(
2202
- (sum, output) => sum + BigInt((0, import_utils7.bytesToNumberBE)(output.output.tokenAmount)),
2203
- BigInt(0)
2204
- );
2205
- }
2206
- function checkIfSelectedOutputsAreAvailable(selectedOutputs, tokenOutputs, tokenPublicKey) {
2207
- const tokenPubKeyHex = (0, import_utils7.bytesToHex)(tokenPublicKey);
2208
- const tokenOutputsAvailable = tokenOutputs.get(tokenPubKeyHex);
2209
- if (!tokenOutputsAvailable) {
2210
- return false;
2211
- }
2212
- if (selectedOutputs.length === 0 || tokenOutputsAvailable.length < selectedOutputs.length) {
2213
- return false;
2214
- }
2215
- const availableOutputIds = new Set(
2216
- tokenOutputsAvailable.map((output) => output.output.id)
2217
- );
2218
- for (const selectedOutput of selectedOutputs) {
2219
- if (!selectedOutput.output?.id || !availableOutputIds.has(selectedOutput.output.id)) {
2220
- return false;
2221
- }
2222
- }
2223
- return true;
2224
- }
2225
- function filterTokenBalanceForTokenPublicKey(tokenBalances, publicKey) {
2226
- if (!tokenBalances) {
2227
- return { balance: 0n };
2228
- }
2229
- const tokenBalance = [...tokenBalances.entries()].find(
2230
- ([, info]) => info.tokenMetadata.tokenPublicKey === publicKey
2231
- );
2232
- if (!tokenBalance) {
2233
- return {
2234
- balance: 0n
2235
- };
2236
- }
2237
- return {
2238
- balance: tokenBalance[1].balance
2239
- };
2240
- }
2241
-
2242
- // src/utils/transfer_package.ts
2243
- var import_utils8 = require("@noble/curves/abstract/utils");
2244
- var import_sha23 = require("@noble/hashes/sha2");
2245
- function getTransferPackageSigningPayload(transferID, transferPackage) {
2246
- const encryptedPayload = transferPackage.keyTweakPackage;
2247
- const pairs = Object.entries(
2248
- encryptedPayload
2249
- ).map(([key, value]) => ({ key, value }));
2250
- pairs.sort((a, b) => a.key.localeCompare(b.key));
2251
- const encoder = new TextEncoder();
2252
- let message = (0, import_utils8.hexToBytes)(transferID.replaceAll("-", ""));
2253
- for (const pair of pairs) {
2254
- const keyPart = encoder.encode(pair.key + ":");
2255
- const separator = encoder.encode(";");
2256
- message = new Uint8Array([
2257
- ...message,
2258
- ...keyPart,
2259
- ...pair.value,
2260
- ...separator
2261
- ]);
2262
- }
2263
- return (0, import_sha23.sha256)(message);
2264
- }
2265
-
2266
- // src/utils/transaction.ts
2267
- var import_btc_signer = require("@scure/btc-signer");
2268
- var TIME_LOCK_INTERVAL = 100;
2269
- var ESTIMATED_TX_SIZE = 191;
2270
- var DEFAULT_SATS_PER_VBYTE = 5;
2271
- var DEFAULT_FEE_SATS = ESTIMATED_TX_SIZE * DEFAULT_SATS_PER_VBYTE;
2272
- function maybeApplyFee(amount) {
2273
- if (amount > BigInt(DEFAULT_FEE_SATS)) {
2274
- return amount - BigInt(DEFAULT_FEE_SATS);
2275
- }
2276
- return amount;
2277
- }
2278
- function createRefundTx(sequence, nodeOutPoint, amountSats, receivingPubkey, network) {
2279
- const newRefundTx = new import_btc_signer.Transaction({
2280
- version: 3,
2281
- allowUnknownOutputs: true
2282
- });
2283
- newRefundTx.addInput({
2284
- ...nodeOutPoint,
2285
- sequence
2286
- });
2287
- const refundPkScript = getP2TRScriptFromPublicKey(receivingPubkey, network);
2288
- newRefundTx.addOutput({
2289
- script: refundPkScript,
2290
- amount: amountSats
2291
- });
2292
- newRefundTx.addOutput(getEphemeralAnchorOutput());
2293
- return newRefundTx;
2294
- }
2295
- function getCurrentTimelock(currSequence) {
2296
- return (currSequence || 0) & 65535;
2297
- }
2298
- function getTransactionSequence(currSequence) {
2299
- const timelock = getCurrentTimelock(currSequence);
2300
- return 1 << 30 | timelock;
2301
- }
2302
- function checkIfValidSequence(currSequence) {
2303
- const TIME_LOCK_ACTIVE = (currSequence || 0) & 2147483648;
2304
- if (TIME_LOCK_ACTIVE !== 0) {
2305
- throw new ValidationError("Timelock not active", {
2306
- field: "currSequence",
2307
- value: currSequence
2308
- });
2309
- }
2310
- const RELATIVE_TIME_LOCK_ACTIVE = (currSequence || 0) & 4194304;
2311
- if (RELATIVE_TIME_LOCK_ACTIVE !== 0) {
2312
- throw new ValidationError("Block based timelock not active", {
2313
- field: "currSequence",
2314
- value: currSequence
2315
- });
2316
- }
2317
- }
2318
- function getNextTransactionSequence(currSequence, forRefresh) {
2319
- const currentTimelock = getCurrentTimelock(currSequence);
2320
- const nextTimelock = currentTimelock - TIME_LOCK_INTERVAL;
2321
- if (forRefresh && nextTimelock <= 100 && currentTimelock > 0) {
2322
- return {
2323
- nextSequence: 1 << 30 | nextTimelock,
2324
- needRefresh: true
2325
- };
2326
- }
2327
- if (nextTimelock < 0) {
2328
- throw new ValidationError("timelock interval is less than 0", {
2329
- field: "nextTimelock",
2330
- value: nextTimelock
2331
- });
2332
- }
2333
- return {
2334
- nextSequence: 1 << 30 | nextTimelock,
2335
- needRefresh: nextTimelock <= 100
2336
- };
2337
- }
2338
- function getEphemeralAnchorOutput() {
2339
- return {
2340
- script: new Uint8Array([81, 2, 78, 115]),
2341
- // Pay-to-anchor (P2A) ephemeral anchor output
2342
- amount: 0n
2343
- };
2344
- }
2345
-
2346
- // src/utils/unilateral-exit.ts
2347
- var import_utils9 = require("@noble/curves/abstract/utils");
2348
- var import_legacy = require("@noble/hashes/legacy");
2349
- var import_sha24 = require("@noble/hashes/sha2");
2350
- var btc3 = __toESM(require("@scure/btc-signer"), 1);
2351
- function isEphemeralAnchorOutput(script, amount) {
2352
- return Boolean(
2353
- amount === 0n && script && // Pattern 1: Bare OP_TRUE (single byte 0x51)
2354
- (script.length === 1 && script[0] === 81 || // Pattern 2: Push OP_TRUE (two bytes 0x01 0x51) - MALFORMED but we detect it
2355
- script.length === 2 && script[0] === 1 && script[1] === 81 || // Pattern 3: Bitcoin v29 ephemeral anchor script (7 bytes: 015152014e0173)
2356
- script.length === 7 && script[0] === 1 && script[1] === 81 && script[2] === 82 && script[3] === 1 && script[4] === 78 && script[5] === 1 && script[6] === 115 || // Pattern 4: Bitcoin ephemeral anchor OP_1 + push 2 bytes (4 bytes: 51024e73)
2357
- script.length === 4 && script[0] === 81 && script[1] === 2 && script[2] === 78 && script[3] === 115)
2358
- );
2359
- }
2360
- async function constructUnilateralExitTxs(nodeHexStrings, sparkClient, network) {
2361
- const result = [];
2362
- const nodes = nodeHexStrings.map((hex) => TreeNode.decode((0, import_utils9.hexToBytes)(hex)));
2363
- const nodeMap = /* @__PURE__ */ new Map();
2364
- for (const node of nodes) {
2365
- nodeMap.set(node.id, node);
2366
- }
2367
- for (const node of nodes) {
2368
- const transactions = [];
2369
- const chain = [];
2370
- let currentNode = node;
2371
- while (currentNode) {
2372
- chain.unshift(currentNode);
2373
- if (currentNode.parentNodeId) {
2374
- let parentNode = nodeMap.get(currentNode.parentNodeId);
2375
- if (!parentNode && sparkClient) {
2376
- try {
2377
- const response = await sparkClient.query_nodes({
2378
- source: {
2379
- $case: "nodeIds",
2380
- nodeIds: {
2381
- nodeIds: [currentNode.parentNodeId]
2382
- }
2383
- },
2384
- includeParents: true,
2385
- network: network || 0
2386
- // Default to mainnet if not provided
2387
- });
2388
- parentNode = response.nodes[currentNode.parentNodeId];
2389
- if (parentNode) {
2390
- nodeMap.set(currentNode.parentNodeId, parentNode);
2391
- }
2392
- } catch (error) {
2393
- console.warn(
2394
- `Failed to query parent node ${currentNode.parentNodeId}: ${error}`
2395
- );
2396
- break;
2397
- }
2398
- }
2399
- if (parentNode) {
2400
- currentNode = parentNode;
2401
- } else {
2402
- if (!sparkClient) {
2403
- console.warn(
2404
- `Parent node ${currentNode.parentNodeId} not found. Provide a sparkClient to fetch missing parents.`
2405
- );
2406
- } else {
2407
- console.warn(
2408
- `Parent node ${currentNode.parentNodeId} not found in database. Chain may be incomplete.`
2409
- );
2410
- }
2411
- break;
2412
- }
2413
- } else {
2414
- break;
2415
- }
2416
- }
2417
- for (const chainNode of chain) {
2418
- const nodeTx = (0, import_utils9.bytesToHex)(chainNode.nodeTx);
2419
- transactions.push(nodeTx);
2420
- if (chainNode.id === node.id) {
2421
- const refundTx = (0, import_utils9.bytesToHex)(chainNode.refundTx);
2422
- transactions.push(refundTx);
2423
- }
2424
- }
2425
- result.push({
2426
- leafId: node.id,
2427
- transactions
2428
- });
2429
- }
2430
- return result;
2431
- }
2432
- async function constructUnilateralExitFeeBumpPackages(nodeHexStrings, utxos, feeRate, electrsUrl, sparkClient, network) {
2433
- const result = [];
2434
- const availableUtxos = [...utxos].sort((a, b) => {
2435
- if (a.value > b.value) return -1;
2436
- if (a.value < b.value) return 1;
2437
- return 0;
2438
- });
2439
- const nodes = [];
2440
- for (let i = 0; i < nodeHexStrings.length; i++) {
2441
- const hex = nodeHexStrings[i];
2442
- try {
2443
- if (!hex || hex.length === 0) {
2444
- throw new Error(`Node hex string at index ${i} is empty`);
2445
- }
2446
- if (hex.startsWith("03000000") || hex.startsWith("02000000") || hex.startsWith("01000000")) {
2447
- throw new Error(
2448
- `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.`
2449
- );
2450
- }
2451
- const nodeBytes = (0, import_utils9.hexToBytes)(hex);
2452
- const node = TreeNode.decode(nodeBytes);
2453
- if (!node.id) {
2454
- throw new Error(
2455
- `Decoded TreeNode at index ${i} is missing required 'id' field`
2456
- );
2457
- }
2458
- if (!node.nodeTx || node.nodeTx.length === 0) {
2459
- throw new Error(
2460
- `Decoded TreeNode at index ${i} is missing required 'nodeTx' field`
2461
- );
2462
- }
2463
- nodes.push(node);
2464
- } catch (decodeError) {
2465
- throw new Error(
2466
- `Failed to decode TreeNode hex string at index ${i}: ${decodeError}. Make sure you're providing TreeNode protobuf hex strings, not raw transaction hex. Use 'leafidtohex' command to get proper hex strings.`
2467
- );
2468
- }
2469
- }
2470
- const nodeMap = /* @__PURE__ */ new Map();
2471
- for (const node of nodes) {
2472
- nodeMap.set(node.id, node);
2473
- }
2474
- const broadcastTxs = /* @__PURE__ */ new Map();
2475
- for (const node of nodes) {
2476
- const txPackages = [];
2477
- let previousFeeBumpTx;
2478
- const chain = [];
2479
- let currentNode = node;
2480
- while (currentNode) {
2481
- chain.unshift(currentNode);
2482
- if (currentNode.parentNodeId) {
2483
- let parentNode = nodeMap.get(currentNode.parentNodeId);
2484
- if (!parentNode && sparkClient) {
2485
- try {
2486
- const response = await sparkClient.query_nodes({
2487
- source: {
2488
- $case: "nodeIds",
2489
- nodeIds: {
2490
- nodeIds: [currentNode.parentNodeId]
2491
- }
2492
- },
2493
- includeParents: true,
2494
- network: network || 0
2495
- // Default to mainnet if not provided
2496
- });
2497
- parentNode = response.nodes[currentNode.parentNodeId];
2498
- if (parentNode) {
2499
- nodeMap.set(currentNode.parentNodeId, parentNode);
2500
- }
2501
- } catch (error) {
2502
- console.warn(
2503
- `Failed to query parent node ${currentNode.parentNodeId}: ${error}`
2504
- );
2505
- break;
2506
- }
2507
- }
2508
- if (parentNode) {
2509
- currentNode = parentNode;
2510
- } else {
2511
- if (!sparkClient) {
2512
- console.warn(
2513
- `Parent node ${currentNode.parentNodeId} not found. Provide a sparkClient to fetch missing parents.`
2514
- );
2515
- } else {
2516
- console.warn(
2517
- `Parent node ${currentNode.parentNodeId} not found in database. Chain may be incomplete.`
2518
- );
2519
- }
2520
- break;
2521
- }
2522
- } else {
2523
- break;
2524
- }
2525
- }
2526
- for (const chainNode of chain) {
2527
- let nodeTxHex = (0, import_utils9.bytesToHex)(chainNode.nodeTx);
2528
- try {
2529
- const txObj = getTxFromRawTxHex(nodeTxHex);
2530
- const txid = getTxId(txObj);
2531
- if (broadcastTxs.get(txid)) {
2532
- continue;
2533
- }
2534
- broadcastTxs.set(txid, true);
2535
- const isBroadcast = await isTxBroadcast(txid, electrsUrl, network);
2536
- if (isBroadcast) {
2537
- continue;
2538
- } else {
2539
- }
2540
- let anchorOutputScriptHex;
2541
- for (let i = txObj.outputsLength - 1; i >= 0; i--) {
2542
- const output = txObj.getOutput(i);
2543
- if (output?.amount === 0n && output.script) {
2544
- anchorOutputScriptHex = (0, import_utils9.bytesToHex)(output.script);
2545
- break;
2546
- }
2547
- }
2548
- } catch (parseError) {
2549
- console.error(
2550
- `\u274C Error parsing nodeTx for anchor check (node ${chainNode.id}): ${parseError}`
2551
- );
2552
- console.log(
2553
- ` This may indicate a corrupted transaction in the TreeNode.`
2554
- );
2555
- console.log(` Transaction hex: ${nodeTxHex}`);
2556
- console.log(
2557
- ` Attempting to continue with original hex, but fee bump may fail.`
2558
- );
2559
- }
2560
- const {
2561
- feeBumpPsbt: nodeFeeBumpPsbt,
2562
- usedUtxos,
2563
- correctedParentTx
2564
- } = constructFeeBumpTx(nodeTxHex, availableUtxos, feeRate, void 0);
2565
- const feeBumpTx = btc3.Transaction.fromPSBT((0, import_utils9.hexToBytes)(nodeFeeBumpPsbt));
2566
- var feeBumpOut = feeBumpTx.outputsLength === 1 ? feeBumpTx.getOutput(0) : null;
2567
- var feeBumpOutPubKey = null;
2568
- for (const usedUtxo of usedUtxos) {
2569
- if (feeBumpOut && (0, import_utils9.bytesToHex)(feeBumpOut.script) == usedUtxo.script) {
2570
- feeBumpOutPubKey = usedUtxo.publicKey;
2571
- }
2572
- const index = availableUtxos.findIndex(
2573
- (u) => u.txid === usedUtxo.txid && u.vout === usedUtxo.vout
2574
- );
2575
- if (index !== -1) {
2576
- availableUtxos.splice(index, 1);
2577
- }
2578
- }
2579
- if (feeBumpOut)
2580
- availableUtxos.unshift({
2581
- txid: getTxId(feeBumpTx),
2582
- vout: 0,
2583
- value: feeBumpOut.amount,
2584
- script: (0, import_utils9.bytesToHex)(feeBumpOut.script),
2585
- publicKey: feeBumpOutPubKey
2586
- });
2587
- const finalNodeTx = correctedParentTx || nodeTxHex;
2588
- txPackages.push({ tx: finalNodeTx, feeBumpPsbt: nodeFeeBumpPsbt });
2589
- if (chainNode.id === node.id) {
2590
- let refundTxHex = (0, import_utils9.bytesToHex)(chainNode.refundTx);
2591
- try {
2592
- const txObj = getTxFromRawTxHex(refundTxHex);
2593
- let anchorOutputScriptHex;
2594
- for (let i = txObj.outputsLength - 1; i >= 0; i--) {
2595
- const output = txObj.getOutput(i);
2596
- if (output?.amount === 0n && output.script) {
2597
- anchorOutputScriptHex = (0, import_utils9.bytesToHex)(output.script);
2598
- break;
2599
- }
2600
- }
2601
- } catch (parseError) {
2602
- console.error(
2603
- `\u274C Error parsing refundTx for anchor check (node ${chainNode.id}): ${parseError}`
2604
- );
2605
- console.log(
2606
- ` This may indicate a corrupted refund transaction in the TreeNode.`
2607
- );
2608
- console.log(` Refund transaction hex: ${refundTxHex}`);
2609
- console.log(
2610
- ` Attempting to continue with original refund hex, but this transaction may be invalid.`
2611
- );
2612
- }
2613
- const refundFeeBump = constructFeeBumpTx(
2614
- refundTxHex,
2615
- availableUtxos,
2616
- feeRate,
2617
- void 0
2618
- );
2619
- txPackages.push({
2620
- tx: refundTxHex,
2621
- feeBumpPsbt: refundFeeBump.feeBumpPsbt
2622
- });
2623
- }
2624
- }
2625
- result.push({
2626
- leafId: node.id,
2627
- txPackages
2628
- });
2629
- }
2630
- return result;
2631
- }
2632
- function hash160(data) {
2633
- const sha256Hash = (0, import_sha24.sha256)(data);
2634
- return (0, import_legacy.ripemd160)(sha256Hash);
2635
- }
2636
- function constructFeeBumpTx(txHex, utxos, feeRate, previousFeeBumpTx) {
2637
- if (!txHex || txHex.length === 0) {
2638
- throw new Error("Transaction hex string is empty or undefined");
2639
- }
2640
- if (utxos.length === 0) {
2641
- throw new Error("No UTXOs available for fee bump");
2642
- }
2643
- let correctedTxHex = txHex;
2644
- let parentTx;
2645
- try {
2646
- parentTx = getTxFromRawTxHex(correctedTxHex);
2647
- if (!parentTx) {
2648
- throw new Error("getTxFromRawTxHex returned null/undefined");
2649
- }
2650
- } catch (parseError) {
2651
- throw new Error(
2652
- `Failed to parse parent transaction hex: ${parseError}. Transaction hex: ${correctedTxHex}`
2653
- );
2654
- }
2655
- try {
2656
- const outputsLength = parentTx.outputsLength;
2657
- const inputsLength = parentTx.inputsLength;
2658
- if (typeof outputsLength !== "number" || outputsLength < 0) {
2659
- throw new Error(
2660
- "Invalid transaction: outputsLength is not a valid number"
2661
- );
2662
- }
2663
- if (typeof inputsLength !== "number" || inputsLength < 0) {
2664
- throw new Error(
2665
- "Invalid transaction: inputsLength is not a valid number"
2666
- );
2667
- }
2668
- } catch (validationError) {
2669
- throw new Error(
2670
- `Transaction validation failed: ${validationError}. This may indicate a corrupted or malformed transaction.`
2671
- );
2672
- }
2673
- const parentTxIdFromLib = parentTx.id;
2674
- let ephemeralAnchorIndex = -1;
2675
- for (let i = 0; i < parentTx.outputsLength; i++) {
2676
- const output = parentTx.getOutput(i);
2677
- const isEphemeralAnchor = isEphemeralAnchorOutput(
2678
- output?.script,
2679
- output?.amount
2680
- );
2681
- if (isEphemeralAnchor) {
2682
- ephemeralAnchorIndex = i;
2683
- break;
2684
- }
2685
- }
2686
- if (ephemeralAnchorIndex === -1) {
2687
- throw new Error(
2688
- "No ephemeral anchor output found in parent transaction. Expected a 0-value output with OP_TRUE script (0x51), malformed OP_TRUE (0x0151), Bitcoin v29 ephemeral anchor script (015152014e0173), or Bitcoin OP_1 + push 2 bytes script (51024e73)."
2689
- );
2690
- }
2691
- const ephemeralAnchorOutput = parentTx.getOutput(ephemeralAnchorIndex);
2692
- if (!ephemeralAnchorOutput)
2693
- throw new Error("No ephemeral anchor output found");
2694
- if (!ephemeralAnchorOutput.script)
2695
- throw new Error("No script found in ephemeral anchor output");
2696
- if (utxos.length === 0) {
2697
- throw new Error("No UTXOs available for fee bump");
2698
- }
2699
- const builder = new btc3.Transaction({
2700
- version: 3,
2701
- allowUnknown: true,
2702
- allowLegacyWitnessUtxo: true
2703
- });
2704
- let totalValue = 0n;
2705
- const processedUtxos = [];
2706
- for (let i = 0; i < utxos.length; i++) {
2707
- const fundingUtxo = utxos[i];
2708
- if (!fundingUtxo) {
2709
- throw new Error(`UTXO at index ${i} is undefined`);
2710
- }
2711
- const pubKeyHash = hash160((0, import_utils9.hexToBytes)(fundingUtxo.publicKey));
2712
- const scriptToUse = new Uint8Array([0, 20, ...pubKeyHash]);
2713
- const providedScript = (0, import_utils9.hexToBytes)(fundingUtxo.script);
2714
- if ((0, import_utils9.bytesToHex)(scriptToUse) !== (0, import_utils9.bytesToHex)(providedScript)) {
2715
- throw new Error(
2716
- `\u274C Derived script doesn't match provided script for UTXO ${i + 1}.`
2717
- );
2718
- }
2719
- builder.addInput({
2720
- txid: fundingUtxo.txid,
2721
- index: fundingUtxo.vout,
2722
- sequence: 4294967295,
2723
- witnessUtxo: {
2724
- script: scriptToUse,
2725
- // Always P2WPKH
2726
- amount: fundingUtxo.value
2727
- }
2728
- });
2729
- totalValue += fundingUtxo.value;
2730
- processedUtxos.push({
2731
- utxo: fundingUtxo,
2732
- p2wpkhScript: scriptToUse
2733
- });
2734
- }
2735
- builder.addInput({
2736
- txid: parentTxIdFromLib,
2737
- index: ephemeralAnchorIndex,
2738
- sequence: 4294967295,
2739
- witnessUtxo: {
2740
- script: ephemeralAnchorOutput.script,
2741
- // Use the original script directly (not P2WSH wrapped)
2742
- amount: 0n
2743
- }
2744
- });
2745
- const fee = 1500n;
2746
- const remainingValue = totalValue - fee;
2747
- if (remainingValue <= 0n) {
2748
- throw new Error(
2749
- `Insufficient funds for fee bump. Required fee: ${fee} sats, Available: ${totalValue} sats`
2750
- );
2751
- }
2752
- if (processedUtxos.length === 0) {
2753
- throw new Error("No processed UTXOs available for change output");
2754
- }
2755
- const firstProcessedUtxo = processedUtxos[0];
2756
- if (!firstProcessedUtxo) {
2757
- throw new Error("First processed UTXO is undefined");
2758
- }
2759
- builder.addOutput({
2760
- script: firstProcessedUtxo.p2wpkhScript,
2761
- amount: remainingValue
2762
- });
2763
- for (let i = 0; i < processedUtxos.length; i++) {
2764
- const processed = processedUtxos[i];
2765
- if (!processed) {
2766
- throw new Error(`Processed UTXO at index ${i} is undefined`);
2767
- }
2768
- try {
2769
- builder.updateInput(i, {
2770
- witnessScript: processed.p2wpkhScript
2771
- });
2772
- builder.signIdx;
2773
- } catch (error) {
2774
- throw new Error(`Failed to handle funding UTXO input ${i + 1}: ${error}`);
2775
- }
2776
- }
2777
- let psbtHex;
2778
- try {
2779
- psbtHex = (0, import_utils9.bytesToHex)(builder.toPSBT());
2780
- } catch (error) {
2781
- throw new Error(`Failed to extract transaction: ${error}`);
2782
- }
2783
- return {
2784
- feeBumpPsbt: psbtHex,
2785
- usedUtxos: utxos,
2786
- correctedParentTx: correctedTxHex !== txHex ? correctedTxHex : void 0
2787
- };
2788
- }
2789
-
2790
- // src/address/address.ts
2791
- var import_secp256k16 = require("@noble/curves/secp256k1");
2792
- var import_utils10 = require("@noble/hashes/utils");
2793
- var import_base2 = require("@scure/base");
2794
- var import_uuidv7 = require("uuidv7");
2795
- var import_utils11 = require("@noble/curves/abstract/utils");
2796
- var AddressNetwork = {
2797
- MAINNET: "sp",
2798
- TESTNET: "spt",
2799
- REGTEST: "sprt",
2800
- SIGNET: "sps",
2801
- LOCAL: "spl"
2802
- };
2803
- function encodeSparkAddress(payload) {
2804
- try {
2805
- isValidPublicKey(payload.identityPublicKey);
2806
- let paymentIntentFields;
2807
- if (payload.paymentIntentFields) {
2808
- paymentIntentFields = payload.paymentIntentFields;
2809
- }
2810
- const sparkAddressProto = SparkAddress.create({
2811
- identityPublicKey: (0, import_utils10.hexToBytes)(payload.identityPublicKey),
2812
- paymentIntentFields
2813
- });
2814
- const serializedPayload = SparkAddress.encode(sparkAddressProto).finish();
2815
- const words = import_base2.bech32m.toWords(serializedPayload);
2816
- return import_base2.bech32m.encode(
2817
- AddressNetwork[payload.network],
2818
- words,
2819
- 500
2820
- );
2821
- } catch (error) {
2822
- throw new ValidationError(
2823
- "Failed to encode Spark address",
2824
- {
2825
- field: "publicKey",
2826
- value: payload.identityPublicKey
2827
- },
2828
- error
2829
- );
2830
- }
2831
- }
2832
- function isValidPublicKey(publicKey) {
2833
- try {
2834
- const point = import_secp256k16.secp256k1.ProjectivePoint.fromHex(publicKey);
2835
- point.assertValidity();
2836
- } catch (error) {
2837
- throw new ValidationError(
2838
- "Invalid public key",
2839
- {
2840
- field: "publicKey",
2841
- value: publicKey
2842
- },
2843
- error
2844
- );
2845
- }
2846
- }
2847
-
2848
- // src/utils/xchain-address.ts
2849
- var btc4 = __toESM(require("@scure/btc-signer"), 1);
2850
- var networkByType = {
2851
- MAINNET: btc4.NETWORK,
2852
- TESTNET: btc4.TEST_NETWORK,
2853
- REGTEST: {
2854
- ...btc4.TEST_NETWORK,
2855
- bech32: "bcrt"
2856
- }
2857
- };
2858
- function getSparkAddressFromTaproot(taprootAddress) {
2859
- for (const networkType of ["MAINNET", "TESTNET", "REGTEST"]) {
2860
- try {
2861
- const result = btc4.Address(networkByType[networkType]).decode(taprootAddress);
2862
- if (result.type === "tr") {
2863
- const outputPublicKey = result.pubkey;
2864
- return encodeSparkAddress({
2865
- identityPublicKey: import_buffer.Buffer.concat([
2866
- import_buffer.Buffer.from([2]),
2867
- outputPublicKey
2868
- ]).toString("hex"),
2869
- network: networkType
2870
- });
2871
- }
2872
- } catch (_) {
2873
- }
2874
- }
2875
- throw new ValidationError("Invalid taproot address");
2876
- }
2877
- // Annotate the CommonJS export names for ESM import in node:
2878
- 0 && (module.exports = {
2879
- DEFAULT_FEE_SATS,
2880
- LRC_WALLET_NETWORK,
2881
- LRC_WALLET_NETWORK_TYPE,
2882
- Network,
2883
- NetworkToProto,
2884
- addPrivateKeys,
2885
- addPublicKeys,
2886
- applyAdaptorToSignature,
2887
- applyAdditiveTweakToPublicKey,
2888
- bigIntToPrivateKey,
2889
- calculateAvailableTokenAmount,
2890
- checkIfSelectedOutputsAreAvailable,
2891
- checkIfValidSequence,
2892
- collectResponses,
2893
- computeTaprootKeyNoScript,
2894
- computerLagrangeCoefficients,
2895
- constructFeeBumpTx,
2896
- constructUnilateralExitFeeBumpPackages,
2897
- constructUnilateralExitTxs,
2898
- createRefundTx,
2899
- createSigningCommitment,
2900
- createSigningNonce,
2901
- decodeBytesToSigningCommitment,
2902
- decodeBytesToSigningNonce,
2903
- encodeSigningCommitmentToBytes,
2904
- encodeSigningNonceToBytes,
2905
- evaluatePolynomial,
2906
- fieldDiv,
2907
- filterTokenBalanceForTokenPublicKey,
2908
- generateAdaptorFromSignature,
2909
- generatePolynomialForSecretSharing,
2910
- generateSignatureFromExistingAdaptor,
2911
- getCurrentTimelock,
2912
- getEphemeralAnchorOutput,
2913
- getLatestDepositTxId,
2914
- getNetwork,
2915
- getNetworkFromAddress,
2916
- getNetworkFromString,
2917
- getNextTransactionSequence,
2918
- getP2TRAddressFromPkScript,
2919
- getP2TRAddressFromPublicKey,
2920
- getP2TRScriptFromPublicKey,
2921
- getP2WPKHAddressFromPublicKey,
2922
- getRandomBigInt,
2923
- getRandomSigningNonce,
2924
- getSigHashFromTx,
2925
- getSigningCommitmentFromNonce,
2926
- getSparkAddressFromTaproot,
2927
- getTransactionSequence,
2928
- getTransferPackageSigningPayload,
2929
- getTxFromRawTxBytes,
2930
- getTxFromRawTxHex,
2931
- getTxId,
2932
- getTxIdNoReverse,
2933
- isEphemeralAnchorOutput,
2934
- isTxBroadcast,
2935
- lastKeyWithTarget,
2936
- maybeApplyFee,
2937
- modInverse,
2938
- proofOfPossessionMessageHashForDepositAddress,
2939
- recoverSecret,
2940
- splitSecret,
2941
- splitSecretWithProofs,
2942
- subtractPrivateKeys,
2943
- subtractPublicKeys,
2944
- sumOfPrivateKeys,
2945
- validateOutboundAdaptorSignature,
2946
- validateShare
2947
- });