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,294 @@
1
+ import { PublicKey } from '@solana/web3.js';
2
+ import BN from 'bn.js';
3
+ import { Keypair as UtxoKeypair } from './models/keypair.js';
4
+ import { WasmFactory } from '@lightprotocol/hasher.rs';
5
+ //@ts-ignore
6
+ import * as ffjavascript from 'ffjavascript';
7
+ import { FETCH_UTXOS_GROUP_SIZE, RELAYER_API_URL, LSK_ENCRYPTED_OUTPUTS, LSK_FETCH_OFFSET, PROGRAM_ID } from './utils/constants.js';
8
+ import { logger } from './utils/logger.js';
9
+ // Use type assertion for the utility functions (same pattern as in get_verification_keys.ts)
10
+ const utils = ffjavascript.utils;
11
+ const { unstringifyBigInts, leInt2Buff } = utils;
12
+ function sleep(ms) {
13
+ return new Promise(resolve => setTimeout(() => {
14
+ resolve('ok');
15
+ }, ms));
16
+ }
17
+ export function localstorageKey(key) {
18
+ return PROGRAM_ID.toString().substring(0, 6) + key.toString();
19
+ }
20
+ let roundStartIndex = 0;
21
+ let decryptionTaskFinished = 0;
22
+ /**
23
+ * Fetch and decrypt all UTXOs for a user
24
+ * @param signed The user's signature
25
+ * @param connection Solana connection to fetch on-chain commitment accounts
26
+ * @param setStatus A global state updator. Set live status message showing on webpage
27
+ * @returns Array of decrypted UTXOs that belong to the user
28
+ */
29
+ export async function getUtxos({ publicKey, connection, encryptionService, storage, abortSignal, offset }) {
30
+ let valid_utxos = [];
31
+ let valid_strings = [];
32
+ let history_indexes = [];
33
+ let offsetStr = storage.getItem(LSK_FETCH_OFFSET + localstorageKey(publicKey));
34
+ if (offsetStr) {
35
+ roundStartIndex = Number(offsetStr);
36
+ }
37
+ else {
38
+ roundStartIndex = 0;
39
+ }
40
+ decryptionTaskFinished = 0;
41
+ if (!offset) {
42
+ offset = 0;
43
+ }
44
+ roundStartIndex = Math.max(offset, roundStartIndex);
45
+ while (true) {
46
+ if (abortSignal?.aborted) {
47
+ throw new Error('aborted');
48
+ }
49
+ let offsetStr = storage.getItem(LSK_FETCH_OFFSET + localstorageKey(publicKey));
50
+ let fetch_utxo_offset = offsetStr ? Number(offsetStr) : 0;
51
+ if (offset) {
52
+ fetch_utxo_offset = Math.max(offset, fetch_utxo_offset);
53
+ }
54
+ let fetch_utxo_end = fetch_utxo_offset + FETCH_UTXOS_GROUP_SIZE;
55
+ let fetch_utxo_url = `${RELAYER_API_URL}/utxos/range?start=${fetch_utxo_offset}&end=${fetch_utxo_end}`;
56
+ let fetched = await fetchUserUtxos({ publicKey, connection, url: fetch_utxo_url, encryptionService, storage, initOffset: offset });
57
+ let am = 0;
58
+ const nonZeroUtxos = [];
59
+ const nonZeroEncrypted = [];
60
+ for (let [k, utxo] of fetched.utxos.entries()) {
61
+ history_indexes.push(utxo.index);
62
+ if (utxo.amount.toNumber() > 0) {
63
+ nonZeroUtxos.push(utxo);
64
+ nonZeroEncrypted.push(fetched.encryptedOutputs[k]);
65
+ }
66
+ }
67
+ if (nonZeroUtxos.length > 0) {
68
+ const spentFlags = await areUtxosSpent(connection, nonZeroUtxos);
69
+ for (let i = 0; i < nonZeroUtxos.length; i++) {
70
+ if (!spentFlags[i]) {
71
+ logger.debug(`found unspent encrypted_output ${nonZeroEncrypted[i]}`);
72
+ am += nonZeroUtxos[i].amount.toNumber();
73
+ valid_utxos.push(nonZeroUtxos[i]);
74
+ valid_strings.push(nonZeroEncrypted[i]);
75
+ }
76
+ }
77
+ }
78
+ storage.setItem(LSK_FETCH_OFFSET + localstorageKey(publicKey), (fetch_utxo_offset + fetched.len).toString());
79
+ if (!fetched.hasMore) {
80
+ break;
81
+ }
82
+ await sleep(20);
83
+ }
84
+ // get history index
85
+ let historyKey = 'tradeHistory' + localstorageKey(publicKey);
86
+ let rec = storage.getItem(historyKey);
87
+ let recIndexes = [];
88
+ if (rec?.length) {
89
+ recIndexes = rec.split(',').map(n => Number(n));
90
+ }
91
+ if (recIndexes.length) {
92
+ history_indexes = [...history_indexes, ...recIndexes];
93
+ }
94
+ let unique_history_indexes = Array.from(new Set(history_indexes));
95
+ let top20 = unique_history_indexes.sort((a, b) => b - a).slice(0, 20);
96
+ if (top20.length) {
97
+ storage.setItem(historyKey, top20.join(','));
98
+ }
99
+ // store valid strings
100
+ logger.debug(`valid_strings len before set: ${valid_strings.length}`);
101
+ valid_strings = [...new Set(valid_strings)];
102
+ logger.debug(`valid_strings len after set: ${valid_strings.length}`);
103
+ storage.setItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(publicKey), JSON.stringify(valid_strings));
104
+ return valid_utxos;
105
+ }
106
+ async function fetchUserUtxos({ publicKey, connection, url, storage, encryptionService, initOffset }) {
107
+ const lightWasm = await WasmFactory.getInstance();
108
+ // Derive the UTXO keypair from the wallet keypair
109
+ const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
110
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
111
+ // Fetch all UTXOs from the API
112
+ let encryptedOutputs = [];
113
+ logger.debug('fetching utxo data', url);
114
+ let res = await fetch(url);
115
+ if (!res.ok)
116
+ throw new Error(`HTTP error! status: ${res.status}`);
117
+ const data = await res.json();
118
+ logger.debug('got utxo data');
119
+ if (!data) {
120
+ throw new Error('API returned empty data');
121
+ }
122
+ else if (Array.isArray(data)) {
123
+ // Handle the case where the API returns an array of UTXOs
124
+ const utxos = data;
125
+ // Extract encrypted outputs from the array of UTXOs
126
+ encryptedOutputs = utxos
127
+ .filter(utxo => utxo.encrypted_output)
128
+ .map(utxo => utxo.encrypted_output);
129
+ }
130
+ else if (typeof data === 'object' && data.encrypted_outputs) {
131
+ // Handle the case where the API returns an object with encrypted_outputs array
132
+ const apiResponse = data;
133
+ encryptedOutputs = apiResponse.encrypted_outputs;
134
+ }
135
+ else {
136
+ throw new Error(`API returned unexpected data format: ${JSON.stringify(data).substring(0, 100)}...`);
137
+ }
138
+ // Try to decrypt each encrypted output
139
+ const myUtxos = [];
140
+ const myEncryptedOutputs = [];
141
+ let decryptionAttempts = 0;
142
+ let successfulDecryptions = 0;
143
+ let cachedStringNum = 0;
144
+ let cachedString = storage.getItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(publicKey));
145
+ if (cachedString) {
146
+ cachedStringNum = JSON.parse(cachedString).length;
147
+ }
148
+ let decryptionTaskTotal = data.total + cachedStringNum - roundStartIndex;
149
+ let batchRes = await decrypt_outputs(encryptedOutputs, encryptionService, utxoKeypair, lightWasm);
150
+ decryptionTaskFinished += encryptedOutputs.length;
151
+ logger.debug('batchReslen', batchRes.length);
152
+ for (let i = 0; i < batchRes.length; i++) {
153
+ let dres = batchRes[i];
154
+ if (dres.status == 'decrypted' && dres.utxo) {
155
+ myUtxos.push(dres.utxo);
156
+ myEncryptedOutputs.push(dres.encryptedOutput);
157
+ }
158
+ }
159
+ logger.info(`(decrypting cached utxo: ${decryptionTaskFinished + 1}/${decryptionTaskTotal}...)`);
160
+ // check cached string when no more fetching tasks
161
+ if (!data.hasMore) {
162
+ if (cachedString) {
163
+ let cachedEncryptedOutputs = JSON.parse(cachedString);
164
+ if (decryptionTaskFinished % 100 == 0) {
165
+ logger.info(`(decrypting cached utxo: ${decryptionTaskFinished + 1}/${decryptionTaskTotal}...)`);
166
+ }
167
+ let batchRes = await decrypt_outputs(cachedEncryptedOutputs, encryptionService, utxoKeypair, lightWasm);
168
+ decryptionTaskFinished += cachedEncryptedOutputs.length;
169
+ logger.debug('cachedbatchReslen', batchRes.length, ' source', cachedEncryptedOutputs.length);
170
+ for (let i = 0; i < batchRes.length; i++) {
171
+ let dres = batchRes[i];
172
+ if (dres.status == 'decrypted' && dres.utxo) {
173
+ myUtxos.push(dres.utxo);
174
+ myEncryptedOutputs.push(dres.encryptedOutput);
175
+ }
176
+ }
177
+ }
178
+ }
179
+ return { encryptedOutputs: myEncryptedOutputs, utxos: myUtxos, hasMore: data.hasMore, len: encryptedOutputs.length };
180
+ }
181
+ /**
182
+ * Check if a UTXO has been spent
183
+ * @param connection Solana connection
184
+ * @param utxo The UTXO to check
185
+ * @returns Promise<boolean> true if spent, false if unspent
186
+ */
187
+ export async function isUtxoSpent(connection, utxo) {
188
+ try {
189
+ // Get the nullifier for this UTXO
190
+ const nullifier = await utxo.getNullifier();
191
+ logger.debug(`Checking if UTXO with nullifier ${nullifier} is spent`);
192
+ // Convert decimal nullifier string to byte array (same format as in proofs)
193
+ // This matches how commitments are handled and how the Rust code expects the seeds
194
+ const nullifierBytes = Array.from(leInt2Buff(unstringifyBigInts(nullifier), 32)).reverse();
195
+ // Try nullifier0 seed
196
+ const [nullifier0PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier0"), Buffer.from(nullifierBytes)], PROGRAM_ID);
197
+ logger.debug(`Derived nullifier0 PDA: ${nullifier0PDA.toBase58()}`);
198
+ const nullifier0Account = await connection.getAccountInfo(nullifier0PDA);
199
+ if (nullifier0Account !== null) {
200
+ logger.debug(`UTXO is spent (nullifier0 account exists)`);
201
+ return true;
202
+ }
203
+ const [nullifier1PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier1"), Buffer.from(nullifierBytes)], PROGRAM_ID);
204
+ logger.debug(`Derived nullifier1 PDA: ${nullifier1PDA.toBase58()}`);
205
+ const nullifier1Account = await connection.getAccountInfo(nullifier1PDA);
206
+ if (nullifier1Account !== null) {
207
+ logger.debug(`UTXO is spent (nullifier1 account exists)`);
208
+ return true;
209
+ }
210
+ return false;
211
+ }
212
+ catch (error) {
213
+ console.error('Error checking if UTXO is spent:', error);
214
+ await new Promise(resolve => setTimeout(resolve, 3000));
215
+ return await isUtxoSpent(connection, utxo);
216
+ }
217
+ }
218
+ async function areUtxosSpent(connection, utxos) {
219
+ try {
220
+ const allPDAs = [];
221
+ for (let i = 0; i < utxos.length; i++) {
222
+ const utxo = utxos[i];
223
+ const nullifier = await utxo.getNullifier();
224
+ const nullifierBytes = Array.from(leInt2Buff(unstringifyBigInts(nullifier), 32)).reverse();
225
+ const [nullifier0PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier0"), Buffer.from(nullifierBytes)], PROGRAM_ID);
226
+ const [nullifier1PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier1"), Buffer.from(nullifierBytes)], PROGRAM_ID);
227
+ allPDAs.push({ utxoIndex: i, pda: nullifier0PDA });
228
+ allPDAs.push({ utxoIndex: i, pda: nullifier1PDA });
229
+ }
230
+ const results = await connection.getMultipleAccountsInfo(allPDAs.map((x) => x.pda));
231
+ const spentFlags = new Array(utxos.length).fill(false);
232
+ for (let i = 0; i < allPDAs.length; i++) {
233
+ if (results[i] !== null) {
234
+ spentFlags[allPDAs[i].utxoIndex] = true;
235
+ }
236
+ }
237
+ return spentFlags;
238
+ }
239
+ catch (error) {
240
+ console.error("Error checking if UTXOs are spent:", error);
241
+ await new Promise((resolve) => setTimeout(resolve, 3000));
242
+ return await areUtxosSpent(connection, utxos);
243
+ }
244
+ }
245
+ // Calculate total balance
246
+ export function getBalanceFromUtxos(utxos) {
247
+ const totalBalance = utxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
248
+ // const LAMPORTS_PER_SOL = new BN(1_000_000_000);
249
+ // const balanceInSol = totalBalance.div(LAMPORTS_PER_SOL);
250
+ // const remainderLamports = totalBalance.mod(LAMPORTS_PER_SOL);
251
+ return { lamports: totalBalance.toNumber() };
252
+ }
253
+ async function decrypt_outputs(encryptedOutputs, encryptionService, utxoKeypair, lightWasm) {
254
+ let results = [];
255
+ // decript all UTXO
256
+ for (const encryptedOutput of encryptedOutputs) {
257
+ if (!encryptedOutput) {
258
+ results.push({ status: 'skipped' });
259
+ continue;
260
+ }
261
+ try {
262
+ const utxo = await encryptionService.decryptUtxo(encryptedOutput, lightWasm);
263
+ results.push({ status: 'decrypted', utxo, encryptedOutput });
264
+ }
265
+ catch {
266
+ results.push({ status: 'unDecrypted' });
267
+ }
268
+ }
269
+ results = results.filter(r => r.status == 'decrypted');
270
+ if (!results.length) {
271
+ return [];
272
+ }
273
+ // update utxo index
274
+ if (results.length > 0) {
275
+ let encrypted_outputs = results.map(r => r.encryptedOutput);
276
+ let url = RELAYER_API_URL + `/utxos/indices`;
277
+ let res = await fetch(url, {
278
+ method: 'POST', headers: { "Content-Type": "application/json" },
279
+ body: JSON.stringify({ encrypted_outputs })
280
+ });
281
+ let j = await res.json();
282
+ if (!j.indices || !Array.isArray(j.indices) || j.indices.length != encrypted_outputs.length) {
283
+ throw new Error('failed fetching /utxos/indices');
284
+ }
285
+ for (let i = 0; i < results.length; i++) {
286
+ let utxo = results[i].utxo;
287
+ if (utxo.index !== j.indices[i] && typeof j.indices[i] == 'number') {
288
+ logger.debug(`Updated UTXO index from ${utxo.index} to ${j.indices[i]}`);
289
+ utxo.index = j.indices[i];
290
+ }
291
+ }
292
+ }
293
+ return results;
294
+ }
@@ -0,0 +1,33 @@
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 getUtxosSPL({ publicKey, connection, encryptionService, storage, abortSignal, offset, mintAddress }: {
13
+ publicKey: PublicKey;
14
+ connection: Connection;
15
+ encryptionService: EncryptionService;
16
+ storage: Storage;
17
+ mintAddress: PublicKey | string;
18
+ abortSignal?: AbortSignal;
19
+ offset?: number;
20
+ }): Promise<Utxo[]>;
21
+ /**
22
+ * Check if a UTXO has been spent
23
+ * @param connection Solana connection
24
+ * @param utxo The UTXO to check
25
+ * @returns Promise<boolean> true if spent, false if unspent
26
+ */
27
+ export declare function isUtxoSpent(connection: Connection, utxo: Utxo): Promise<boolean>;
28
+ export declare function getBalanceFromUtxosSPL(utxos: Utxo[]): {
29
+ base_units: number;
30
+ amount: number;
31
+ /** @deprecated use base_units instead */
32
+ lamports: number;
33
+ };