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