privacycash 1.0.16 → 1.0.18

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 (45) hide show
  1. package/__tests__/e2e.test.ts +5 -1
  2. package/__tests__/e2espl.test.ts +73 -0
  3. package/dist/config.d.ts +1 -0
  4. package/dist/config.js +6 -10
  5. package/dist/deposit.js +4 -11
  6. package/dist/depositSPL.d.ts +19 -0
  7. package/dist/depositSPL.js +433 -0
  8. package/dist/exportUtils.d.ts +3 -0
  9. package/dist/exportUtils.js +3 -0
  10. package/dist/getUtxos.d.ts +2 -1
  11. package/dist/getUtxos.js +68 -79
  12. package/dist/getUtxosSPL.d.ts +31 -0
  13. package/dist/getUtxosSPL.js +369 -0
  14. package/dist/index.d.ts +31 -1
  15. package/dist/index.js +73 -3
  16. package/dist/models/utxo.js +10 -1
  17. package/dist/utils/address_lookup_table.d.ts +1 -0
  18. package/dist/utils/address_lookup_table.js +23 -0
  19. package/dist/utils/constants.d.ts +3 -1
  20. package/dist/utils/constants.js +6 -3
  21. package/dist/utils/encryption.d.ts +1 -1
  22. package/dist/utils/encryption.js +5 -3
  23. package/dist/utils/prover.d.ts +4 -1
  24. package/dist/utils/prover.js +26 -2
  25. package/dist/utils/utils.d.ts +3 -2
  26. package/dist/utils/utils.js +26 -6
  27. package/dist/withdraw.js +3 -3
  28. package/dist/withdrawSPL.d.ts +22 -0
  29. package/dist/withdrawSPL.js +290 -0
  30. package/package.json +5 -3
  31. package/src/config.ts +7 -14
  32. package/src/deposit.ts +4 -11
  33. package/src/depositSPL.ts +555 -0
  34. package/src/exportUtils.ts +5 -1
  35. package/src/getUtxos.ts +73 -78
  36. package/src/getUtxosSPL.ts +495 -0
  37. package/src/index.ts +84 -3
  38. package/src/models/utxo.ts +10 -1
  39. package/src/utils/address_lookup_table.ts +54 -6
  40. package/src/utils/constants.ts +8 -3
  41. package/src/utils/encryption.ts +6 -3
  42. package/src/utils/prover.ts +36 -3
  43. package/src/utils/utils.ts +29 -6
  44. package/src/withdraw.ts +4 -4
  45. package/src/withdrawSPL.ts +379 -0
