privacycash 1.0.16 → 1.0.18

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 (45) hide show
  1. package/__tests__/e2e.test.ts +5 -1
  2. package/__tests__/e2espl.test.ts +73 -0
  3. package/dist/config.d.ts +1 -0
  4. package/dist/config.js +6 -10
  5. package/dist/deposit.js +4 -11
  6. package/dist/depositSPL.d.ts +19 -0
  7. package/dist/depositSPL.js +433 -0
  8. package/dist/exportUtils.d.ts +3 -0
  9. package/dist/exportUtils.js +3 -0
  10. package/dist/getUtxos.d.ts +2 -1
  11. package/dist/getUtxos.js +68 -79
  12. package/dist/getUtxosSPL.d.ts +31 -0
  13. package/dist/getUtxosSPL.js +369 -0
  14. package/dist/index.d.ts +31 -1
  15. package/dist/index.js +73 -3
  16. package/dist/models/utxo.js +10 -1
  17. package/dist/utils/address_lookup_table.d.ts +1 -0
  18. package/dist/utils/address_lookup_table.js +23 -0
  19. package/dist/utils/constants.d.ts +3 -1
  20. package/dist/utils/constants.js +6 -3
  21. package/dist/utils/encryption.d.ts +1 -1
  22. package/dist/utils/encryption.js +5 -3
  23. package/dist/utils/prover.d.ts +4 -1
  24. package/dist/utils/prover.js +26 -2
  25. package/dist/utils/utils.d.ts +3 -2
  26. package/dist/utils/utils.js +26 -6
  27. package/dist/withdraw.js +3 -3
  28. package/dist/withdrawSPL.d.ts +22 -0
  29. package/dist/withdrawSPL.js +290 -0
  30. package/package.json +5 -3
  31. package/src/config.ts +7 -14
  32. package/src/deposit.ts +4 -11
  33. package/src/depositSPL.ts +555 -0
  34. package/src/exportUtils.ts +5 -1
  35. package/src/getUtxos.ts +73 -78
  36. package/src/getUtxosSPL.ts +495 -0
  37. package/src/index.ts +84 -3
  38. package/src/models/utxo.ts +10 -1
  39. package/src/utils/address_lookup_table.ts +54 -6
  40. package/src/utils/constants.ts +8 -3
  41. package/src/utils/encryption.ts +6 -3
  42. package/src/utils/prover.ts +36 -3
  43. package/src/utils/utils.ts +29 -6
  44. package/src/withdraw.ts +4 -4
  45. package/src/withdrawSPL.ts +379 -0
