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