privacycash 1.0.17 → 1.0.19

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 (43) hide show
  1. package/README.md +5 -1
  2. package/__tests__/e2e.test.ts +5 -1
  3. package/__tests__/e2espl.test.ts +73 -0
  4. package/dist/config.d.ts +1 -0
  5. package/dist/config.js +6 -10
  6. package/dist/deposit.js +4 -11
  7. package/dist/depositSPL.d.ts +19 -0
  8. package/dist/depositSPL.js +434 -0
  9. package/dist/exportUtils.d.ts +3 -0
  10. package/dist/exportUtils.js +3 -0
  11. package/dist/getUtxos.d.ts +2 -1
  12. package/dist/getUtxos.js +68 -79
  13. package/dist/getUtxosSPL.d.ts +31 -0
  14. package/dist/getUtxosSPL.js +369 -0
  15. package/dist/index.d.ts +31 -1
  16. package/dist/index.js +73 -3
  17. package/dist/models/utxo.js +10 -1
  18. package/dist/utils/address_lookup_table.d.ts +1 -0
  19. package/dist/utils/address_lookup_table.js +23 -0
  20. package/dist/utils/constants.d.ts +3 -2
  21. package/dist/utils/constants.js +5 -4
  22. package/dist/utils/encryption.d.ts +1 -1
  23. package/dist/utils/encryption.js +5 -3
  24. package/dist/utils/utils.d.ts +3 -2
  25. package/dist/utils/utils.js +26 -6
  26. package/dist/withdraw.js +3 -4
  27. package/dist/withdrawSPL.d.ts +22 -0
  28. package/dist/withdrawSPL.js +289 -0
  29. package/package.json +5 -3
  30. package/src/config.ts +7 -14
  31. package/src/deposit.ts +4 -11
  32. package/src/depositSPL.ts +556 -0
  33. package/src/exportUtils.ts +5 -1
  34. package/src/getUtxos.ts +73 -78
  35. package/src/getUtxosSPL.ts +495 -0
  36. package/src/index.ts +84 -3
  37. package/src/models/utxo.ts +10 -1
  38. package/src/utils/address_lookup_table.ts +54 -6
  39. package/src/utils/constants.ts +7 -5
  40. package/src/utils/encryption.ts +6 -3
  41. package/src/utils/utils.ts +29 -6
  42. package/src/withdraw.ts +4 -6
  43. package/src/withdrawSPL.ts +377 -0
