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