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