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