@velumdotcash/sdk 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -0
  3. package/dist/__tests__/paylink.test.d.ts +9 -0
  4. package/dist/__tests__/paylink.test.js +254 -0
  5. package/dist/config.d.ts +9 -0
  6. package/dist/config.js +12 -0
  7. package/dist/deposit.d.ts +22 -0
  8. package/dist/deposit.js +445 -0
  9. package/dist/depositSPL.d.ts +24 -0
  10. package/dist/depositSPL.js +499 -0
  11. package/dist/errors.d.ts +78 -0
  12. package/dist/errors.js +127 -0
  13. package/dist/exportUtils.d.ts +10 -0
  14. package/dist/exportUtils.js +10 -0
  15. package/dist/getUtxos.d.ts +30 -0
  16. package/dist/getUtxos.js +335 -0
  17. package/dist/getUtxosSPL.d.ts +34 -0
  18. package/dist/getUtxosSPL.js +442 -0
  19. package/dist/index.d.ts +183 -0
  20. package/dist/index.js +436 -0
  21. package/dist/models/keypair.d.ts +26 -0
  22. package/dist/models/keypair.js +43 -0
  23. package/dist/models/utxo.d.ts +51 -0
  24. package/dist/models/utxo.js +99 -0
  25. package/dist/test_paylink_logic.test.d.ts +1 -0
  26. package/dist/test_paylink_logic.test.js +114 -0
  27. package/dist/utils/address_lookup_table.d.ts +9 -0
  28. package/dist/utils/address_lookup_table.js +45 -0
  29. package/dist/utils/constants.d.ts +27 -0
  30. package/dist/utils/constants.js +56 -0
  31. package/dist/utils/debug-logger.d.ts +250 -0
  32. package/dist/utils/debug-logger.js +688 -0
  33. package/dist/utils/encryption.d.ts +152 -0
  34. package/dist/utils/encryption.js +700 -0
  35. package/dist/utils/logger.d.ts +9 -0
  36. package/dist/utils/logger.js +35 -0
  37. package/dist/utils/merkle_tree.d.ts +92 -0
  38. package/dist/utils/merkle_tree.js +186 -0
  39. package/dist/utils/node-shim.d.ts +14 -0
  40. package/dist/utils/node-shim.js +21 -0
  41. package/dist/utils/prover.d.ts +36 -0
  42. package/dist/utils/prover.js +169 -0
  43. package/dist/utils/utils.d.ts +64 -0
  44. package/dist/utils/utils.js +165 -0
  45. package/dist/withdraw.d.ts +22 -0
  46. package/dist/withdraw.js +290 -0
  47. package/dist/withdrawSPL.d.ts +24 -0
  48. package/dist/withdrawSPL.js +329 -0
  49. package/package.json +59 -0
