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