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