@@ -0,0 +1,555 @@
1
+ import { Connection, Keypair, PublicKey, TransactionInstruction, SystemProgram, ComputeBudgetProgram, VersionedTransaction, TransactionMessage, AddressLookupTableProgram } from '@solana/web3.js';
2
+ import BN from 'bn.js';
3
+ import { Utxo } from './models/utxo.js';
4
+ import { fetchMerkleProof, findNullifierPDAs, getProgramAccounts, queryRemoteTreeState, findCrossCheckNullifierPDAs, getExtDataHash, getMintAddressField } from './utils/utils.js';
5
+ import { prove, parseProofToBytesArray, parseToBytesArray } from './utils/prover.js';
6
+ import * as hasher from '@lightprotocol/hasher.rs';
7
+ import { MerkleTree } from './utils/merkle_tree.js';
8
+ import { EncryptionService, serializeProofAndExtData } from './utils/encryption.js';
9
+ import { Keypair as UtxoKeypair } from './models/keypair.js';
10
+ import { getUtxosSPL, isUtxoSpent } from './getUtxosSPL.js';
11
+ import { FIELD_SIZE, FEE_RECIPIENT, MERKLE_TREE_DEPTH, RELAYER_API_URL, PROGRAM_ID, ALT_ADDRESS } from './utils/constants.js';
12
+ import { getProtocolAddressesWithMint, useExistingALT } from './utils/address_lookup_table.js';
13
+ import { logger } from './utils/logger.js';
14
+ import { getAssociatedTokenAddress, ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, getMint, getAccount } from '@solana/spl-token';
15
+
16
+
17
+ // Function to relay pre-signed deposit transaction to indexer backend
18
+ async function relayDepositToIndexer({ signedTransaction, publicKey, referrer, mintAddress }:
19
+ {
20
+ signedTransaction: string,
21
+ publicKey: PublicKey,
22
+ mintAddress: string,
23
+ referrer?: string
24
+ })
25
+ : Promise<string> {
26
+ try {
27
+ logger.debug('Relaying pre-signed deposit transaction to indexer backend...');
28
+
29
+ const params: any = {
30
+ signedTransaction,
31
+ senderAddress: publicKey.toString()
32
+ };
33
+
34
+ if (referrer) {
35
+ params.referralWalletAddress = referrer
36
+ }
37
+ params.mintAddress = mintAddress.toString()
38
+
39
+ const response = await fetch(`${RELAYER_API_URL}/deposit/spl`, {
40
+ method: 'POST',
41
+ headers: {
42
+ 'Content-Type': 'application/json',
43
+ },
44
+ body: JSON.stringify(params)
45
+ });
46
+
47
+ if (!response.ok) {
48
+ console.log('res text:', await response.json())
49
+ throw new Error('response not ok')
50
+ // const errorData = await response.json() as { error?: string };
51
+ // throw new Error(`Deposit relay failed: ${response.status} ${response.statusText} - ${errorData.error || 'Unknown error'}`);
52
+ }
53
+
54
+ const result = await response.json() as { signature: string, success: boolean };
55
+ logger.debug('Pre-signed deposit transaction relayed successfully!');
56
+ logger.debug('Response:', result);
57
+
58
+ return result.signature;
59
+ } catch (error) {
60
+ console.error('Failed to relay deposit transaction to indexer:', error);
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ type DepositParams = {
66
+ mintAddress: PublicKey,
67
+ publicKey: PublicKey,
68
+ connection: Connection,
69
+ base_units: number,
70
+ storage: Storage,
71
+ encryptionService: EncryptionService,
72
+ keyBasePath: string,
73
+ lightWasm: hasher.LightWasm,
74
+ referrer?: string,
75
+ transactionSigner: (tx: VersionedTransaction) => Promise<VersionedTransaction>
76
+ }
77
+ export async function depositSPL({ lightWasm, storage, keyBasePath, publicKey, connection, base_units, encryptionService, transactionSigner, referrer, mintAddress }: DepositParams) {
78
+ let mintInfo = await getMint(connection, mintAddress)
79
+ let units_per_token = 10 ** mintInfo.decimals
80
+
81
+ let recipient = new PublicKey('AWexibGxNFKTa1b5R5MN4PJr9HWnWRwf8EW9g8cLx3dM')
82
+ let recipient_ata = getAssociatedTokenAddressSync(
83
+ mintAddress,
84
+ recipient,
85
+ true
86
+ );
87
+ let feeRecipientTokenAccount = getAssociatedTokenAddressSync(
88
+ mintAddress,
89
+ FEE_RECIPIENT,
90
+ true
91
+ );
92
+ let signerTokenAccount = getAssociatedTokenAddressSync(
93
+ mintAddress,
94
+ publicKey
95
+ );
96
+
97
+ // Derive tree account PDA with mint address for SPL (different from SOL version)
98
+ const [treeAccount] = PublicKey.findProgramAddressSync(
99
+ [Buffer.from('merkle_tree'), mintAddress.toBuffer()],
100
+ PROGRAM_ID
101
+ );
102
+
103
+ let limitAmount = await checkDepositLimit(connection, treeAccount)
104
+ if (limitAmount && base_units > limitAmount * 1e6) {
105
+ throw new Error(`Don't deposit more than ${limitAmount} USDC`)
106
+ }
107
+
108
+
109
+
110
+ // check limit
111
+ // let limitAmount = await checkDepositLimit(connection)
112
+ // if (limitAmount && base_units > limitAmount * units_per_token) {
113
+ // throw new Error(`Don't deposit more than ${limitAmount} SOL`)
114
+ // }
115
+
116
+ // const base_units = amount_in_sol * units_per_token
117
+ const fee_base_units = 0
118
+ logger.debug('Encryption key generated from user keypair');
119
+ logger.debug(`User wallet: ${publicKey.toString()}`);
120
+ logger.debug(`Deposit amount: ${base_units} base_units (${base_units / units_per_token} USDC)`);
121
+ logger.debug(`Calculated fee: ${fee_base_units} base_units (${fee_base_units / units_per_token} USDC)`);
122
+
123
+ // Check SPL balance
124
+ const accountInfo = await getAccount(connection, signerTokenAccount)
125
+ let balance = Number(accountInfo.amount)
126
+ logger.debug(`USDC wallet balance: ${balance / units_per_token} USDC`);
127
+ console.log('balance', balance)
128
+ console.log('base_units + fee_base_units', base_units + fee_base_units)
129
+
130
+ if (balance < (base_units + fee_base_units)) {
131
+ throw new Error(`Insufficient balance. Need at least ${(base_units + fee_base_units) / units_per_token} USDC.`);
132
+ }
133
+
134
+ // Check SOL balance
135
+ const solBalance = await connection.getBalance(publicKey);
136
+ logger.debug(`SOL Wallet balance: ${solBalance / 1e9} SOL`);
137
+
138
+ if (solBalance / 1e9 < 0.01) {
139
+ throw new Error(`Need at least 0.01 SOL for Solana fees.`);
140
+ }
141
+
142
+ const { globalConfigAccount } = getProgramAccounts()
143
+
144
+ // Create the merkle tree with the pre-initialized poseidon hash
145
+ const tree = new MerkleTree(MERKLE_TREE_DEPTH, lightWasm);
146
+
147
+ // Initialize root and nextIndex variables
148
+ const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState('usdc');
149
+
150
+ logger.debug(`Using tree root: ${root}`);
151
+ logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
152
+
153
+ // Generate a deterministic private key derived from the wallet keypair
154
+ // const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
155
+ const utxoPrivateKey = encryptionService.getUtxoPrivateKeyV2();
156
+
157
+ // Create a UTXO keypair that will be used for all inputs and outputs
158
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
159
+ logger.debug('Using wallet-derived UTXO keypair for deposit');
160
+
161
+ // Fetch existing UTXOs for this user
162
+ logger.debug('\nFetching existing UTXOs...');
163
+ const mintUtxos = await getUtxosSPL({ connection, publicKey, encryptionService, storage, mintAddress });
164
+ // Calculate output amounts and external amount based on scenario
165
+ let extAmount: number;
166
+ let outputAmount: string;
167
+
168
+ // Create inputs based on whether we have existing UTXOs
169
+ let inputs: Utxo[];
170
+ let inputMerklePathIndices: number[];
171
+ let inputMerklePathElements: string[][];
172
+
173
+ if (mintUtxos.length === 0) {
174
+ // Scenario 1: Fresh deposit with dummy inputs - add new funds to the system
175
+ extAmount = base_units;
176
+ outputAmount = new BN(base_units).sub(new BN(fee_base_units)).toString();
177
+
178
+ logger.debug(`Fresh deposit scenario (no existing UTXOs):`);
179
+ logger.debug(`External amount (deposit): ${extAmount}`);
180
+ logger.debug(`Fee amount: ${fee_base_units}`);
181
+ logger.debug(`Output amount: ${outputAmount}`);
182
+
183
+ // Use two dummy UTXOs as inputs
184
+ inputs = [
185
+ new Utxo({
186
+ lightWasm,
187
+ keypair: utxoKeypair,
188
+ mintAddress: mintAddress.toString()
189
+ }),
190
+ new Utxo({
191
+ lightWasm,
192
+ keypair: utxoKeypair,
193
+ mintAddress: mintAddress.toString()
194
+ })
195
+ ];
196
+
197
+ // Both inputs are dummy, so use mock indices and zero-filled Merkle paths
198
+ inputMerklePathIndices = inputs.map((input) => input.index || 0);
199
+ inputMerklePathElements = inputs.map(() => {
200
+ return [...new Array(tree.levels).fill("0")];
201
+ });
202
+ } else {
203
+ // Scenario 2: Deposit that consolidates with existing UTXO(s)
204
+ const firstUtxo = mintUtxos[0];
205
+ const firstUtxoAmount = firstUtxo.amount;
206
+ const secondUtxoAmount = mintUtxos.length > 1 ? mintUtxos[1].amount : new BN(0);
207
+ extAmount = base_units; // Still depositing new funds
208
+
209
+ // Output combines existing UTXO amounts + new deposit amount - fee
210
+ outputAmount = firstUtxoAmount.add(secondUtxoAmount).add(new BN(base_units)).sub(new BN(fee_base_units)).toString();
211
+
212
+ logger.debug(`Deposit with consolidation scenario:`);
213
+ logger.debug(`First existing UTXO amount: ${firstUtxoAmount.toString()}`);
214
+ if (secondUtxoAmount.gt(new BN(0))) {
215
+ logger.debug(`Second existing UTXO amount: ${secondUtxoAmount.toString()}`);
216
+ }
217
+ logger.debug(`New deposit amount: ${base_units}`);
218
+ logger.debug(`Fee amount: ${fee_base_units}`);
219
+ logger.debug(`Output amount (existing UTXOs + deposit - fee): ${outputAmount}`);
220
+ logger.debug(`External amount (deposit): ${extAmount}`);
221
+
222
+ logger.debug('\nFirst UTXO to be consolidated:');
223
+ await firstUtxo.log();
224
+
225
+ // Use first existing UTXO as first input, and either second UTXO or dummy UTXO as second input
226
+ const secondUtxo = mintUtxos.length > 1 ? mintUtxos[1] : new Utxo({
227
+ lightWasm,
228
+ keypair: utxoKeypair,
229
+ amount: '0', // This UTXO will be inserted at currentNextIndex
230
+ mintAddress: mintAddress.toString()
231
+ });
232
+
233
+ inputs = [
234
+ firstUtxo, // Use the first existing UTXO
235
+ secondUtxo // Use second UTXO if available, otherwise dummy
236
+ ];
237
+
238
+ // Fetch Merkle proofs for real UTXOs
239
+ const firstUtxoCommitment = await firstUtxo.getCommitment();
240
+ const firstUtxoMerkleProof = await fetchMerkleProof(firstUtxoCommitment, 'usdc');
241
+
242
+ let secondUtxoMerkleProof;
243
+ if (secondUtxo.amount.gt(new BN(0))) {
244
+ // Second UTXO is real, fetch its proof
245
+ const secondUtxoCommitment = await secondUtxo.getCommitment();
246
+ secondUtxoMerkleProof = await fetchMerkleProof(secondUtxoCommitment, 'usdc');
247
+ logger.debug('\nSecond UTXO to be consolidated:');
248
+ await secondUtxo.log();
249
+ }
250
+
251
+ // Use the real pathIndices from API for real inputs, mock index for dummy input
252
+ inputMerklePathIndices = [
253
+ firstUtxo.index || 0, // Use the real UTXO's index
254
+ secondUtxo.amount.gt(new BN(0)) ? (secondUtxo.index || 0) : 0 // Real UTXO index or dummy
255
+ ];
256
+
257
+ // Create Merkle path elements: real proof for real inputs, zeros for dummy input
258
+ inputMerklePathElements = [
259
+ firstUtxoMerkleProof.pathElements, // Real Merkle proof for first existing UTXO
260
+ secondUtxo.amount.gt(new BN(0)) ? secondUtxoMerkleProof!.pathElements : [...new Array(tree.levels).fill("0")] // Real proof or zero-filled for dummy
261
+ ];
262
+
263
+ logger.debug(`Using first UTXO with amount: ${firstUtxo.amount.toString()} and index: ${firstUtxo.index}`);
264
+ 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}` : ''}`);
265
+ logger.debug(`First UTXO Merkle proof path indices from API: [${firstUtxoMerkleProof.pathIndices.join(', ')}]`);
266
+ if (secondUtxo.amount.gt(new BN(0))) {
267
+ logger.debug(`Second UTXO Merkle proof path indices from API: [${secondUtxoMerkleProof!.pathIndices.join(', ')}]`);
268
+ }
269
+ }
270
+
271
+ const publicAmountForCircuit = new BN(extAmount).sub(new BN(fee_base_units)).add(FIELD_SIZE).mod(FIELD_SIZE);
272
+ logger.debug(`Public amount calculation: (${extAmount} - ${fee_base_units} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
273
+
274
+ // Create outputs for the transaction with the same shared keypair
275
+ const outputs = [
276
+ new Utxo({
277
+ lightWasm,
278
+ amount: outputAmount,
279
+ keypair: utxoKeypair,
280
+ index: currentNextIndex, // This UTXO will be inserted at currentNextIndex
281
+ mintAddress: mintAddress.toString()
282
+ }), // Output with value (either deposit amount minus fee, or input amount minus fee)
283
+ new Utxo({
284
+ lightWasm,
285
+ amount: '0',
286
+ keypair: utxoKeypair,
287
+ index: currentNextIndex + 1, // This UTXO will be inserted at currentNextIndex
288
+ mintAddress: mintAddress.toString()
289
+ }) // Empty UTXO
290
+ ];
291
+
292
+ // Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
293
+ const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
294
+ const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
295
+ logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
296
+
297
+ // Convert to circuit-compatible format
298
+ const publicAmountCircuitResult = sumIns.add(publicAmountForCircuit).mod(FIELD_SIZE);
299
+ logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
300
+ logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
301
+ logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
302
+
303
+ // Generate nullifiers and commitments
304
+ const inputNullifiers = await Promise.all(inputs.map(x => x.getNullifier()));
305
+ const outputCommitments = await Promise.all(outputs.map(x => x.getCommitment()));
306
+
307
+ // Save original commitment and nullifier values for verification
308
+ logger.debug('\n=== UTXO VALIDATION ===');
309
+ logger.debug('Output 0 Commitment:', outputCommitments[0]);
310
+ logger.debug('Output 1 Commitment:', outputCommitments[1]);
311
+
312
+ // Encrypt the UTXO data using a compact format that includes the keypair
313
+ logger.debug('\nEncrypting UTXOs with keypair data...');
314
+ const encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
315
+ const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
316
+
317
+ logger.debug(`\nOutput[0] (with value):`);
318
+ await outputs[0].log();
319
+ logger.debug(`\nOutput[1] (empty):`);
320
+ await outputs[1].log();
321
+
322
+ logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
323
+ logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
324
+ logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
325
+
326
+ // Test decryption to verify commitment values match
327
+ logger.debug('\n=== TESTING DECRYPTION ===');
328
+ logger.debug('Decrypting output 1 to verify commitment matches...');
329
+ const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
330
+ const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
331
+ logger.debug('Original commitment:', outputCommitments[0]);
332
+ logger.debug('Decrypted commitment:', decryptedCommitment1);
333
+ logger.debug('Commitment matches:', outputCommitments[0] === decryptedCommitment1);
334
+
335
+ // Create the deposit ExtData with real encrypted outputs
336
+ const extData = {
337
+ // recipient - just a placeholder, not actually used for deposits.
338
+ recipient: recipient_ata,
339
+ extAmount: new BN(extAmount),
340
+ encryptedOutput1: encryptedOutput1,
341
+ encryptedOutput2: encryptedOutput2,
342
+ fee: new BN(fee_base_units),
343
+ feeRecipient: feeRecipientTokenAccount,
344
+ mintAddress: mintAddress.toString()
345
+ };
346
+ // Calculate the extDataHash with the encrypted outputs (now includes mintAddress for security)
347
+ const calculatedExtDataHash = getExtDataHash(extData);
348
+
349
+ // Create the input for the proof generation (must match circuit input order exactly)
350
+ const input = {
351
+ // Common transaction data
352
+ root: root,
353
+ mintAddress: getMintAddressField(mintAddress),// new mint address
354
+ publicAmount: publicAmountForCircuit.toString(), // Use proper field arithmetic result
355
+ extDataHash: calculatedExtDataHash,
356
+
357
+ // Input UTXO data (UTXOs being spent) - ensure all values are in decimal format
358
+ inAmount: inputs.map(x => x.amount.toString(10)),
359
+ inPrivateKey: inputs.map(x => x.keypair.privkey),
360
+ inBlinding: inputs.map(x => x.blinding.toString(10)),
361
+ inPathIndices: inputMerklePathIndices,
362
+ inPathElements: inputMerklePathElements,
363
+ inputNullifier: inputNullifiers, // Use resolved values instead of Promise objects
364
+
365
+ // Output UTXO data (UTXOs being created) - ensure all values are in decimal format
366
+ outAmount: outputs.map(x => x.amount.toString(10)),
367
+ outBlinding: outputs.map(x => x.blinding.toString(10)),
368
+ outPubkey: outputs.map(x => x.keypair.pubkey),
369
+ outputCommitment: outputCommitments,
370
+ };
371
+
372
+ logger.info('generating ZK proof...');
373
+
374
+ // Generate the zero-knowledge proof
375
+ const { proof, publicSignals } = await prove(input, keyBasePath);
376
+ // Parse the proof and public signals into byte arrays
377
+ const proofInBytes = parseProofToBytesArray(proof);
378
+ const inputsInBytes = parseToBytesArray(publicSignals);
379
+
380
+ // Create the proof object to submit to the program
381
+ const proofToSubmit = {
382
+ proofA: proofInBytes.proofA,
383
+ proofB: proofInBytes.proofB.flat(),
384
+ proofC: proofInBytes.proofC,
385
+ root: inputsInBytes[0],
386
+ publicAmount: inputsInBytes[1],
387
+ extDataHash: inputsInBytes[2],
388
+ inputNullifiers: [
389
+ inputsInBytes[3],
390
+ inputsInBytes[4]
391
+ ],
392
+ outputCommitments: [
393
+ inputsInBytes[5],
394
+ inputsInBytes[6]
395
+ ],
396
+ };
397
+
398
+ // Find PDAs for nullifiers and commitments
399
+ const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
400
+ const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
401
+
402
+ const [globalConfigPda, globalConfigPdaBump] = await PublicKey.findProgramAddressSync(
403
+ [Buffer.from("global_config")],
404
+ PROGRAM_ID
405
+ );
406
+ const treeAta = getAssociatedTokenAddressSync(mintAddress, globalConfigPda, true);
407
+
408
+ const lookupTableAccount = await useExistingALT(connection, ALT_ADDRESS);
409
+
410
+ if (!lookupTableAccount?.value) {
411
+ throw new Error(`ALT not found at address ${ALT_ADDRESS.toString()} `);
412
+ }
413
+
414
+ // Serialize the proof and extData with SPL discriminator
415
+ const serializedProof = serializeProofAndExtData(proofToSubmit, extData, true);
416
+ logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
417
+
418
+ // Create the deposit instruction (user signs, not relayer)
419
+ const depositInstruction = new TransactionInstruction({
420
+ keys: [
421
+ { pubkey: treeAccount, isSigner: false, isWritable: true },
422
+ { pubkey: nullifier0PDA, isSigner: false, isWritable: true },
423
+ { pubkey: nullifier1PDA, isSigner: false, isWritable: true },
424
+ { pubkey: nullifier2PDA, isSigner: false, isWritable: false },
425
+ { pubkey: nullifier3PDA, isSigner: false, isWritable: false },
426
+
427
+ { pubkey: globalConfigAccount, isSigner: false, isWritable: false },
428
+ // signer
429
+ { pubkey: publicKey, isSigner: true, isWritable: true },
430
+ // SPL token mint
431
+ { pubkey: mintAddress, isSigner: false, isWritable: false },
432
+ // signer's token account
433
+ { pubkey: signerTokenAccount, isSigner: false, isWritable: true },
434
+ // recipient (placeholder)
435
+ { pubkey: recipient, isSigner: false, isWritable: true },
436
+ // recipient's token account (placeholder)
437
+ { pubkey: recipient_ata, isSigner: false, isWritable: true },
438
+ // tree ATA
439
+ { pubkey: treeAta, isSigner: false, isWritable: true },
440
+ // fee recipient token account
441
+ { pubkey: feeRecipientTokenAccount, isSigner: false, isWritable: true },
442
+
443
+ // token program id
444
+ { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
445
+ // ATA program
446
+ { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
447
+ // system protgram
448
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
449
+
450
+ ],
451
+ programId: PROGRAM_ID,
452
+ data: serializedProof,
453
+ });
454
+
455
+ // Set compute budget for the transaction
456
+ const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
457
+ units: 1_000_000
458
+ });
459
+
460
+ // Create versioned transaction with Address Lookup Table
461
+ const recentBlockhash = await connection.getLatestBlockhash();
462
+
463
+ const messageV0 = new TransactionMessage({
464
+ payerKey: publicKey, // User pays for their own deposit
465
+ recentBlockhash: recentBlockhash.blockhash,
466
+ instructions: [modifyComputeUnits, depositInstruction],
467
+ }).compileToV0Message([lookupTableAccount.value]);
468
+
469
+
470
+ let versionedTransaction = new VersionedTransaction(messageV0);
471
+
472
+ // sign tx
473
+ versionedTransaction = await transactionSigner(versionedTransaction)
474
+
475
+ logger.debug('Transaction signed by user');
476
+
477
+ // Serialize the signed transaction for relay
478
+ const serializedTransaction = Buffer.from(versionedTransaction.serialize()).toString('base64');
479
+
480
+ logger.debug('Prepared signed transaction for relay to indexer backend');
481
+
482
+ // Relay the pre-signed transaction to indexer backend
483
+ logger.info('submitting transaction to relayer...')
484
+ const signature = await relayDepositToIndexer({
485
+ mintAddress: mintAddress.toString(),
486
+ publicKey,
487
+ signedTransaction: serializedTransaction
488
+ });
489
+ logger.debug('Transaction signature:', signature);
490
+ logger.debug(`Transaction link: https://explorer.solana.com/tx/${signature}`);
491
+
492
+ logger.info('Waiting for transaction confirmation...')
493
+
494
+ let retryTimes = 0
495
+ let itv = 2
496
+ const encryptedOutputStr = Buffer.from(encryptedOutput1).toString('hex')
497
+ let start = Date.now()
498
+ while (true) {
499
+ logger.debug(`retryTimes: ${retryTimes}`)
500
+ await new Promise(resolve => setTimeout(resolve, itv * 1000));
501
+ logger.debug('Fetching updated tree state...');
502
+ let url = RELAYER_API_URL + '/utxos/check/' + encryptedOutputStr + '?token=usdc'
503
+ let res = await fetch(url)
504
+ let resJson = await res.json()
505
+ if (resJson.exists) {
506
+ logger.debug(`Top up successfully in ${((Date.now() - start) / 1000).toFixed(2)} seconds!`);
507
+ return { tx: signature }
508
+ }
509
+ if (retryTimes >= 10) {
510
+ throw new Error('Refresh the page to see latest balance.')
511
+ }
512
+ retryTimes++
513
+ }
514
+
515
+ }
516
+
517
+
518
+ async function checkDepositLimit(connection: Connection, treeAccount: PublicKey) {
519
+ try {
520
+
521
+ // Fetch the account data
522
+ const accountInfo = await connection.getAccountInfo(treeAccount);
523
+
524
+ if (!accountInfo) {
525
+ console.error('❌ Tree account not found. Make sure the program is initialized.');
526
+ return;
527
+ }
528
+
529
+ const authority = new PublicKey(accountInfo.data.slice(8, 40));
530
+ const nextIndex = new BN(accountInfo.data.slice(40, 48), 'le');
531
+ const rootIndex = new BN(accountInfo.data.slice(4112, 4120), 'le');
532
+ const maxDepositAmount = new BN(accountInfo.data.slice(4120, 4128), 'le');
533
+ const bump = accountInfo.data[4128];
534
+
535
+ // Convert to SOL using BN division to handle large numbers
536
+ const lamportsPerSol = new BN(1e6);
537
+ const maxDepositSol = maxDepositAmount.div(lamportsPerSol);
538
+ const remainder = maxDepositAmount.mod(lamportsPerSol);
539
+
540
+ // Format the SOL amount with decimals
541
+ let solFormatted = '1';
542
+ if (remainder.eq(new BN(0))) {
543
+ solFormatted = maxDepositSol.toString();
544
+ } else {
545
+ // Handle fractional SOL by converting remainder to decimal
546
+ const fractional = remainder.toNumber() / 1e6;
547
+ solFormatted = `${maxDepositSol.toString()}${fractional.toFixed(9).substring(1)}`;
548
+ }
549
+ return Number(solFormatted)
550
+
551
+ } catch (error) {
552
+ console.log('❌ Error reading deposit limit:', error);
553
+ throw error
554
+ }
555
+ }
@@ -3,4 +3,8 @@ export { deposit } from './deposit.js'
3
3
  export { withdraw } from './withdraw.js'
4
4
  export { EncryptionService } from './utils/encryption.js'
5
5
  export { setLogger } from './utils/logger.js'
6
- export { getBalanceFromUtxos, getUtxos, localstorageKey } from './getUtxos.js'
6
+ export { getBalanceFromUtxos, getUtxos, localstorageKey } from './getUtxos.js'
7
+
8
+ export { depositSPL } from './depositSPL.js'
9
+ export { withdrawSPL } from './withdrawSPL.js'
10
+ export { getBalanceFromUtxosSPL, getUtxosSPL } from './getUtxosSPL.js'