pctestupgrade2 1.1.8

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