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