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,379 @@
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, DEPLOYER_ID, 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
+ logger.debug(`Deployer wallet: ${DEPLOYER_ID.toString()}`);
95
+
96
+ // Derive tree account PDA with mint address for SPL (different from SOL version)
97
+ const [treeAccount] = PublicKey.findProgramAddressSync(
98
+ [Buffer.from('merkle_tree'), mintAddress.toBuffer()],
99
+ PROGRAM_ID
100
+ );
101
+
102
+ const { globalConfigAccount, treeTokenAccount } = getProgramAccounts()
103
+
104
+ // Get current tree state
105
+ const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState('usdc');
106
+ logger.debug(`Using tree root: ${root}`);
107
+ logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
108
+
109
+ // Generate a deterministic private key derived from the wallet keypair
110
+ const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
111
+
112
+ // Create a UTXO keypair that will be used for all inputs and outputs
113
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
114
+ logger.debug('Using wallet-derived UTXO keypair for withdrawal');
115
+
116
+ // Generate a deterministic private key derived from the wallet keypair (V2)
117
+ const utxoPrivateKeyV2 = encryptionService.getUtxoPrivateKeyV2();
118
+ const utxoKeypairV2 = new UtxoKeypair(utxoPrivateKeyV2, lightWasm);
119
+
120
+ // Fetch existing UTXOs for this user
121
+ logger.debug('\nFetching existing UTXOs...');
122
+ const mintUtxos = await getUtxosSPL({ connection, publicKey, encryptionService, storage, mintAddress });
123
+
124
+ logger.debug(`Found ${mintUtxos.length} total UTXOs`);
125
+
126
+ // Calculate and log total unspent UTXO balance
127
+ const totalUnspentBalance = mintUtxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
128
+ logger.debug(`Total unspent UTXO balance before: ${totalUnspentBalance.toString()} lamports (${totalUnspentBalance.toNumber() / 1e9} SOL)`);
129
+
130
+ if (mintUtxos.length < 1) {
131
+ throw new Error('Need at least 1 unspent UTXO to perform a withdrawal');
132
+ }
133
+
134
+ // Sort UTXOs by amount in descending order to use the largest ones first
135
+ mintUtxos.sort((a, b) => b.amount.cmp(a.amount));
136
+
137
+ // Use the largest UTXO as first input, and either second largest UTXO or dummy UTXO as second input
138
+ const firstInput = mintUtxos[0];
139
+ const secondInput = mintUtxos.length > 1 ? mintUtxos[1] : new Utxo({
140
+ lightWasm,
141
+ keypair: utxoKeypair,
142
+ amount: '0',
143
+ mintAddress: mintAddress.toString()
144
+ });
145
+
146
+ const inputs = [firstInput, secondInput];
147
+ logger.debug(`firstInput index: ${firstInput.index}, commitment: ${firstInput.getCommitment()}`)
148
+ logger.debug(`secondInput index: ${secondInput.index}, commitment: ${secondInput.getCommitment()}`)
149
+ const totalInputAmount = firstInput.amount.add(secondInput.amount);
150
+ 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'}`);
151
+ if (totalInputAmount.toNumber() === 0) {
152
+ throw new Error('no balance')
153
+ }
154
+ if (totalInputAmount.lt(new BN(base_units + fee_base_units))) {
155
+ isPartial = true
156
+ base_units = totalInputAmount.toNumber()
157
+ base_units -= fee_base_units
158
+ }
159
+
160
+ // Calculate the change amount (what's left after withdrawal and fee)
161
+ const changeAmount = totalInputAmount.sub(new BN(base_units)).sub(new BN(fee_base_units));
162
+ logger.debug(`Withdrawing ${base_units} lamports with ${fee_base_units} fee, ${changeAmount.toString()} as change`);
163
+
164
+ // Get Merkle proofs for both input UTXOs
165
+ const inputMerkleProofs = await Promise.all(
166
+ inputs.map(async (utxo, index) => {
167
+ // For dummy UTXO (amount is 0), use a zero-filled proof
168
+ if (utxo.amount.eq(new BN(0))) {
169
+ return {
170
+ pathElements: [...new Array(MERKLE_TREE_DEPTH).fill("0")],
171
+ pathIndices: Array(MERKLE_TREE_DEPTH).fill(0)
172
+ };
173
+ }
174
+ // For real UTXOs, fetch the proof from API
175
+ const commitment = await utxo.getCommitment();
176
+ return fetchMerkleProof(commitment, 'usdc');
177
+ })
178
+ );
179
+
180
+ // Extract path elements and indices
181
+ const inputMerklePathElements = inputMerkleProofs.map(proof => proof.pathElements);
182
+ const inputMerklePathIndices = inputs.map(utxo => utxo.index || 0);
183
+
184
+ // Create outputs: first output is change, second is dummy (required by protocol)
185
+ const outputs = [
186
+ new Utxo({
187
+ lightWasm,
188
+ amount: changeAmount.toString(),
189
+ keypair: utxoKeypairV2,
190
+ index: currentNextIndex,
191
+ mintAddress: mintAddress.toString()
192
+ }), // Change output
193
+ new Utxo({
194
+ lightWasm,
195
+ amount: '0',
196
+ keypair: utxoKeypairV2,
197
+ index: currentNextIndex + 1,
198
+ mintAddress: mintAddress.toString()
199
+ }) // Empty UTXO
200
+ ];
201
+
202
+ // For withdrawals, extAmount is negative (funds leaving the system)
203
+ const extAmount = -base_units;
204
+ const publicAmountForCircuit = new BN(extAmount).sub(new BN(fee_base_units)).add(FIELD_SIZE).mod(FIELD_SIZE);
205
+ logger.debug(`Public amount calculation: (${extAmount} - ${fee_base_units} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
206
+
207
+ // Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
208
+ const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
209
+ const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
210
+ logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
211
+
212
+ // Convert to circuit-compatible format
213
+ const publicAmountCircuitResult = sumIns.add(publicAmountForCircuit).mod(FIELD_SIZE);
214
+ logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
215
+ logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
216
+ logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
217
+
218
+ // Generate nullifiers and commitments
219
+ const inputNullifiers = await Promise.all(inputs.map(x => x.getNullifier()));
220
+ const outputCommitments = await Promise.all(outputs.map(x => x.getCommitment()));
221
+
222
+ // Save original commitment and nullifier values for verification
223
+ logger.debug('\n=== UTXO VALIDATION ===');
224
+ logger.debug('Output 0 Commitment:', outputCommitments[0]);
225
+ logger.debug('Output 1 Commitment:', outputCommitments[1]);
226
+
227
+ // Encrypt the UTXO data using a compact format that includes the keypair
228
+ logger.debug('\nEncrypting UTXOs with keypair data...');
229
+ const encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
230
+ const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
231
+
232
+ logger.debug(`\nOutput[0] (change):`);
233
+ await outputs[0].log();
234
+ logger.debug(`\nOutput[1] (empty):`);
235
+ await outputs[1].log();
236
+ logger.debug(`Encrypted output 1: ${encryptedOutput1.toString('hex')}`)
237
+ logger.debug(`Encrypted output 2: ${encryptedOutput2.toString('hex')}`)
238
+ logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
239
+ logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
240
+ logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
241
+
242
+ // Test decryption to verify commitment values match
243
+ logger.debug('\n=== TESTING DECRYPTION ===');
244
+ logger.debug('Decrypting output 1 to verify commitment matches...');
245
+ const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
246
+ const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
247
+ logger.debug('Original commitment:', outputCommitments[0]);
248
+ logger.debug('Decrypted commitment:', decryptedCommitment1);
249
+ logger.debug('Commitment matches:', outputCommitments[0] === decryptedCommitment1);
250
+
251
+ // Create the withdrawal ExtData with real encrypted outputs
252
+ const extData = {
253
+ // it can be any address
254
+ recipient: recipient_ata,
255
+ extAmount: new BN(extAmount),
256
+ encryptedOutput1: encryptedOutput1,
257
+ encryptedOutput2: encryptedOutput2,
258
+ fee: new BN(fee_base_units),
259
+ feeRecipient: feeRecipientTokenAccount,
260
+ mintAddress: mintAddress.toString()
261
+ };
262
+ // Calculate the extDataHash with the encrypted outputs
263
+ const calculatedExtDataHash = getExtDataHash(extData);
264
+
265
+ // Create the input for the proof generation
266
+ const input = {
267
+ // Common transaction data
268
+ root: root,
269
+ mintAddress: getMintAddressField(mintAddress),// new mint address
270
+ publicAmount: publicAmountForCircuit.toString(), // Use proper field arithmetic result
271
+ extDataHash: calculatedExtDataHash,
272
+
273
+ // Input UTXO data (UTXOs being spent) - ensure all values are in decimal format
274
+ inAmount: inputs.map(x => x.amount.toString(10)),
275
+ inPrivateKey: inputs.map(x => x.keypair.privkey),
276
+ inBlinding: inputs.map(x => x.blinding.toString(10)),
277
+ inPathIndices: inputMerklePathIndices,
278
+ inPathElements: inputMerklePathElements,
279
+ inputNullifier: inputNullifiers, // Use resolved values instead of Promise objects
280
+
281
+ // Output UTXO data (UTXOs being created) - ensure all values are in decimal format
282
+ outAmount: outputs.map(x => x.amount.toString(10)),
283
+ outBlinding: outputs.map(x => x.blinding.toString(10)),
284
+ outPubkey: outputs.map(x => x.keypair.pubkey),
285
+ outputCommitment: outputCommitments,
286
+ };
287
+
288
+ logger.info('generating ZK proof...')
289
+
290
+ // Generate the zero-knowledge proof
291
+ const { proof, publicSignals } = await prove(input, keyBasePath);
292
+
293
+ // Parse the proof and public signals into byte arrays
294
+ const proofInBytes = parseProofToBytesArray(proof);
295
+ const inputsInBytes = parseToBytesArray(publicSignals);
296
+
297
+ // Create the proof object to submit to the program
298
+ const proofToSubmit = {
299
+ proofA: proofInBytes.proofA,
300
+ proofB: proofInBytes.proofB.flat(),
301
+ proofC: proofInBytes.proofC,
302
+ root: inputsInBytes[0],
303
+ publicAmount: inputsInBytes[1],
304
+ extDataHash: inputsInBytes[2],
305
+ inputNullifiers: [
306
+ inputsInBytes[3],
307
+ inputsInBytes[4]
308
+ ],
309
+ outputCommitments: [
310
+ inputsInBytes[5],
311
+ inputsInBytes[6]
312
+ ],
313
+ };
314
+
315
+ // Find PDAs for nullifiers and commitments
316
+ const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
317
+ const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
318
+
319
+ // Serialize the proof and extData
320
+ const serializedProof = serializeProofAndExtData(proofToSubmit, extData, true);
321
+ logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
322
+
323
+ const [globalConfigPda, globalConfigPdaBump] = await PublicKey.findProgramAddressSync(
324
+ [Buffer.from("global_config")],
325
+ PROGRAM_ID
326
+ );
327
+ const treeAta = getAssociatedTokenAddressSync(mintAddress, globalConfigPda, true);
328
+
329
+ // Prepare withdraw parameters for indexer backend
330
+ const withdrawParams = {
331
+ serializedProof: serializedProof.toString('base64'),
332
+ treeAccount: treeAccount.toString(),
333
+ nullifier0PDA: nullifier0PDA.toString(),
334
+ nullifier1PDA: nullifier1PDA.toString(),
335
+ nullifier2PDA: nullifier2PDA.toString(),
336
+ nullifier3PDA: nullifier3PDA.toString(),
337
+ treeTokenAccount: treeTokenAccount.toString(),
338
+ globalConfigAccount: globalConfigAccount.toString(),
339
+ recipient: recipient.toString(),
340
+ feeRecipientAccount: FEE_RECIPIENT.toString(),
341
+ extAmount: extAmount,
342
+ fee: fee_base_units,
343
+ lookupTableAddress: ALT_ADDRESS.toString(),
344
+ senderAddress: publicKey.toString(),
345
+ treeAta: treeAta.toString(),
346
+ recipientAta: recipient_ata.toString(),
347
+ mintAddress: mintAddress.toString(),
348
+ feeRecipientTokenAccount: feeRecipientTokenAccount.toString()
349
+ };
350
+
351
+
352
+ logger.debug('Prepared withdraw parameters for indexer backend');
353
+
354
+ // Submit to indexer backend instead of directly to Solana
355
+ logger.info('submitting transaction to relayer...')
356
+ const signature = await submitWithdrawToIndexer(withdrawParams);
357
+ // Wait a moment for the transaction to be confirmed
358
+ logger.info('waiting for transaction confirmation...')
359
+ let retryTimes = 0
360
+ let itv = 2
361
+ const encryptedOutputStr = Buffer.from(encryptedOutput1).toString('hex')
362
+ let start = Date.now()
363
+ while (true) {
364
+ console.log(`retryTimes: ${retryTimes}`)
365
+ await new Promise(resolve => setTimeout(resolve, itv * 1000));
366
+ console.log('Fetching updated tree state...');
367
+ let res = await fetch(RELAYER_API_URL + '/utxos/check/' + encryptedOutputStr + '?token=usdc')
368
+ let resJson = await res.json()
369
+ console.log('resJson:', resJson)
370
+ if (resJson.exists) {
371
+ return { isPartial, tx: signature, recipient: recipient.toString(), base_units, fee_base_units }
372
+ }
373
+ if (retryTimes >= 10) {
374
+ throw new Error('Refresh the page to see latest balance.')
375
+ }
376
+ retryTimes++
377
+ }
378
+
379
+ }