@@ -0,0 +1,290 @@
1
+ import { PublicKey } from '@solana/web3.js';
2
+ import BN from 'bn.js';
3
+ import { Buffer } from 'buffer';
4
+ import { Keypair as UtxoKeypair } from './models/keypair.js';
5
+ import { Utxo } from './models/utxo.js';
6
+ import { parseProofToBytesArray, parseToBytesArray, prove } from './utils/prover.js';
7
+ import { ALT_ADDRESS, DEPLOYER_ID, FEE_RECIPIENT, FIELD_SIZE, RELAYER_API_URL, MERKLE_TREE_DEPTH, PROGRAM_ID } from './utils/constants.js';
8
+ import { serializeProofAndExtData } from './utils/encryption.js';
9
+ import { fetchMerkleProof, findNullifierPDAs, getProgramAccounts, queryRemoteTreeState, findCrossCheckNullifierPDAs, getMintAddressField, getExtDataHash } from './utils/utils.js';
10
+ import { getUtxosSPL } from './getUtxosSPL.js';
11
+ import { logger } from './utils/logger.js';
12
+ import { getConfig } from './config.js';
13
+ import { getAssociatedTokenAddressSync, getMint } from '@solana/spl-token';
14
+ // Indexer API endpoint
15
+ // Function to submit withdraw request to indexer backend
16
+ async function submitWithdrawToIndexer(params) {
17
+ try {
18
+ const response = await fetch(`${RELAYER_API_URL}/withdraw/spl`, {
19
+ method: 'POST',
20
+ headers: {
21
+ 'Content-Type': 'application/json',
22
+ },
23
+ body: JSON.stringify(params)
24
+ });
25
+ if (!response.ok) {
26
+ const errorData = await response.json();
27
+ throw new Error(errorData.error);
28
+ }
29
+ const result = await response.json();
30
+ logger.debug('Withdraw request submitted successfully!');
31
+ logger.debug('Response:', result);
32
+ return result.signature;
33
+ }
34
+ catch (error) {
35
+ logger.debug('Failed to submit withdraw request to indexer:', typeof error, error);
36
+ throw error;
37
+ }
38
+ }
39
+ export async function withdrawSPL({ recipient, lightWasm, storage, publicKey, connection, base_units, encryptionService, keyBasePath, mintAddress }) {
40
+ let mintInfo = await getMint(connection, mintAddress);
41
+ let units_per_token = 10 ** mintInfo.decimals;
42
+ let withdraw_fee_rate = await getConfig('withdraw_fee_rate');
43
+ let withdraw_rent_fee = await getConfig('usdc_withdraw_rent_fee');
44
+ let fee_base_units = Math.floor(base_units * withdraw_fee_rate + units_per_token * withdraw_rent_fee);
45
+ base_units -= fee_base_units;
46
+ if (base_units <= 0) {
47
+ throw new Error('withdraw amount too low');
48
+ }
49
+ let isPartial = false;
50
+ let recipient_ata = getAssociatedTokenAddressSync(mintAddress, recipient, true);
51
+ let feeRecipientTokenAccount = getAssociatedTokenAddressSync(mintAddress, FEE_RECIPIENT, true);
52
+ let signerTokenAccount = getAssociatedTokenAddressSync(mintAddress, publicKey);
53
+ logger.debug('Encryption key generated from user keypair');
54
+ logger.debug(`Deployer wallet: ${DEPLOYER_ID.toString()}`);
55
+ // Derive tree account PDA with mint address for SPL (different from SOL version)
56
+ const [treeAccount] = PublicKey.findProgramAddressSync([Buffer.from('merkle_tree'), mintAddress.toBuffer()], PROGRAM_ID);
57
+ const { globalConfigAccount, treeTokenAccount } = getProgramAccounts();
58
+ // Get current tree state
59
+ const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState('usdc');
60
+ logger.debug(`Using tree root: ${root}`);
61
+ logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
62
+ // Generate a deterministic private key derived from the wallet keypair
63
+ const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
64
+ // Create a UTXO keypair that will be used for all inputs and outputs
65
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
66
+ logger.debug('Using wallet-derived UTXO keypair for withdrawal');
67
+ // Generate a deterministic private key derived from the wallet keypair (V2)
68
+ const utxoPrivateKeyV2 = encryptionService.getUtxoPrivateKeyV2();
69
+ const utxoKeypairV2 = new UtxoKeypair(utxoPrivateKeyV2, lightWasm);
70
+ // Fetch existing UTXOs for this user
71
+ logger.debug('\nFetching existing UTXOs...');
72
+ const mintUtxos = await getUtxosSPL({ connection, publicKey, encryptionService, storage, mintAddress });
73
+ logger.debug(`Found ${mintUtxos.length} total UTXOs`);
74
+ // Calculate and log total unspent UTXO balance
75
+ const totalUnspentBalance = mintUtxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
76
+ logger.debug(`Total unspent UTXO balance before: ${totalUnspentBalance.toString()} lamports (${totalUnspentBalance.toNumber() / 1e9} SOL)`);
77
+ if (mintUtxos.length < 1) {
78
+ throw new Error('Need at least 1 unspent UTXO to perform a withdrawal');
79
+ }
80
+ // Sort UTXOs by amount in descending order to use the largest ones first
81
+ mintUtxos.sort((a, b) => b.amount.cmp(a.amount));
82
+ // Use the largest UTXO as first input, and either second largest UTXO or dummy UTXO as second input
83
+ const firstInput = mintUtxos[0];
84
+ const secondInput = mintUtxos.length > 1 ? mintUtxos[1] : new Utxo({
85
+ lightWasm,
86
+ keypair: utxoKeypair,
87
+ amount: '0',
88
+ mintAddress: mintAddress.toString()
89
+ });
90
+ const inputs = [firstInput, secondInput];
91
+ logger.debug(`firstInput index: ${firstInput.index}, commitment: ${firstInput.getCommitment()}`);
92
+ logger.debug(`secondInput index: ${secondInput.index}, commitment: ${secondInput.getCommitment()}`);
93
+ const totalInputAmount = firstInput.amount.add(secondInput.amount);
94
+ logger.debug(`Using UTXO with amount: ${firstInput.amount.toString()} and ${secondInput.amount.gt(new BN(0)) ? 'second UTXO with amount: ' + secondInput.amount.toString() : 'dummy UTXO'}`);
95
+ if (totalInputAmount.toNumber() === 0) {
96
+ throw new Error('no balance');
97
+ }
98
+ if (totalInputAmount.lt(new BN(base_units + fee_base_units))) {
99
+ isPartial = true;
100
+ base_units = totalInputAmount.toNumber();
101
+ base_units -= fee_base_units;
102
+ }
103
+ // Calculate the change amount (what's left after withdrawal and fee)
104
+ const changeAmount = totalInputAmount.sub(new BN(base_units)).sub(new BN(fee_base_units));
105
+ logger.debug(`Withdrawing ${base_units} lamports with ${fee_base_units} fee, ${changeAmount.toString()} as change`);
106
+ // Get Merkle proofs for both input UTXOs
107
+ const inputMerkleProofs = await Promise.all(inputs.map(async (utxo, index) => {
108
+ // For dummy UTXO (amount is 0), use a zero-filled proof
109
+ if (utxo.amount.eq(new BN(0))) {
110
+ return {
111
+ pathElements: [...new Array(MERKLE_TREE_DEPTH).fill("0")],
112
+ pathIndices: Array(MERKLE_TREE_DEPTH).fill(0)
113
+ };
114
+ }
115
+ // For real UTXOs, fetch the proof from API
116
+ const commitment = await utxo.getCommitment();
117
+ return fetchMerkleProof(commitment, 'usdc');
118
+ }));
119
+ // Extract path elements and indices
120
+ const inputMerklePathElements = inputMerkleProofs.map(proof => proof.pathElements);
121
+ const inputMerklePathIndices = inputs.map(utxo => utxo.index || 0);
122
+ // Create outputs: first output is change, second is dummy (required by protocol)
123
+ const outputs = [
124
+ new Utxo({
125
+ lightWasm,
126
+ amount: changeAmount.toString(),
127
+ keypair: utxoKeypairV2,
128
+ index: currentNextIndex,
129
+ mintAddress: mintAddress.toString()
130
+ }), // Change output
131
+ new Utxo({
132
+ lightWasm,
133
+ amount: '0',
134
+ keypair: utxoKeypairV2,
135
+ index: currentNextIndex + 1,
136
+ mintAddress: mintAddress.toString()
137
+ }) // Empty UTXO
138
+ ];
139
+ // For withdrawals, extAmount is negative (funds leaving the system)
140
+ const extAmount = -base_units;
141
+ const publicAmountForCircuit = new BN(extAmount).sub(new BN(fee_base_units)).add(FIELD_SIZE).mod(FIELD_SIZE);
142
+ logger.debug(`Public amount calculation: (${extAmount} - ${fee_base_units} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
143
+ // Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
144
+ const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
145
+ const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
146
+ logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
147
+ // Convert to circuit-compatible format
148
+ const publicAmountCircuitResult = sumIns.add(publicAmountForCircuit).mod(FIELD_SIZE);
149
+ logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
150
+ logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
151
+ logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
152
+ // Generate nullifiers and commitments
153
+ const inputNullifiers = await Promise.all(inputs.map(x => x.getNullifier()));
154
+ const outputCommitments = await Promise.all(outputs.map(x => x.getCommitment()));
155
+ // Save original commitment and nullifier values for verification
156
+ logger.debug('\n=== UTXO VALIDATION ===');
157
+ logger.debug('Output 0 Commitment:', outputCommitments[0]);
158
+ logger.debug('Output 1 Commitment:', outputCommitments[1]);
159
+ // Encrypt the UTXO data using a compact format that includes the keypair
160
+ logger.debug('\nEncrypting UTXOs with keypair data...');
161
+ const encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
162
+ const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
163
+ logger.debug(`\nOutput[0] (change):`);
164
+ await outputs[0].log();
165
+ logger.debug(`\nOutput[1] (empty):`);
166
+ await outputs[1].log();
167
+ logger.debug(`Encrypted output 1: ${encryptedOutput1.toString('hex')}`);
168
+ logger.debug(`Encrypted output 2: ${encryptedOutput2.toString('hex')}`);
169
+ logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
170
+ logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
171
+ logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
172
+ // Test decryption to verify commitment values match
173
+ logger.debug('\n=== TESTING DECRYPTION ===');
174
+ logger.debug('Decrypting output 1 to verify commitment matches...');
175
+ const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
176
+ const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
177
+ logger.debug('Original commitment:', outputCommitments[0]);
178
+ logger.debug('Decrypted commitment:', decryptedCommitment1);
179
+ logger.debug('Commitment matches:', outputCommitments[0] === decryptedCommitment1);
180
+ // Create the withdrawal ExtData with real encrypted outputs
181
+ const extData = {
182
+ // it can be any address
183
+ recipient: recipient_ata,
184
+ extAmount: new BN(extAmount),
185
+ encryptedOutput1: encryptedOutput1,
186
+ encryptedOutput2: encryptedOutput2,
187
+ fee: new BN(fee_base_units),
188
+ feeRecipient: feeRecipientTokenAccount,
189
+ mintAddress: mintAddress.toString()
190
+ };
191
+ // Calculate the extDataHash with the encrypted outputs
192
+ const calculatedExtDataHash = getExtDataHash(extData);
193
+ // Create the input for the proof generation
194
+ const input = {
195
+ // Common transaction data
196
+ root: root,
197
+ mintAddress: getMintAddressField(mintAddress), // new mint address
198
+ publicAmount: publicAmountForCircuit.toString(), // Use proper field arithmetic result
199
+ extDataHash: calculatedExtDataHash,
200
+ // Input UTXO data (UTXOs being spent) - ensure all values are in decimal format
201
+ inAmount: inputs.map(x => x.amount.toString(10)),
202
+ inPrivateKey: inputs.map(x => x.keypair.privkey),
203
+ inBlinding: inputs.map(x => x.blinding.toString(10)),
204
+ inPathIndices: inputMerklePathIndices,
205
+ inPathElements: inputMerklePathElements,
206
+ inputNullifier: inputNullifiers, // Use resolved values instead of Promise objects
207
+ // Output UTXO data (UTXOs being created) - ensure all values are in decimal format
208
+ outAmount: outputs.map(x => x.amount.toString(10)),
209
+ outBlinding: outputs.map(x => x.blinding.toString(10)),
210
+ outPubkey: outputs.map(x => x.keypair.pubkey),
211
+ outputCommitment: outputCommitments,
212
+ };
213
+ logger.info('generating ZK proof...');
214
+ // Generate the zero-knowledge proof
215
+ const { proof, publicSignals } = await prove(input, keyBasePath);
216
+ // Parse the proof and public signals into byte arrays
217
+ const proofInBytes = parseProofToBytesArray(proof);
218
+ const inputsInBytes = parseToBytesArray(publicSignals);
219
+ // Create the proof object to submit to the program
220
+ const proofToSubmit = {
221
+ proofA: proofInBytes.proofA,
222
+ proofB: proofInBytes.proofB.flat(),
223
+ proofC: proofInBytes.proofC,
224
+ root: inputsInBytes[0],
225
+ publicAmount: inputsInBytes[1],
226
+ extDataHash: inputsInBytes[2],
227
+ inputNullifiers: [
228
+ inputsInBytes[3],
229
+ inputsInBytes[4]
230
+ ],
231
+ outputCommitments: [
232
+ inputsInBytes[5],
233
+ inputsInBytes[6]
234
+ ],
235
+ };
236
+ // Find PDAs for nullifiers and commitments
237
+ const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
238
+ const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
239
+ // Serialize the proof and extData
240
+ const serializedProof = serializeProofAndExtData(proofToSubmit, extData, true);
241
+ logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
242
+ const [globalConfigPda, globalConfigPdaBump] = await PublicKey.findProgramAddressSync([Buffer.from("global_config")], PROGRAM_ID);
243
+ const treeAta = getAssociatedTokenAddressSync(mintAddress, globalConfigPda, true);
244
+ // Prepare withdraw parameters for indexer backend
245
+ const withdrawParams = {
246
+ serializedProof: serializedProof.toString('base64'),
247
+ treeAccount: treeAccount.toString(),
248
+ nullifier0PDA: nullifier0PDA.toString(),
249
+ nullifier1PDA: nullifier1PDA.toString(),
250
+ nullifier2PDA: nullifier2PDA.toString(),
251
+ nullifier3PDA: nullifier3PDA.toString(),
252
+ treeTokenAccount: treeTokenAccount.toString(),
253
+ globalConfigAccount: globalConfigAccount.toString(),
254
+ recipient: recipient.toString(),
255
+ feeRecipientAccount: FEE_RECIPIENT.toString(),
256
+ extAmount: extAmount,
257
+ fee: fee_base_units,
258
+ lookupTableAddress: ALT_ADDRESS.toString(),
259
+ senderAddress: publicKey.toString(),
260
+ treeAta: treeAta.toString(),
261
+ recipientAta: recipient_ata.toString(),
262
+ mintAddress: mintAddress.toString(),
263
+ feeRecipientTokenAccount: feeRecipientTokenAccount.toString()
264
+ };
265
+ logger.debug('Prepared withdraw parameters for indexer backend');
266
+ // Submit to indexer backend instead of directly to Solana
267
+ logger.info('submitting transaction to relayer...');
268
+ const signature = await submitWithdrawToIndexer(withdrawParams);
269
+ // Wait a moment for the transaction to be confirmed
270
+ logger.info('waiting for transaction confirmation...');
271
+ let retryTimes = 0;
272
+ let itv = 2;
273
+ const encryptedOutputStr = Buffer.from(encryptedOutput1).toString('hex');
274
+ let start = Date.now();
275
+ while (true) {
276
+ console.log(`retryTimes: ${retryTimes}`);
277
+ await new Promise(resolve => setTimeout(resolve, itv * 1000));
278
+ console.log('Fetching updated tree state...');
279
+ let res = await fetch(RELAYER_API_URL + '/utxos/check/' + encryptedOutputStr + '?token=usdc');
280
+ let resJson = await res.json();
281
+ console.log('resJson:', resJson);
282
+ if (resJson.exists) {
283
+ return { isPartial, tx: signature, recipient: recipient.toString(), base_units, fee_base_units };
284
+ }
285
+ if (retryTimes >= 10) {
286
+ throw new Error('Refresh the page to see latest balance.');
287
+ }
288
+ retryTimes++;
289
+ }
290
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "privacycash",
3
- "version": "1.0.16",
3
+ "version": "1.0.18",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "repository": "https://github.com/Privacy-Cash/privacy-cash-sdk",
@@ -12,8 +12,9 @@
12
12
  "type": "module",
13
13
  "scripts": {
14
14
  "build": "tsc",
15
- "test": "vitest run --exclude \"**/__tests__/e2e.test.ts\"",
16
- "teste2e": "vitest run e2e.test.ts"
15
+ "test": "vitest run --exclude \"**/__tests__/e2e.test.ts,**/__tests__/e2espl.test.ts\"",
16
+ "teste2e": "vitest run e2e.test.ts",
17
+ "teste2espl": "vitest run e2espl.test.ts"
17
18
  },
18
19
  "keywords": [],
19
20
  "author": "",
@@ -23,6 +24,7 @@
23
24
  "@ethersproject/keccak256": "^5.8.0",
24
25
  "@ethersproject/sha2": "^5.8.0",
25
26
  "@lightprotocol/hasher.rs": "^0.2.1",
27
+ "@solana/spl-token": "^0.4.14",
26
28
  "@solana/web3.js": "^1.98.4",
27
29
  "@types/bn.js": "^5.2.0",
28
30
  "@types/snarkjs": "^0.7.9",
package/src/config.ts CHANGED
@@ -1,28 +1,21 @@
1
- import { INDEXER_API_URL } from "./utils/constants.js";
1
+ import { RELAYER_API_URL } from "./utils/constants.js";
2
2
 
3
3
  type Config = {
4
4
  withdraw_fee_rate: number
5
5
  withdraw_rent_fee: number
6
6
  deposit_fee_rate: number
7
+ usdc_withdraw_rent_fee: number
7
8
  }
8
9
 
9
10
  let config: Config | undefined
10
11
 
11
12
  export async function getConfig<K extends keyof Config>(key: K): Promise<Config[K]> {
12
13
  if (!config) {
13
- const res = await fetch(INDEXER_API_URL + '/config')
14
- const data = await res.json()
15
-
16
- // check types
17
- if (
18
- typeof data.withdraw_fee_rate !== 'number' ||
19
- typeof data.withdraw_rent_fee !== 'number' ||
20
- typeof data.deposit_fee_rate !== 'number'
21
- ) {
22
- throw new Error("Invalid config received from server")
23
- }
24
-
25
- config = data
14
+ const res = await fetch(RELAYER_API_URL + '/config')
15
+ config = await res.json()
16
+ }
17
+ if (typeof config![key] != 'number') {
18
+ throw new Error(`can not get ${key} from ${RELAYER_API_URL}/config`)
26
19
  }
27
20
  return config![key]
28
21
  }
package/src/deposit.ts CHANGED
@@ -8,7 +8,7 @@ import { MerkleTree } from './utils/merkle_tree.js';
8
8
  import { EncryptionService, serializeProofAndExtData } from './utils/encryption.js';
9
9
  import { Keypair as UtxoKeypair } from './models/keypair.js';
10
10
  import { getUtxos, isUtxoSpent } from './getUtxos.js';
11
- import { FIELD_SIZE, FEE_RECIPIENT, MERKLE_TREE_DEPTH, INDEXER_API_URL, PROGRAM_ID } from './utils/constants.js';
11
+ import { FIELD_SIZE, FEE_RECIPIENT, MERKLE_TREE_DEPTH, RELAYER_API_URL, PROGRAM_ID, ALT_ADDRESS } from './utils/constants.js';
12
12
  import { useExistingALT } from './utils/address_lookup_table.js';
13
13
  import { logger } from './utils/logger.js';
14
14
 
@@ -27,7 +27,7 @@ async function relayDepositToIndexer(signedTransaction: string, publicKey: Publi
27
27
  params.referralWalletAddress = referrer
28
28
  }
29
29
 
30
- const response = await fetch(`${INDEXER_API_URL}/deposit`, {
30
+ const response = await fetch(`${RELAYER_API_URL}/deposit`, {
31
31
  method: 'POST',
32
32
  headers: {
33
33
  'Content-Type': 'application/json',
@@ -83,7 +83,7 @@ export async function deposit({ lightWasm, storage, keyBasePath, publicKey, conn
83
83
  logger.debug(`Wallet balance: ${balance / 1e9} SOL`);
84
84
 
85
85
  if (balance < amount_in_lamports + fee_amount_in_lamports) {
86
- new Error(`Insufficient balance: ${balance / 1e9} SOL. Need at least ${(amount_in_lamports + fee_amount_in_lamports) / LAMPORTS_PER_SOL} SOL.`);
86
+ throw new Error(`Insufficient balance: ${balance / 1e9} SOL. Need at least ${(amount_in_lamports + fee_amount_in_lamports) / LAMPORTS_PER_SOL} SOL.`);
87
87
  }
88
88
 
89
89
  const { treeAccount, treeTokenAccount, globalConfigAccount } = getProgramAccounts()
@@ -348,7 +348,6 @@ export async function deposit({ lightWasm, storage, keyBasePath, publicKey, conn
348
348
  // Address Lookup Table for transaction size optimization
349
349
  logger.debug('Setting up Address Lookup Table...');
350
350
 
351
- const ALT_ADDRESS = new PublicKey('72bpRay17JKp4k8H87p7ieU9C6aRDy5yCqwvtpTN2wuU');
352
351
  const lookupTableAccount = await useExistingALT(connection, ALT_ADDRESS);
353
352
 
354
353
  if (!lookupTableAccount?.value) {
@@ -423,7 +422,7 @@ export async function deposit({ lightWasm, storage, keyBasePath, publicKey, conn
423
422
  logger.debug(`retryTimes: ${retryTimes}`)
424
423
  await new Promise(resolve => setTimeout(resolve, itv * 1000));
425
424
  logger.debug('Fetching updated tree state...');
426
- let res = await fetch(INDEXER_API_URL + '/utxos/check/' + encryptedOutputStr)
425
+ let res = await fetch(RELAYER_API_URL + '/utxos/check/' + encryptedOutputStr)
427
426
  let resJson = await res.json()
428
427
  if (resJson.exists) {
429
428
  logger.debug(`Top up successfully in ${((Date.now() - start) / 1000).toFixed(2)} seconds!`);
@@ -463,11 +462,6 @@ async function checkDepositLimit(connection: Connection) {
463
462
  const maxDepositAmount = new BN(accountInfo.data.slice(4120, 4128), 'le');
464
463
  const bump = accountInfo.data[4128];
465
464
 
466
- console.log('\nšŸ“‹ MerkleTreeAccount Details:');
467
- console.log(`ā”Œā”€ Authority: ${authority.toString()}`);
468
- console.log(`ā”œā”€ Next Index: ${nextIndex.toString()}`);
469
- console.log(`ā”œā”€ Root Index: ${rootIndex.toString()}`);
470
- console.log(`ā”œā”€ Max Deposit Amount: ${maxDepositAmount.toString()} lamports`);
471
465
 
472
466
  // Convert to SOL using BN division to handle large numbers
473
467
  const lamportsPerSol = new BN(1_000_000_000);
@@ -483,7 +477,6 @@ async function checkDepositLimit(connection: Connection) {
483
477
  const fractional = remainder.toNumber() / 1e9;
484
478
  solFormatted = `${maxDepositSol.toString()}${fractional.toFixed(9).substring(1)}`;
485
479
  }
486
- console.log('solFormatted', solFormatted)
487
480
  return Number(solFormatted)
488
481
 
489
482
  } catch (error) {