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