privacycash 1.0.6

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