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