@@ -0,0 +1,377 @@
1
+ import { Connection, Keypair, PublicKey, Transaction, TransactionInstruction, VersionedTransaction } 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 * as hasher from '@lightprotocol/hasher.rs';
6
+ import { Utxo } from './models/utxo.js';
7
+ import { parseProofToBytesArray, parseToBytesArray, prove } from './utils/prover.js';
8
+
9
+ import { ALT_ADDRESS, FEE_RECIPIENT, FIELD_SIZE, RELAYER_API_URL, MERKLE_TREE_DEPTH, PROGRAM_ID } from './utils/constants.js';
10
+ import { EncryptionService, serializeProofAndExtData } from './utils/encryption.js';
11
+ import { fetchMerkleProof, findNullifierPDAs, getProgramAccounts, queryRemoteTreeState, findCrossCheckNullifierPDAs, getMintAddressField, getExtDataHash } from './utils/utils.js';
12
+
13
+ import { getUtxosSPL, isUtxoSpent } from './getUtxosSPL.js';
14
+ import { logger } from './utils/logger.js';
15
+ import { getConfig } from './config.js';
16
+ import { getAssociatedTokenAddressSync, getMint } from '@solana/spl-token';
17
+ // Indexer API endpoint
18
+
19
+
20
+ // Function to submit withdraw request to indexer backend
21
+ async function submitWithdrawToIndexer(params: any): Promise<string> {
22
+ try {
23
+
24
+ const response = await fetch(`${RELAYER_API_URL}/withdraw/spl`, {
25
+ method: 'POST',
26
+ headers: {
27
+ 'Content-Type': 'application/json',
28
+ },
29
+ body: JSON.stringify(params)
30
+ });
31
+
32
+ if (!response.ok) {
33
+ const errorData = await response.json() as { error?: string };
34
+ throw new Error(errorData.error)
35
+ }
36
+
37
+ const result = await response.json() as { signature: string, success: boolean };
38
+ logger.debug('Withdraw request submitted successfully!');
39
+ logger.debug('Response:', result);
40
+
41
+ return result.signature;
42
+ } catch (error) {
43
+ logger.debug('Failed to submit withdraw request to indexer:', typeof error, error);
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ type WithdrawParams = {
49
+ publicKey: PublicKey,
50
+ connection: Connection,
51
+ base_units: number,
52
+ keyBasePath: string,
53
+ encryptionService: EncryptionService,
54
+ lightWasm: hasher.LightWasm,
55
+ recipient: PublicKey,
56
+ mintAddress: PublicKey,
57
+ storage: Storage
58
+ }
59
+
60
+ export async function withdrawSPL({ recipient, lightWasm, storage, publicKey, connection, base_units, encryptionService, keyBasePath, mintAddress }: WithdrawParams) {
61
+ let mintInfo = await getMint(connection, mintAddress)
62
+ let units_per_token = 10 ** mintInfo.decimals
63
+
64
+ let withdraw_fee_rate = await getConfig('withdraw_fee_rate')
65
+ let withdraw_rent_fee = await getConfig('usdc_withdraw_rent_fee')
66
+
67
+ let fee_base_units = Math.floor(base_units * withdraw_fee_rate + units_per_token * withdraw_rent_fee)
68
+ base_units -= fee_base_units
69
+
70
+ if (base_units <= 0) {
71
+ throw new Error('withdraw amount too low')
72
+ }
73
+ let isPartial = false
74
+
75
+ let recipient_ata = getAssociatedTokenAddressSync(
76
+ mintAddress,
77
+ recipient,
78
+ true
79
+ );
80
+
81
+ let feeRecipientTokenAccount = getAssociatedTokenAddressSync(
82
+ mintAddress,
83
+ FEE_RECIPIENT,
84
+ true
85
+ );
86
+ let signerTokenAccount = getAssociatedTokenAddressSync(
87
+ mintAddress,
88
+ publicKey
89
+ );
90
+
91
+
92
+ logger.debug('Encryption key generated from user keypair');
93
+
94
+ // Derive tree account PDA with mint address for SPL (different from SOL version)
95
+ const [treeAccount] = PublicKey.findProgramAddressSync(
96
+ [Buffer.from('merkle_tree'), mintAddress.toBuffer()],
97
+ PROGRAM_ID
98
+ );
99
+
100
+ const { globalConfigAccount, treeTokenAccount } = getProgramAccounts()
101
+
102
+ // Get current tree state
103
+ const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState('usdc');
104
+ logger.debug(`Using tree root: ${root}`);
105
+ logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
106
+
107
+ // Generate a deterministic private key derived from the wallet keypair
108
+ const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
109
+
110
+ // Create a UTXO keypair that will be used for all inputs and outputs
111
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
112
+ logger.debug('Using wallet-derived UTXO keypair for withdrawal');
113
+
114
+ // Generate a deterministic private key derived from the wallet keypair (V2)
115
+ const utxoPrivateKeyV2 = encryptionService.getUtxoPrivateKeyV2();
116
+ const utxoKeypairV2 = new UtxoKeypair(utxoPrivateKeyV2, lightWasm);
117
+
118
+ // Fetch existing UTXOs for this user
119
+ logger.debug('\nFetching existing UTXOs...');
120
+ const mintUtxos = await getUtxosSPL({ connection, publicKey, encryptionService, storage, mintAddress });
121
+
122
+ logger.debug(`Found ${mintUtxos.length} total UTXOs`);
123
+
124
+ // Calculate and log total unspent UTXO balance
125
+ const totalUnspentBalance = mintUtxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
126
+ logger.debug(`Total unspent UTXO balance before: ${totalUnspentBalance.toString()} lamports (${totalUnspentBalance.toNumber() / 1e9} SOL)`);
127
+
128
+ if (mintUtxos.length < 1) {
129
+ throw new Error('Need at least 1 unspent UTXO to perform a withdrawal');
130
+ }
131
+
132
+ // Sort UTXOs by amount in descending order to use the largest ones first
133
+ mintUtxos.sort((a, b) => b.amount.cmp(a.amount));
134
+
135
+ // Use the largest UTXO as first input, and either second largest UTXO or dummy UTXO as second input
136
+ const firstInput = mintUtxos[0];
137
+ const secondInput = mintUtxos.length > 1 ? mintUtxos[1] : new Utxo({
138
+ lightWasm,
139
+ keypair: utxoKeypair,
140
+ amount: '0',
141
+ mintAddress: mintAddress.toString()
142
+ });
143
+
144
+ const inputs = [firstInput, secondInput];
145
+ logger.debug(`firstInput index: ${firstInput.index}, commitment: ${firstInput.getCommitment()}`)
146
+ logger.debug(`secondInput index: ${secondInput.index}, commitment: ${secondInput.getCommitment()}`)
147
+ const totalInputAmount = firstInput.amount.add(secondInput.amount);
148
+ 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'}`);
149
+ if (totalInputAmount.toNumber() === 0) {
150
+ throw new Error('no balance')
151
+ }
152
+ if (totalInputAmount.lt(new BN(base_units + fee_base_units))) {
153
+ isPartial = true
154
+ base_units = totalInputAmount.toNumber()
155
+ base_units -= fee_base_units
156
+ }
157
+
158
+ // Calculate the change amount (what's left after withdrawal and fee)
159
+ const changeAmount = totalInputAmount.sub(new BN(base_units)).sub(new BN(fee_base_units));
160
+ logger.debug(`Withdrawing ${base_units} lamports with ${fee_base_units} fee, ${changeAmount.toString()} as change`);
161
+
162
+ // Get Merkle proofs for both input UTXOs
163
+ const inputMerkleProofs = await Promise.all(
164
+ inputs.map(async (utxo, index) => {
165
+ // For dummy UTXO (amount is 0), use a zero-filled proof
166
+ if (utxo.amount.eq(new BN(0))) {
167
+ return {
168
+ pathElements: [...new Array(MERKLE_TREE_DEPTH).fill("0")],
169
+ pathIndices: Array(MERKLE_TREE_DEPTH).fill(0)
170
+ };
171
+ }
172
+ // For real UTXOs, fetch the proof from API
173
+ const commitment = await utxo.getCommitment();
174
+ return fetchMerkleProof(commitment, 'usdc');
175
+ })
176
+ );
177
+
178
+ // Extract path elements and indices
179
+ const inputMerklePathElements = inputMerkleProofs.map(proof => proof.pathElements);
180
+ const inputMerklePathIndices = inputs.map(utxo => utxo.index || 0);
181
+
182
+ // Create outputs: first output is change, second is dummy (required by protocol)
183
+ const outputs = [
184
+ new Utxo({
185
+ lightWasm,
186
+ amount: changeAmount.toString(),
187
+ keypair: utxoKeypairV2,
188
+ index: currentNextIndex,
189
+ mintAddress: mintAddress.toString()
190
+ }), // Change output
191
+ new Utxo({
192
+ lightWasm,
193
+ amount: '0',
194
+ keypair: utxoKeypairV2,
195
+ index: currentNextIndex + 1,
196
+ mintAddress: mintAddress.toString()
197
+ }) // Empty UTXO
198
+ ];
199
+
200
+ // For withdrawals, extAmount is negative (funds leaving the system)
201
+ const extAmount = -base_units;
202
+ const publicAmountForCircuit = new BN(extAmount).sub(new BN(fee_base_units)).add(FIELD_SIZE).mod(FIELD_SIZE);
203
+ logger.debug(`Public amount calculation: (${extAmount} - ${fee_base_units} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
204
+
205
+ // Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
206
+ const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
207
+ const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
208
+ logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
209
+
210
+ // Convert to circuit-compatible format
211
+ const publicAmountCircuitResult = sumIns.add(publicAmountForCircuit).mod(FIELD_SIZE);
212
+ logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
213
+ logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
214
+ logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
215
+
216
+ // Generate nullifiers and commitments
217
+ const inputNullifiers = await Promise.all(inputs.map(x => x.getNullifier()));
218
+ const outputCommitments = await Promise.all(outputs.map(x => x.getCommitment()));
219
+
220
+ // Save original commitment and nullifier values for verification
221
+ logger.debug('\n=== UTXO VALIDATION ===');
222
+ logger.debug('Output 0 Commitment:', outputCommitments[0]);
223
+ logger.debug('Output 1 Commitment:', outputCommitments[1]);
224
+
225
+ // Encrypt the UTXO data using a compact format that includes the keypair
226
+ logger.debug('\nEncrypting UTXOs with keypair data...');
227
+ const encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
228
+ const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
229
+
230
+ logger.debug(`\nOutput[0] (change):`);
231
+ await outputs[0].log();
232
+ logger.debug(`\nOutput[1] (empty):`);
233
+ await outputs[1].log();
234
+ logger.debug(`Encrypted output 1: ${encryptedOutput1.toString('hex')}`)
235
+ logger.debug(`Encrypted output 2: ${encryptedOutput2.toString('hex')}`)
236
+ logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
237
+ logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
238
+ logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
239
+
240
+ // Test decryption to verify commitment values match
241
+ logger.debug('\n=== TESTING DECRYPTION ===');
242
+ logger.debug('Decrypting output 1 to verify commitment matches...');
243
+ const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
244
+ const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
245
+ logger.debug('Original commitment:', outputCommitments[0]);
246
+ logger.debug('Decrypted commitment:', decryptedCommitment1);
247
+ logger.debug('Commitment matches:', outputCommitments[0] === decryptedCommitment1);
248
+
249
+ // Create the withdrawal ExtData with real encrypted outputs
250
+ const extData = {
251
+ // it can be any address
252
+ recipient: recipient_ata,
253
+ extAmount: new BN(extAmount),
254
+ encryptedOutput1: encryptedOutput1,
255
+ encryptedOutput2: encryptedOutput2,
256
+ fee: new BN(fee_base_units),
257
+ feeRecipient: feeRecipientTokenAccount,
258
+ mintAddress: mintAddress.toString()
259
+ };
260
+ // Calculate the extDataHash with the encrypted outputs
261
+ const calculatedExtDataHash = getExtDataHash(extData);
262
+
263
+ // Create the input for the proof generation
264
+ const input = {
265
+ // Common transaction data
266
+ root: root,
267
+ mintAddress: getMintAddressField(mintAddress),// new mint address
268
+ publicAmount: publicAmountForCircuit.toString(), // Use proper field arithmetic result
269
+ extDataHash: calculatedExtDataHash,
270
+
271
+ // Input UTXO data (UTXOs being spent) - ensure all values are in decimal format
272
+ inAmount: inputs.map(x => x.amount.toString(10)),
273
+ inPrivateKey: inputs.map(x => x.keypair.privkey),
274
+ inBlinding: inputs.map(x => x.blinding.toString(10)),
275
+ inPathIndices: inputMerklePathIndices,
276
+ inPathElements: inputMerklePathElements,
277
+ inputNullifier: inputNullifiers, // Use resolved values instead of Promise objects
278
+
279
+ // Output UTXO data (UTXOs being created) - ensure all values are in decimal format
280
+ outAmount: outputs.map(x => x.amount.toString(10)),
281
+ outBlinding: outputs.map(x => x.blinding.toString(10)),
282
+ outPubkey: outputs.map(x => x.keypair.pubkey),
283
+ outputCommitment: outputCommitments,
284
+ };
285
+
286
+ logger.info('generating ZK proof...')
287
+
288
+ // Generate the zero-knowledge proof
289
+ const { proof, publicSignals } = await prove(input, keyBasePath);
290
+
291
+ // Parse the proof and public signals into byte arrays
292
+ const proofInBytes = parseProofToBytesArray(proof);
293
+ const inputsInBytes = parseToBytesArray(publicSignals);
294
+
295
+ // Create the proof object to submit to the program
296
+ const proofToSubmit = {
297
+ proofA: proofInBytes.proofA,
298
+ proofB: proofInBytes.proofB.flat(),
299
+ proofC: proofInBytes.proofC,
300
+ root: inputsInBytes[0],
301
+ publicAmount: inputsInBytes[1],
302
+ extDataHash: inputsInBytes[2],
303
+ inputNullifiers: [
304
+ inputsInBytes[3],
305
+ inputsInBytes[4]
306
+ ],
307
+ outputCommitments: [
308
+ inputsInBytes[5],
309
+ inputsInBytes[6]
310
+ ],
311
+ };
312
+
313
+ // Find PDAs for nullifiers and commitments
314
+ const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
315
+ const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
316
+
317
+ // Serialize the proof and extData
318
+ const serializedProof = serializeProofAndExtData(proofToSubmit, extData, true);
319
+ logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
320
+
321
+ const [globalConfigPda, globalConfigPdaBump] = await PublicKey.findProgramAddressSync(
322
+ [Buffer.from("global_config")],
323
+ PROGRAM_ID
324
+ );
325
+ const treeAta = getAssociatedTokenAddressSync(mintAddress, globalConfigPda, true);
326
+
327
+ // Prepare withdraw parameters for indexer backend
328
+ const withdrawParams = {
329
+ serializedProof: serializedProof.toString('base64'),
330
+ treeAccount: treeAccount.toString(),
331
+ nullifier0PDA: nullifier0PDA.toString(),
332
+ nullifier1PDA: nullifier1PDA.toString(),
333
+ nullifier2PDA: nullifier2PDA.toString(),
334
+ nullifier3PDA: nullifier3PDA.toString(),
335
+ treeTokenAccount: treeTokenAccount.toString(),
336
+ globalConfigAccount: globalConfigAccount.toString(),
337
+ recipient: recipient.toString(),
338
+ feeRecipientAccount: FEE_RECIPIENT.toString(),
339
+ extAmount: extAmount,
340
+ fee: fee_base_units,
341
+ lookupTableAddress: ALT_ADDRESS.toString(),
342
+ senderAddress: publicKey.toString(),
343
+ treeAta: treeAta.toString(),
344
+ recipientAta: recipient_ata.toString(),
345
+ mintAddress: mintAddress.toString(),
346
+ feeRecipientTokenAccount: feeRecipientTokenAccount.toString()
347
+ };
348
+
349
+
350
+ logger.debug('Prepared withdraw parameters for indexer backend');
351
+
352
+ // Submit to indexer backend instead of directly to Solana
353
+ logger.info('submitting transaction to relayer...')
354
+ const signature = await submitWithdrawToIndexer(withdrawParams);
355
+ // Wait a moment for the transaction to be confirmed
356
+ logger.info('waiting for transaction confirmation...')
357
+ let retryTimes = 0
358
+ let itv = 2
359
+ const encryptedOutputStr = Buffer.from(encryptedOutput1).toString('hex')
360
+ let start = Date.now()
361
+ while (true) {
362
+ console.log(`retryTimes: ${retryTimes}`)
363
+ await new Promise(resolve => setTimeout(resolve, itv * 1000));
364
+ console.log('Fetching updated tree state...');
365
+ let res = await fetch(RELAYER_API_URL + '/utxos/check/' + encryptedOutputStr + '?token=usdc')
366
+ let resJson = await res.json()
367
+ console.log('resJson:', resJson)
368
+ if (resJson.exists) {
369
+ return { isPartial, tx: signature, recipient: recipient.toString(), base_units, fee_base_units }
370
+ }
371
+ if (retryTimes >= 10) {
372
+ throw new Error('Refresh the page to see latest balance.')
373
+ }
374
+ retryTimes++
375
+ }
376
+
377
+ }