@@ -0,0 +1,445 @@
1
+ import { PublicKey, TransactionInstruction, SystemProgram, ComputeBudgetProgram, VersionedTransaction, TransactionMessage, LAMPORTS_PER_SOL, } from "@solana/web3.js";
2
+ import BN from "bn.js";
3
+ import { Utxo } from "./models/utxo.js";
4
+ import { fetchMerkleProof, findNullifierPDAs, getExtDataHash, getProgramAccounts, queryRemoteTreeState, findCrossCheckNullifierPDAs, } from "./utils/utils.js";
5
+ import { prove, parseProofToBytesArray, parseToBytesArray, } from "./utils/prover.js";
6
+ import { MerkleTree } from "./utils/merkle_tree.js";
7
+ import { InsufficientBalanceError, DepositLimitError, TransactionTimeoutError, } from "./errors.js";
8
+ import { serializeProofAndExtData, } from "./utils/encryption.js";
9
+ import { Keypair as UtxoKeypair } from "./models/keypair.js";
10
+ import { getUtxos } from "./getUtxos.js";
11
+ import { FIELD_SIZE, FEE_RECIPIENT, MERKLE_TREE_DEPTH, RELAYER_API_URL, PROGRAM_ID, ALT_ADDRESS, } from "./utils/constants.js";
12
+ import { useExistingALT } from "./utils/address_lookup_table.js";
13
+ import { logger } from "./utils/logger.js";
14
+ // Function to relay pre-signed deposit transaction to indexer backend
15
+ async function relayDepositToIndexer(signedTransaction, publicKey, referrer) {
16
+ try {
17
+ logger.debug("Relaying pre-signed deposit transaction to indexer backend...");
18
+ const params = {
19
+ signedTransaction,
20
+ senderAddress: publicKey.toString(),
21
+ };
22
+ if (referrer) {
23
+ params.referralWalletAddress = referrer;
24
+ }
25
+ const response = await fetch(`${RELAYER_API_URL}/deposit`, {
26
+ method: "POST",
27
+ headers: {
28
+ "Content-Type": "application/json",
29
+ },
30
+ body: JSON.stringify(params),
31
+ });
32
+ if (!response.ok) {
33
+ logger.error("res text:", await response.text());
34
+ throw new Error("response not ok");
35
+ // const errorData = await response.json() as { error?: string };
36
+ // throw new Error(`Deposit relay failed: ${response.status} ${response.statusText} - ${errorData.error || 'Unknown error'}`);
37
+ }
38
+ const result = (await response.json());
39
+ logger.debug("Pre-signed deposit transaction relayed successfully!");
40
+ logger.debug("Response:", result);
41
+ return result.signature;
42
+ }
43
+ catch (error) {
44
+ console.error("Failed to relay deposit transaction to indexer:", error);
45
+ throw error;
46
+ }
47
+ }
48
+ export async function deposit({ lightWasm, storage, keyBasePath, publicKey, connection, amount_in_lamports, encryptionService, transactionSigner, referrer, signer, recipientUtxoPublicKey, recipientEncryptionKey, }) {
49
+ // check limit
50
+ let limitAmount = await checkDepositLimit(connection);
51
+ if (limitAmount && amount_in_lamports > limitAmount * LAMPORTS_PER_SOL) {
52
+ throw new DepositLimitError(limitAmount * LAMPORTS_PER_SOL, amount_in_lamports);
53
+ }
54
+ if (!signer) {
55
+ signer = publicKey;
56
+ }
57
+ // const amount_in_lamports = amount_in_sol * LAMPORTS_PER_SOL
58
+ const fee_amount_in_lamports = 0;
59
+ logger.debug("Encryption key generated from user keypair");
60
+ logger.debug(`User wallet: ${signer.toString()}`);
61
+ logger.debug(`Deposit amount: ${amount_in_lamports} lamports (${amount_in_lamports / LAMPORTS_PER_SOL} SOL)`);
62
+ logger.debug(`Calculated fee: ${fee_amount_in_lamports} lamports (${fee_amount_in_lamports / LAMPORTS_PER_SOL} SOL)`);
63
+ // Check wallet balance
64
+ const balance = await connection.getBalance(signer);
65
+ logger.debug(`Wallet balance: ${balance / 1e9} SOL`);
66
+ if (balance < amount_in_lamports + fee_amount_in_lamports) {
67
+ throw new InsufficientBalanceError(amount_in_lamports + fee_amount_in_lamports, balance);
68
+ }
69
+ const { treeAccount, treeTokenAccount, globalConfigAccount } = getProgramAccounts();
70
+ // Create the merkle tree with the pre-initialized poseidon hash
71
+ const tree = new MerkleTree(MERKLE_TREE_DEPTH, lightWasm);
72
+ // Initialize root and nextIndex variables
73
+ const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState();
74
+ logger.debug(`Using tree root: ${root}`);
75
+ logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
76
+ // Generate a deterministic private key derived from the wallet keypair
77
+ // const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
78
+ const utxoPrivateKey = encryptionService.getUtxoPrivateKeyV2();
79
+ // Create a UTXO keypair that will be used for all inputs and outputs (unless recipient is specified)
80
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
81
+ logger.debug("Using wallet-derived UTXO keypair for deposit");
82
+ // Fetch existing UTXOs for this user (SKIP if third-party deposit)
83
+ let existingUnspentUtxos = [];
84
+ if (!recipientUtxoPublicKey) {
85
+ logger.debug("\nFetching existing UTXOs...");
86
+ existingUnspentUtxos = await getUtxos({
87
+ connection,
88
+ publicKey,
89
+ encryptionService,
90
+ storage,
91
+ });
92
+ }
93
+ else {
94
+ logger.debug("\nThird-party deposit detected. Skipping UTXO fetch (Fresh Deposit forced).");
95
+ }
96
+ // Calculate output amounts and external amount based on scenario
97
+ let extAmount;
98
+ let outputAmount;
99
+ // Create inputs based on whether we have existing UTXOs
100
+ let inputs;
101
+ let inputMerklePathIndices;
102
+ let inputMerklePathElements;
103
+ if (existingUnspentUtxos.length === 0) {
104
+ // Scenario 1: Fresh deposit with dummy inputs - add new funds to the system
105
+ extAmount = amount_in_lamports;
106
+ outputAmount = new BN(amount_in_lamports)
107
+ .sub(new BN(fee_amount_in_lamports))
108
+ .toString();
109
+ logger.debug(`Fresh deposit scenario (no existing UTXOs):`);
110
+ logger.debug(`External amount (deposit): ${extAmount}`);
111
+ logger.debug(`Fee amount: ${fee_amount_in_lamports}`);
112
+ logger.debug(`Output amount: ${outputAmount}`);
113
+ // Use two dummy UTXOs as inputs
114
+ inputs = [
115
+ new Utxo({
116
+ lightWasm,
117
+ keypair: utxoKeypair,
118
+ }),
119
+ new Utxo({
120
+ lightWasm,
121
+ keypair: utxoKeypair,
122
+ }),
123
+ ];
124
+ // Both inputs are dummy, so use mock indices and zero-filled Merkle paths
125
+ inputMerklePathIndices = inputs.map((input) => input.index || 0);
126
+ inputMerklePathElements = inputs.map(() => {
127
+ return [...new Array(tree.levels).fill("0")];
128
+ });
129
+ }
130
+ else {
131
+ // Scenario 2: Deposit that consolidates with existing UTXO(s)
132
+ const firstUtxo = existingUnspentUtxos[0];
133
+ const firstUtxoAmount = firstUtxo.amount;
134
+ const secondUtxoAmount = existingUnspentUtxos.length > 1
135
+ ? existingUnspentUtxos[1].amount
136
+ : new BN(0);
137
+ extAmount = amount_in_lamports; // Still depositing new funds
138
+ // Output combines existing UTXO amounts + new deposit amount - fee
139
+ outputAmount = firstUtxoAmount
140
+ .add(secondUtxoAmount)
141
+ .add(new BN(amount_in_lamports))
142
+ .sub(new BN(fee_amount_in_lamports))
143
+ .toString();
144
+ logger.debug(`Deposit with consolidation scenario:`);
145
+ logger.debug(`First existing UTXO amount: ${firstUtxoAmount.toString()}`);
146
+ if (secondUtxoAmount.gt(new BN(0))) {
147
+ logger.debug(`Second existing UTXO amount: ${secondUtxoAmount.toString()}`);
148
+ }
149
+ logger.debug(`New deposit amount: ${amount_in_lamports}`);
150
+ logger.debug(`Fee amount: ${fee_amount_in_lamports}`);
151
+ logger.debug(`Output amount (existing UTXOs + deposit - fee): ${outputAmount}`);
152
+ logger.debug(`External amount (deposit): ${extAmount}`);
153
+ logger.debug("\nFirst UTXO to be consolidated:");
154
+ await firstUtxo.log();
155
+ // Use first existing UTXO as first input, and either second UTXO or dummy UTXO as second input
156
+ const secondUtxo = existingUnspentUtxos.length > 1
157
+ ? existingUnspentUtxos[1]
158
+ : new Utxo({
159
+ lightWasm,
160
+ keypair: utxoKeypair,
161
+ amount: "0",
162
+ });
163
+ inputs = [
164
+ firstUtxo, // Use the first existing UTXO
165
+ secondUtxo, // Use second UTXO if available, otherwise dummy
166
+ ];
167
+ // Fetch Merkle proofs for real UTXOs
168
+ const firstUtxoCommitment = await firstUtxo.getCommitment();
169
+ const firstUtxoMerkleProof = await fetchMerkleProof(firstUtxoCommitment);
170
+ let secondUtxoMerkleProof;
171
+ if (secondUtxo.amount.gt(new BN(0))) {
172
+ // Second UTXO is real, fetch its proof
173
+ const secondUtxoCommitment = await secondUtxo.getCommitment();
174
+ secondUtxoMerkleProof = await fetchMerkleProof(secondUtxoCommitment);
175
+ logger.debug("\nSecond UTXO to be consolidated:");
176
+ await secondUtxo.log();
177
+ }
178
+ // Use the real pathIndices from API for real inputs, mock index for dummy input
179
+ inputMerklePathIndices = [
180
+ firstUtxo.index || 0, // Use the real UTXO's index
181
+ secondUtxo.amount.gt(new BN(0)) ? secondUtxo.index || 0 : 0, // Real UTXO index or dummy
182
+ ];
183
+ // Create Merkle path elements: real proof for real inputs, zeros for dummy input
184
+ inputMerklePathElements = [
185
+ firstUtxoMerkleProof.pathElements, // Real Merkle proof for first existing UTXO
186
+ secondUtxo.amount.gt(new BN(0))
187
+ ? secondUtxoMerkleProof.pathElements
188
+ : [...new Array(tree.levels).fill("0")], // Real proof or zero-filled for dummy
189
+ ];
190
+ logger.debug(`Using first UTXO with amount: ${firstUtxo.amount.toString()} and index: ${firstUtxo.index}`);
191
+ logger.debug(`Using second ${secondUtxo.amount.gt(new BN(0)) ? "UTXO" : "dummy UTXO"} with amount: ${secondUtxo.amount.toString()}${secondUtxo.amount.gt(new BN(0)) ? ` and index: ${secondUtxo.index}` : ""}`);
192
+ logger.debug(`First UTXO Merkle proof path indices from API: [${firstUtxoMerkleProof.pathIndices.join(", ")}]`);
193
+ if (secondUtxo.amount.gt(new BN(0))) {
194
+ logger.debug(`Second UTXO Merkle proof path indices from API: [${secondUtxoMerkleProof.pathIndices.join(", ")}]`);
195
+ }
196
+ }
197
+ const publicAmountForCircuit = new BN(extAmount)
198
+ .sub(new BN(fee_amount_in_lamports))
199
+ .add(FIELD_SIZE)
200
+ .mod(FIELD_SIZE);
201
+ logger.debug(`Public amount calculation: (${extAmount} - ${fee_amount_in_lamports} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
202
+ // Create outputs for the transaction
203
+ // If recipient is specified, the first output goes to them.
204
+ // Otherwise, it goes to the sender (utxoKeypair).
205
+ let output1Config = {
206
+ lightWasm,
207
+ amount: outputAmount,
208
+ index: currentNextIndex,
209
+ };
210
+ if (recipientUtxoPublicKey) {
211
+ // Third-party deposit: Use Recipient's Public Key
212
+ output1Config.publicKey = recipientUtxoPublicKey;
213
+ }
214
+ else {
215
+ // Self-deposit: Use Sender's Keypair
216
+ output1Config.keypair = utxoKeypair;
217
+ }
218
+ const outputs = [
219
+ new Utxo(output1Config), // Output with value
220
+ new Utxo({
221
+ lightWasm,
222
+ amount: "0",
223
+ keypair: utxoKeypair, // Dummy/Change always to sender/signer for now
224
+ index: currentNextIndex + 1,
225
+ }), // Empty UTXO
226
+ ];
227
+ // Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
228
+ const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
229
+ const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
230
+ logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
231
+ // Convert to circuit-compatible format
232
+ const publicAmountCircuitResult = sumIns
233
+ .add(publicAmountForCircuit)
234
+ .mod(FIELD_SIZE);
235
+ logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
236
+ logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
237
+ logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
238
+ // Generate nullifiers and commitments
239
+ const inputNullifiers = await Promise.all(inputs.map((x) => x.getNullifier()));
240
+ const outputCommitments = await Promise.all(outputs.map((x) => x.getCommitment()));
241
+ // Save original commitment and nullifier values for verification
242
+ logger.debug("\n=== UTXO VALIDATION ===");
243
+ logger.debug("Output 0 Commitment:", outputCommitments[0]);
244
+ logger.debug("Output 1 Commitment:", outputCommitments[1]);
245
+ // Encrypt the UTXO data using a compact format that includes the keypair
246
+ logger.debug("\nEncrypting UTXOs...");
247
+ let encryptedOutput1;
248
+ if (recipientEncryptionKey) {
249
+ logger.debug("Encrypting Output 1 for Recipient (Asymmetric)...");
250
+ encryptedOutput1 = encryptionService.encryptUtxo(outputs[0], recipientEncryptionKey);
251
+ }
252
+ else {
253
+ encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
254
+ }
255
+ const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
256
+ logger.debug(`\nOutput[0] (with value):`);
257
+ await outputs[0].log();
258
+ logger.debug(`\nOutput[1] (empty):`);
259
+ await outputs[1].log();
260
+ logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
261
+ logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
262
+ logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
263
+ // Test decryption ONLY if we have the key (Self-Deposit)
264
+ if (!recipientEncryptionKey) {
265
+ logger.debug("\n=== TESTING DECRYPTION ===");
266
+ logger.debug("Decrypting output 1 to verify commitment matches...");
267
+ const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
268
+ if (decryptedUtxo1) {
269
+ const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
270
+ logger.debug("Original commitment:", outputCommitments[0]);
271
+ logger.debug("Decrypted commitment:", decryptedCommitment1);
272
+ logger.debug("Commitment matches:", outputCommitments[0] === decryptedCommitment1);
273
+ }
274
+ }
275
+ // Create the deposit ExtData with real encrypted outputs
276
+ const extData = {
277
+ // recipient - just a placeholder, not actually used for deposits.
278
+ recipient: new PublicKey("AWexibGxNFKTa1b5R5MN4PJr9HWnWRwf8EW9g8cLx3dM"),
279
+ extAmount: new BN(extAmount),
280
+ encryptedOutput1: encryptedOutput1,
281
+ encryptedOutput2: encryptedOutput2,
282
+ fee: new BN(fee_amount_in_lamports),
283
+ feeRecipient: FEE_RECIPIENT,
284
+ mintAddress: inputs[0].mintAddress,
285
+ };
286
+ // Calculate the extDataHash with the encrypted outputs (now includes mintAddress for security)
287
+ const calculatedExtDataHash = getExtDataHash(extData);
288
+ // Create the input for the proof generation (must match circuit input order exactly)
289
+ const input = {
290
+ // Common transaction data
291
+ root: root,
292
+ inputNullifier: inputNullifiers, // Use resolved values instead of Promise objects
293
+ outputCommitment: outputCommitments, // Use resolved values instead of Promise objects
294
+ publicAmount: publicAmountForCircuit.toString(), // Use proper field arithmetic result
295
+ extDataHash: calculatedExtDataHash,
296
+ // Input UTXO data (UTXOs being spent) - ensure all values are in decimal format
297
+ inAmount: inputs.map((x) => x.amount.toString(10)),
298
+ inPrivateKey: inputs.map((x) => x.keypair.privkey),
299
+ inBlinding: inputs.map((x) => x.blinding.toString(10)),
300
+ inPathIndices: inputMerklePathIndices,
301
+ inPathElements: inputMerklePathElements,
302
+ // Output UTXO data (UTXOs being created) - ensure all values are in decimal format
303
+ outAmount: outputs.map((x) => x.amount.toString(10)),
304
+ outBlinding: outputs.map((x) => x.blinding.toString(10)),
305
+ outPubkey: outputs.map((x) => x.pubkey), // Use .pubkey (BN) directly, as keypair might be undefined
306
+ // new mint address
307
+ mintAddress: inputs[0].mintAddress,
308
+ };
309
+ logger.info("generating ZK proof...");
310
+ // Generate the zero-knowledge proof
311
+ const { proof, publicSignals } = await prove(input, keyBasePath);
312
+ // Parse the proof and public signals into byte arrays
313
+ const proofInBytes = parseProofToBytesArray(proof);
314
+ const inputsInBytes = parseToBytesArray(publicSignals);
315
+ // Create the proof object to submit to the program
316
+ const proofToSubmit = {
317
+ proofA: proofInBytes.proofA,
318
+ proofB: proofInBytes.proofB.flat(),
319
+ proofC: proofInBytes.proofC,
320
+ root: inputsInBytes[0],
321
+ publicAmount: inputsInBytes[1],
322
+ extDataHash: inputsInBytes[2],
323
+ inputNullifiers: [inputsInBytes[3], inputsInBytes[4]],
324
+ outputCommitments: [inputsInBytes[5], inputsInBytes[6]],
325
+ };
326
+ // Find PDAs for nullifiers and commitments
327
+ const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
328
+ const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
329
+ // Address Lookup Table for transaction size optimization
330
+ logger.debug("Setting up Address Lookup Table...");
331
+ const lookupTableAccount = await useExistingALT(connection, ALT_ADDRESS);
332
+ if (!lookupTableAccount?.value) {
333
+ throw new Error(`ALT not found at address ${ALT_ADDRESS.toString()} `);
334
+ }
335
+ // Serialize the proof and extData
336
+ const serializedProof = serializeProofAndExtData(proofToSubmit, extData);
337
+ logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
338
+ // Create the deposit instruction (user signs, not relayer)
339
+ const depositInstruction = new TransactionInstruction({
340
+ keys: [
341
+ { pubkey: treeAccount, isSigner: false, isWritable: true },
342
+ { pubkey: nullifier0PDA, isSigner: false, isWritable: true },
343
+ { pubkey: nullifier1PDA, isSigner: false, isWritable: true },
344
+ { pubkey: nullifier2PDA, isSigner: false, isWritable: false },
345
+ { pubkey: nullifier3PDA, isSigner: false, isWritable: false },
346
+ { pubkey: treeTokenAccount, isSigner: false, isWritable: true },
347
+ { pubkey: globalConfigAccount, isSigner: false, isWritable: false },
348
+ // recipient - just a placeholder, not actually used for deposits. using an ALT address to save bytes
349
+ {
350
+ pubkey: new PublicKey("AWexibGxNFKTa1b5R5MN4PJr9HWnWRwf8EW9g8cLx3dM"),
351
+ isSigner: false,
352
+ isWritable: true,
353
+ },
354
+ // fee recipient
355
+ { pubkey: FEE_RECIPIENT, isSigner: false, isWritable: true },
356
+ // signer
357
+ { pubkey: signer, isSigner: true, isWritable: true },
358
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
359
+ ],
360
+ programId: PROGRAM_ID,
361
+ data: serializedProof,
362
+ });
363
+ // Set compute budget for the transaction
364
+ const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
365
+ units: 1_000_000,
366
+ });
367
+ // Create versioned transaction with Address Lookup Table
368
+ const recentBlockhash = await connection.getLatestBlockhash();
369
+ const messageV0 = new TransactionMessage({
370
+ payerKey: signer, // User pays for their own deposit
371
+ recentBlockhash: recentBlockhash.blockhash,
372
+ instructions: [modifyComputeUnits, depositInstruction],
373
+ }).compileToV0Message([lookupTableAccount.value]);
374
+ let versionedTransaction = new VersionedTransaction(messageV0);
375
+ // sign tx
376
+ versionedTransaction = await transactionSigner(versionedTransaction);
377
+ logger.debug("Transaction signed by user");
378
+ // Serialize the signed transaction for relay
379
+ const serializedTransaction = Buffer.from(versionedTransaction.serialize()).toString("base64");
380
+ logger.debug("Prepared signed transaction for relay to indexer backend");
381
+ // Relay the pre-signed transaction to indexer backend
382
+ logger.info("submitting transaction to relayer...");
383
+ const signature = await relayDepositToIndexer(serializedTransaction, signer, referrer);
384
+ logger.debug("Transaction signature:", signature);
385
+ logger.debug(`Transaction link: https://orbmarkets.io/tx/${signature}`);
386
+ logger.info("Waiting for transaction confirmation...");
387
+ let retryTimes = 0;
388
+ let itv = 2;
389
+ const encryptedOutputStr = Buffer.from(encryptedOutput1).toString("hex");
390
+ let start = Date.now();
391
+ while (true) {
392
+ logger.info("Confirming transaction..");
393
+ logger.debug(`retryTimes: ${retryTimes}`);
394
+ await new Promise((resolve) => setTimeout(resolve, itv * 1000));
395
+ logger.debug("Fetching updated tree state...");
396
+ let res = await fetch(RELAYER_API_URL + "/utxos/check/" + encryptedOutputStr);
397
+ let resJson = await res.json();
398
+ if (resJson.exists) {
399
+ logger.debug(`Top up successfully in ${((Date.now() - start) / 1000).toFixed(2)} seconds!`);
400
+ return { tx: signature };
401
+ }
402
+ if (retryTimes >= 10) {
403
+ throw new TransactionTimeoutError(`Transaction confirmation timeout after ${retryTimes * 3} seconds`, signature || undefined);
404
+ }
405
+ retryTimes++;
406
+ }
407
+ }
408
+ async function checkDepositLimit(connection) {
409
+ try {
410
+ // Derive the tree account PDA
411
+ const [treeAccount] = PublicKey.findProgramAddressSync([Buffer.from("merkle_tree")], PROGRAM_ID);
412
+ // Fetch the account data
413
+ const accountInfo = await connection.getAccountInfo(treeAccount);
414
+ if (!accountInfo) {
415
+ console.error("❌ Tree account not found. Make sure the program is initialized." +
416
+ PROGRAM_ID);
417
+ return;
418
+ }
419
+ logger.debug(`Account data size: ${accountInfo.data.length} bytes`);
420
+ const authority = new PublicKey(accountInfo.data.slice(8, 40));
421
+ const nextIndex = new BN(accountInfo.data.slice(40, 48), "le");
422
+ const rootIndex = new BN(accountInfo.data.slice(4112, 4120), "le");
423
+ const maxDepositAmount = new BN(accountInfo.data.slice(4120, 4128), "le");
424
+ const bump = accountInfo.data[4128];
425
+ // Convert to SOL using BN division to handle large numbers
426
+ const lamportsPerSol = new BN(1_000_000_000);
427
+ const maxDepositSol = maxDepositAmount.div(lamportsPerSol);
428
+ const remainder = maxDepositAmount.mod(lamportsPerSol);
429
+ // Format the SOL amount with decimals
430
+ let solFormatted = "1";
431
+ if (remainder.eq(new BN(0))) {
432
+ solFormatted = maxDepositSol.toString();
433
+ }
434
+ else {
435
+ // Handle fractional SOL by converting remainder to decimal
436
+ const fractional = remainder.toNumber() / 1e9;
437
+ solFormatted = `${maxDepositSol.toString()}${fractional.toFixed(9).substring(1)}`;
438
+ }
439
+ return Number(solFormatted);
440
+ }
441
+ catch (error) {
442
+ console.log("❌ Error reading deposit limit:", error);
443
+ throw error;
444
+ }
445
+ }
@@ -0,0 +1,24 @@
1
+ import { Connection, PublicKey, VersionedTransaction } from "@solana/web3.js";
2
+ import BN from "bn.js";
3
+ import * as hasher from "@lightprotocol/hasher.rs";
4
+ import { EncryptionService } from "./utils/encryption.js";
5
+ type DepositParams = {
6
+ mintAddress: PublicKey | string;
7
+ publicKey: PublicKey;
8
+ connection: Connection;
9
+ base_units?: number;
10
+ amount?: number;
11
+ storage: Storage;
12
+ encryptionService: EncryptionService;
13
+ keyBasePath: string;
14
+ lightWasm: hasher.LightWasm;
15
+ referrer?: string;
16
+ signer?: PublicKey;
17
+ transactionSigner: (tx: VersionedTransaction) => Promise<VersionedTransaction>;
18
+ recipientUtxoPublicKey?: BN | string;
19
+ recipientEncryptionKey?: Uint8Array;
20
+ };
21
+ export declare function depositSPL({ lightWasm, storage, keyBasePath, publicKey, connection, base_units, amount, encryptionService, transactionSigner, referrer, mintAddress, signer, recipientUtxoPublicKey, recipientEncryptionKey, }: DepositParams): Promise<{
22
+ tx: string;
23
+ }>;
24
+ export {};