nova-privacy-sdk 1.0.0

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 (69) hide show
  1. package/.github/workflows/npm-publish.yml +55 -0
  2. package/PUBLISH.md +122 -0
  3. package/README.md +177 -0
  4. package/__tests__/e2e.test.ts +56 -0
  5. package/__tests__/e2espl.test.ts +73 -0
  6. package/__tests__/encryption.test.ts +1635 -0
  7. package/circuit2/transaction2.wasm +0 -0
  8. package/circuit2/transaction2.zkey +0 -0
  9. package/dist/config.d.ts +9 -0
  10. package/dist/config.js +12 -0
  11. package/dist/deposit.d.ts +18 -0
  12. package/dist/deposit.js +392 -0
  13. package/dist/depositSPL.d.ts +20 -0
  14. package/dist/depositSPL.js +448 -0
  15. package/dist/exportUtils.d.ts +11 -0
  16. package/dist/exportUtils.js +11 -0
  17. package/dist/getUtxos.d.ts +29 -0
  18. package/dist/getUtxos.js +294 -0
  19. package/dist/getUtxosSPL.d.ts +33 -0
  20. package/dist/getUtxosSPL.js +395 -0
  21. package/dist/index.d.ts +125 -0
  22. package/dist/index.js +302 -0
  23. package/dist/models/keypair.d.ts +26 -0
  24. package/dist/models/keypair.js +43 -0
  25. package/dist/models/utxo.d.ts +49 -0
  26. package/dist/models/utxo.js +85 -0
  27. package/dist/utils/address_lookup_table.d.ts +9 -0
  28. package/dist/utils/address_lookup_table.js +45 -0
  29. package/dist/utils/constants.d.ts +31 -0
  30. package/dist/utils/constants.js +62 -0
  31. package/dist/utils/encryption.d.ts +107 -0
  32. package/dist/utils/encryption.js +376 -0
  33. package/dist/utils/logger.d.ts +9 -0
  34. package/dist/utils/logger.js +35 -0
  35. package/dist/utils/merkle_tree.d.ts +92 -0
  36. package/dist/utils/merkle_tree.js +186 -0
  37. package/dist/utils/node-shim.d.ts +5 -0
  38. package/dist/utils/node-shim.js +5 -0
  39. package/dist/utils/prover.d.ts +36 -0
  40. package/dist/utils/prover.js +147 -0
  41. package/dist/utils/utils.d.ts +69 -0
  42. package/dist/utils/utils.js +182 -0
  43. package/dist/withdraw.d.ts +21 -0
  44. package/dist/withdraw.js +270 -0
  45. package/dist/withdrawSPL.d.ts +23 -0
  46. package/dist/withdrawSPL.js +306 -0
  47. package/package.json +77 -0
  48. package/setup-git.sh +51 -0
  49. package/setup-github.sh +36 -0
  50. package/src/config.ts +22 -0
  51. package/src/deposit.ts +487 -0
  52. package/src/depositSPL.ts +567 -0
  53. package/src/exportUtils.ts +13 -0
  54. package/src/getUtxos.ts +396 -0
  55. package/src/getUtxosSPL.ts +528 -0
  56. package/src/index.ts +350 -0
  57. package/src/models/keypair.ts +52 -0
  58. package/src/models/utxo.ts +106 -0
  59. package/src/utils/address_lookup_table.ts +78 -0
  60. package/src/utils/constants.ts +84 -0
  61. package/src/utils/encryption.ts +464 -0
  62. package/src/utils/logger.ts +42 -0
  63. package/src/utils/merkle_tree.ts +207 -0
  64. package/src/utils/node-shim.ts +6 -0
  65. package/src/utils/prover.ts +222 -0
  66. package/src/utils/utils.ts +242 -0
  67. package/src/withdraw.ts +332 -0
  68. package/src/withdrawSPL.ts +394 -0
  69. package/tsconfig.json +28 -0
@@ -0,0 +1,528 @@
1
+ import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
2
+ import BN from 'bn.js';
3
+ import { Keypair as UtxoKeypair } from './models/keypair.js';
4
+ import { Utxo } from './models/utxo.js';
5
+ import { EncryptionService } from './utils/encryption.js';
6
+ import { WasmFactory } from '@lightprotocol/hasher.rs';
7
+ //@ts-ignore
8
+ import * as ffjavascript from 'ffjavascript';
9
+ import { FETCH_UTXOS_GROUP_SIZE, RELAYER_API_URL, LSK_ENCRYPTED_OUTPUTS, LSK_FETCH_OFFSET, PROGRAM_ID, SplList, tokens } from './utils/constants.js';
10
+ import { logger } from './utils/logger.js';
11
+ import { getAssociatedTokenAddress } from '@solana/spl-token';
12
+
13
+ // Use type assertion for the utility functions (same pattern as in get_verification_keys.ts)
14
+ const utils = ffjavascript.utils as any;
15
+ const { unstringifyBigInts, leInt2Buff } = utils;
16
+
17
+ /**
18
+ * Interface for the UTXO data returned from the API
19
+ */
20
+ interface ApiUtxo {
21
+ commitment: string;
22
+ encrypted_output: string; // Hex-encoded encrypted UTXO data
23
+ index: number;
24
+ nullifier?: string; // Optional, might not be present for all UTXOs
25
+ }
26
+
27
+ /**
28
+ * Interface for the API response format that includes count and encrypted_outputs
29
+ */
30
+ interface ApiResponse {
31
+ count: number;
32
+ encrypted_outputs: string[];
33
+ }
34
+
35
+ function sleep(ms: number): Promise<string> {
36
+ return new Promise(resolve => setTimeout(() => {
37
+ resolve('ok')
38
+ }, ms))
39
+ }
40
+
41
+ export function localstorageKey(key: PublicKey) {
42
+ return PROGRAM_ID.toString().substring(0, 6) + key.toString()
43
+ }
44
+
45
+ type Utxos = { [k: string]: Utxo[] }
46
+
47
+ let getMyUtxosPromise: Promise<Utxo[]> | null = null
48
+ let roundStartIndex = 0
49
+ let decryptionTaskFinished = 0;
50
+ /**
51
+ * Fetch and decrypt all UTXOs for a user
52
+ * @param signed The user's signature
53
+ * @param connection Solana connection to fetch on-chain commitment accounts
54
+ * @param setStatus A global state updator. Set live status message showing on webpage
55
+ * @returns Array of decrypted UTXOs that belong to the user
56
+ */
57
+
58
+ export async function getUtxosSPL({ publicKey, connection, encryptionService, storage, abortSignal, offset, mintAddress }: {
59
+ publicKey: PublicKey,
60
+ connection: Connection,
61
+ encryptionService: EncryptionService,
62
+ storage: Storage,
63
+ mintAddress: PublicKey | string,
64
+ abortSignal?: AbortSignal
65
+ offset?: number
66
+ }): Promise<Utxo[]> {
67
+ let valid_utxos: Utxo[] = []
68
+ let valid_strings: string[] = []
69
+ let history_indexes: number[] = []
70
+ let publicKey_ata: PublicKey
71
+
72
+ if (typeof mintAddress == 'string') {
73
+ mintAddress = new PublicKey(mintAddress)
74
+ }
75
+
76
+ let token = tokens.find(t => t.pubkey.toString() == mintAddress.toString())
77
+ if (!token) {
78
+ throw new Error('token not found: ' + mintAddress.toString())
79
+ }
80
+
81
+ logger.debug('token name: ' + token.name + ', token address' + token.pubkey.toString())
82
+
83
+ try {
84
+ publicKey_ata = await getAssociatedTokenAddress(
85
+ token.pubkey,
86
+ publicKey
87
+ );
88
+ let offsetStr = storage.getItem(LSK_FETCH_OFFSET + localstorageKey(publicKey_ata))
89
+ if (offsetStr) {
90
+ roundStartIndex = Number(offsetStr)
91
+ } else {
92
+ roundStartIndex = 0
93
+ }
94
+ decryptionTaskFinished = 0
95
+ if (!offset) {
96
+ offset = 0
97
+ }
98
+ roundStartIndex = Math.max(offset, roundStartIndex)
99
+ while (true) {
100
+ if (abortSignal?.aborted) {
101
+ throw new Error('aborted')
102
+ }
103
+ let offsetStr = storage.getItem(LSK_FETCH_OFFSET + localstorageKey(publicKey_ata))
104
+ let fetch_utxo_offset = offsetStr ? Number(offsetStr) : 0
105
+ if (offset) {
106
+ fetch_utxo_offset = Math.max(offset, fetch_utxo_offset)
107
+ }
108
+ logger.debug(' ####fetch_utxo_offset', fetch_utxo_offset)
109
+ let fetch_utxo_end = fetch_utxo_offset + FETCH_UTXOS_GROUP_SIZE
110
+ let fetch_utxo_url = `${RELAYER_API_URL}/utxos/range?token=${token.name}&start=${fetch_utxo_offset}&end=${fetch_utxo_end}`
111
+ let fetched = await fetchUserUtxos({ url: fetch_utxo_url, encryptionService, storage, publicKey_ata, tokenName: token.name })
112
+ let am = 0
113
+
114
+ const nonZeroUtxos: Utxo[] = [];
115
+ const nonZeroEncrypted: any[] = [];
116
+ for (let [k, utxo] of fetched.utxos.entries()) {
117
+ history_indexes.push(utxo.index)
118
+ if (utxo.amount.toNumber() > 0) {
119
+ nonZeroUtxos.push(utxo);
120
+ nonZeroEncrypted.push(fetched.encryptedOutputs[k]);
121
+ }
122
+ }
123
+ if (nonZeroUtxos.length > 0) {
124
+ const spentFlags = await areUtxosSpent(connection, nonZeroUtxos);
125
+ for (let i = 0; i < nonZeroUtxos.length; i++) {
126
+ if (!spentFlags[i]) {
127
+ logger.debug(`found unspent encrypted_output ${nonZeroEncrypted[i]}`)
128
+ am += nonZeroUtxos[i].amount.toNumber();
129
+ valid_utxos.push(nonZeroUtxos[i]);
130
+ valid_strings.push(nonZeroEncrypted[i]);
131
+ }
132
+ }
133
+ }
134
+ storage.setItem(LSK_FETCH_OFFSET + localstorageKey(publicKey_ata), (fetch_utxo_offset + fetched.len).toString())
135
+ if (!fetched.hasMore) {
136
+ break
137
+ }
138
+ await sleep(100)
139
+ }
140
+ } catch (e: any) {
141
+ throw e
142
+ } finally {
143
+ getMyUtxosPromise = null
144
+ }
145
+ // get history index
146
+ let historyKey = 'tradeHistory' + localstorageKey(publicKey_ata)
147
+ let rec = storage.getItem(historyKey)
148
+ let recIndexes: number[] = []
149
+ if (rec?.length) {
150
+ recIndexes = rec.split(',').map(n => Number(n))
151
+ }
152
+ if (recIndexes.length) {
153
+ history_indexes = [...history_indexes, ...recIndexes]
154
+ }
155
+ let unique_history_indexes = Array.from(new Set(history_indexes));
156
+ let top20 = unique_history_indexes.sort((a, b) => b - a).slice(0, 20);
157
+ if (top20.length) {
158
+ storage.setItem(historyKey, top20.join(','))
159
+ }
160
+ // store valid strings
161
+ logger.debug(`valid_strings len before set: ${valid_strings.length}`)
162
+ valid_strings = [...new Set(valid_strings)];
163
+ logger.debug(`valid_strings len after set: ${valid_strings.length}`)
164
+ storage.setItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(publicKey_ata), JSON.stringify(valid_strings))
165
+ return valid_utxos.filter(u => u.mintAddress == token.pubkey.toString())
166
+
167
+ }
168
+
169
+ async function fetchUserUtxos({ url, storage, encryptionService, publicKey_ata, tokenName }: {
170
+ url: string,
171
+ encryptionService: EncryptionService,
172
+ storage: Storage,
173
+ publicKey_ata: PublicKey
174
+ tokenName: string
175
+ }): Promise<{
176
+ encryptedOutputs: string[],
177
+ utxos: Utxo[],
178
+ hasMore: boolean,
179
+ len: number
180
+ }> {
181
+ const lightWasm = await WasmFactory.getInstance();
182
+
183
+ // Derive the UTXO keypair from the wallet keypair
184
+ const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
185
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
186
+
187
+
188
+ // Fetch all UTXOs from the API
189
+ let encryptedOutputs: string[] = [];
190
+ logger.debug('fetching utxo data', url)
191
+ let res = await fetch(url)
192
+ if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
193
+ const data: any = await res.json()
194
+ logger.debug('got utxo data')
195
+ if (!data) {
196
+ throw new Error('API returned empty data')
197
+ } else if (Array.isArray(data)) {
198
+ // Handle the case where the API returns an array of UTXOs
199
+ const utxos: ApiUtxo[] = data;
200
+ // Extract encrypted outputs from the array of UTXOs
201
+ encryptedOutputs = utxos
202
+ .filter(utxo => utxo.encrypted_output)
203
+ .map(utxo => utxo.encrypted_output);
204
+ } else if (typeof data === 'object' && data.encrypted_outputs) {
205
+ // Handle the case where the API returns an object with encrypted_outputs array
206
+ const apiResponse = data as ApiResponse;
207
+ encryptedOutputs = apiResponse.encrypted_outputs;
208
+ } else {
209
+ throw new Error(`API returned unexpected data format: ${JSON.stringify(data).substring(0, 100)}...`);
210
+ }
211
+
212
+ // Try to decrypt each encrypted output
213
+ const myUtxos: Utxo[] = [];
214
+ const myEncryptedOutputs: string[] = [];
215
+ let decryptionAttempts = 0;
216
+ let successfulDecryptions = 0;
217
+
218
+ let cachedStringNum = 0
219
+ let cachedString = storage.getItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(publicKey_ata))
220
+ if (cachedString) {
221
+ cachedStringNum = JSON.parse(cachedString).length
222
+ }
223
+
224
+
225
+ let decryptionTaskTotal = data.total + cachedStringNum - roundStartIndex;
226
+ let batchRes = await decrypt_outputs(encryptedOutputs, encryptionService, utxoKeypair, lightWasm, tokenName)
227
+ decryptionTaskFinished += encryptedOutputs.length
228
+ logger.debug('batchReslen', batchRes.length)
229
+ for (let i = 0; i < batchRes.length; i++) {
230
+ let dres = batchRes[i]
231
+ if (dres.status == 'decrypted' && dres.utxo) {
232
+ myUtxos.push(dres.utxo)
233
+ myEncryptedOutputs.push(dres.encryptedOutput!)
234
+ }
235
+ }
236
+ logger.info(`(decrypting cached utxo: ${decryptionTaskFinished + 1}/${decryptionTaskTotal}...)`)
237
+ // check cached string when no more fetching tasks
238
+ if (!data.hasMore) {
239
+ if (cachedString) {
240
+ let cachedEncryptedOutputs = JSON.parse(cachedString)
241
+ if (decryptionTaskFinished % 100 == 0) {
242
+ logger.info(`(decrypting cached utxo: ${decryptionTaskFinished + 1}/${decryptionTaskTotal}...)`)
243
+ }
244
+ let batchRes = await decrypt_outputs(cachedEncryptedOutputs, encryptionService, utxoKeypair, lightWasm, tokenName)
245
+ decryptionTaskFinished += cachedEncryptedOutputs.length
246
+ logger.debug('cachedbatchReslen', batchRes.length, ' source', cachedEncryptedOutputs.length)
247
+ for (let i = 0; i < batchRes.length; i++) {
248
+ let dres = batchRes[i]
249
+ if (dres.status == 'decrypted' && dres.utxo) {
250
+ myUtxos.push(dres.utxo)
251
+ myEncryptedOutputs.push(dres.encryptedOutput!)
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ return { encryptedOutputs: myEncryptedOutputs, utxos: myUtxos, hasMore: data.hasMore, len: encryptedOutputs.length };
258
+ }
259
+
260
+ /**
261
+ * Check if a UTXO has been spent
262
+ * @param connection Solana connection
263
+ * @param utxo The UTXO to check
264
+ * @returns Promise<boolean> true if spent, false if unspent
265
+ */
266
+ export async function isUtxoSpent(connection: Connection, utxo: Utxo): Promise<boolean> {
267
+ try {
268
+ // Get the nullifier for this UTXO
269
+ const nullifier = await utxo.getNullifier();
270
+ logger.debug(`Checking if UTXO with nullifier ${nullifier} is spent`);
271
+
272
+ // Convert decimal nullifier string to byte array (same format as in proofs)
273
+ // This matches how commitments are handled and how the Rust code expects the seeds
274
+ const nullifierBytes = Array.from(
275
+ leInt2Buff(unstringifyBigInts(nullifier), 32)
276
+ ).reverse() as number[];
277
+
278
+ // Try nullifier0 seed
279
+ const [nullifier0PDA] = PublicKey.findProgramAddressSync(
280
+ [Buffer.from("nullifier0"), Buffer.from(nullifierBytes)],
281
+ PROGRAM_ID
282
+ );
283
+
284
+ logger.debug(`Derived nullifier0 PDA: ${nullifier0PDA.toBase58()}`);
285
+ const nullifier0Account = await connection.getAccountInfo(nullifier0PDA);
286
+ if (nullifier0Account !== null) {
287
+ logger.debug(`UTXO is spent (nullifier0 account exists)`);
288
+ return true;
289
+ }
290
+
291
+
292
+ const [nullifier1PDA] = PublicKey.findProgramAddressSync(
293
+ [Buffer.from("nullifier1"), Buffer.from(nullifierBytes)],
294
+ PROGRAM_ID
295
+ );
296
+
297
+ logger.debug(`Derived nullifier1 PDA: ${nullifier1PDA.toBase58()}`);
298
+ const nullifier1Account = await connection.getAccountInfo(nullifier1PDA);
299
+ if (nullifier1Account !== null) {
300
+ logger.debug(`UTXO is spent (nullifier1 account exists)`);
301
+ return true
302
+ }
303
+ return false;
304
+ } catch (error: any) {
305
+ console.error('Error checking if UTXO is spent:', error);
306
+ await new Promise(resolve => setTimeout(resolve, 3000));
307
+ return await isUtxoSpent(connection, utxo)
308
+ }
309
+ }
310
+
311
+ async function areUtxosSpent(
312
+ connection: Connection,
313
+ utxos: Utxo[]
314
+ ): Promise<boolean[]> {
315
+ try {
316
+ const allPDAs: { utxoIndex: number; pda: PublicKey }[] = [];
317
+
318
+ for (let i = 0; i < utxos.length; i++) {
319
+ const utxo = utxos[i];
320
+ const nullifier = await utxo.getNullifier();
321
+
322
+ const nullifierBytes = Array.from(
323
+ leInt2Buff(unstringifyBigInts(nullifier), 32)
324
+ ).reverse() as number[];
325
+
326
+ const [nullifier0PDA] = PublicKey.findProgramAddressSync(
327
+ [Buffer.from("nullifier0"), Buffer.from(nullifierBytes)],
328
+ PROGRAM_ID
329
+ );
330
+ const [nullifier1PDA] = PublicKey.findProgramAddressSync(
331
+ [Buffer.from("nullifier1"), Buffer.from(nullifierBytes)],
332
+ PROGRAM_ID
333
+ );
334
+
335
+ allPDAs.push({ utxoIndex: i, pda: nullifier0PDA });
336
+ allPDAs.push({ utxoIndex: i, pda: nullifier1PDA });
337
+ }
338
+
339
+ const results: any[] =
340
+ await connection.getMultipleAccountsInfo(allPDAs.map((x) => x.pda));
341
+
342
+ const spentFlags = new Array(utxos.length).fill(false);
343
+ for (let i = 0; i < allPDAs.length; i++) {
344
+ if (results[i] !== null) {
345
+ spentFlags[allPDAs[i].utxoIndex] = true;
346
+ }
347
+ }
348
+
349
+ return spentFlags;
350
+ } catch (error: any) {
351
+ console.error("Error checking if UTXOs are spent:", error);
352
+ await new Promise((resolve) => setTimeout(resolve, 3000));
353
+ return await areUtxosSpent(connection, utxos);
354
+ }
355
+ }
356
+
357
+ // Calculate total balance
358
+ export function getBalanceFromUtxosSPL(utxos: Utxo[]): {
359
+ base_units: number
360
+ amount: number
361
+ /** @deprecated use base_units instead */
362
+ lamports: number
363
+ } {
364
+ if (!utxos.length) {
365
+ return { base_units: 0, amount: 0, lamports: 0 }
366
+ }
367
+ let token = tokens.find(t => t.pubkey.toString() == utxos[0].mintAddress.toString())
368
+ if (!token) {
369
+ throw new Error('token not found for ' + utxos[0].mintAddress.toString())
370
+ }
371
+ const totalBalance = utxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
372
+ return {
373
+ base_units: totalBalance.toNumber(),
374
+ lamports: totalBalance.toNumber(),
375
+ amount: totalBalance.toNumber() / token.units_per_token
376
+ }
377
+ }
378
+
379
+ // Decrypt single output to Utxo
380
+ type DecryptRes = { status: 'decrypted' | 'skipped' | 'unDecrypted', utxo?: Utxo, encryptedOutput?: string }
381
+ async function decrypt_output(
382
+ encryptedOutput: string,
383
+ encryptionService: EncryptionService,
384
+ utxoKeypair: UtxoKeypair,
385
+ lightWasm: any,
386
+ connection: Connection
387
+ ): Promise<DecryptRes> {
388
+ let res: DecryptRes = { status: 'unDecrypted' }
389
+ try {
390
+ if (!encryptedOutput) {
391
+ return { status: 'skipped' }
392
+ }
393
+
394
+ // Try to decrypt the UTXO
395
+ res.utxo = await encryptionService.decryptUtxo(
396
+ encryptedOutput,
397
+ lightWasm
398
+ );
399
+
400
+ // If we got here, decryption succeeded, so this UTXO belongs to the user
401
+ res.status = 'decrypted'
402
+
403
+ // Get the real index from the on-chain commitment account
404
+ try {
405
+ if (!res.utxo) {
406
+ throw new Error('res.utxo undefined')
407
+ }
408
+ const commitment = await res.utxo.getCommitment();
409
+ // Convert decimal commitment string to byte array (same format as in proofs)
410
+ const commitmentBytes = Array.from(
411
+ leInt2Buff(unstringifyBigInts(commitment), 32)
412
+ ).reverse() as number[];
413
+
414
+ // Derive the commitment PDA (could be either commitment0 or commitment1)
415
+ // We'll try both seeds since we don't know which one it is
416
+ let commitmentAccount = null;
417
+ let realIndex = null;
418
+ // Try commitment0 seed
419
+ try {
420
+ const [commitment0PDA] = PublicKey.findProgramAddressSync(
421
+ [Buffer.from("commitment0"), Buffer.from(commitmentBytes)],
422
+ PROGRAM_ID
423
+ );
424
+
425
+ const account0Info = await connection.getAccountInfo(commitment0PDA);
426
+ if (account0Info) {
427
+ // Parse the index from the account data according to CommitmentAccount structure:
428
+ // 0-8: Anchor discriminator
429
+ // 8-40: commitment (32 bytes)
430
+ // 40-44: encrypted_output length (4 bytes)
431
+ // 44-44+len: encrypted_output data
432
+ // 44+len-52+len: index (8 bytes)
433
+ const encryptedOutputLength = account0Info.data.readUInt32LE(40);
434
+ const indexOffset = 44 + encryptedOutputLength;
435
+ const indexBytes = account0Info.data.slice(indexOffset, indexOffset + 8);
436
+ realIndex = new BN(indexBytes, 'le').toNumber();
437
+ }
438
+ } catch (e) {
439
+ // Try commitment1 seed if commitment0 fails
440
+ try {
441
+ const [commitment1PDA] = PublicKey.findProgramAddressSync(
442
+ [Buffer.from("commitment1"), Buffer.from(commitmentBytes)],
443
+ PROGRAM_ID
444
+ );
445
+
446
+ const account1Info = await connection.getAccountInfo(commitment1PDA);
447
+ if (account1Info) {
448
+ // Parse the index from the account data according to CommitmentAccount structure
449
+ const encryptedOutputLength = account1Info.data.readUInt32LE(40);
450
+ const indexOffset = 44 + encryptedOutputLength;
451
+ const indexBytes = account1Info.data.slice(indexOffset, indexOffset + 8);
452
+ realIndex = new BN(indexBytes, 'le').toNumber();
453
+ logger.debug(`Found commitment1 account with index: ${realIndex}`);
454
+ }
455
+ } catch (e2) {
456
+ logger.debug(`Could not find commitment account for ${commitment}, using encrypted index: ${res.utxo.index}`);
457
+ }
458
+ }
459
+
460
+ // Update the UTXO with the real index if we found it
461
+ if (realIndex !== null) {
462
+ const oldIndex = res.utxo.index;
463
+ res.utxo.index = realIndex;
464
+ }
465
+
466
+ } catch (error: any) {
467
+ logger.debug(`Failed to get real index for UTXO: ${error.message}`);
468
+ }
469
+ } catch (error: any) {
470
+ // this UTXO doesn't belong to the user
471
+ }
472
+ return res
473
+ }
474
+
475
+ async function decrypt_outputs(
476
+ encryptedOutputs: string[],
477
+ encryptionService: EncryptionService,
478
+ utxoKeypair: UtxoKeypair,
479
+ lightWasm: any,
480
+ tokenName: string
481
+ ): Promise<DecryptRes[]> {
482
+ let results: DecryptRes[] = [];
483
+
484
+ // decript all UTXO
485
+ for (const encryptedOutput of encryptedOutputs) {
486
+ if (!encryptedOutput) {
487
+ results.push({ status: 'skipped' });
488
+ continue;
489
+ }
490
+ try {
491
+ const utxo = await encryptionService.decryptUtxo(
492
+ encryptedOutput,
493
+ lightWasm
494
+ );
495
+ results.push({ status: 'decrypted', utxo, encryptedOutput });
496
+ } catch {
497
+ results.push({ status: 'unDecrypted' });
498
+ }
499
+ }
500
+ results = results.filter(r => r.status == 'decrypted')
501
+ if (!results.length) {
502
+ return []
503
+ }
504
+
505
+ // update utxo index
506
+ if (results.length > 0) {
507
+ let encrypted_outputs = results.map(r => r.encryptedOutput)
508
+
509
+ let url = RELAYER_API_URL + `/utxos/indices`
510
+ let res = await fetch(url, {
511
+ method: 'POST', headers: { "Content-Type": "application/json" },
512
+ body: JSON.stringify({ encrypted_outputs, token: tokenName })
513
+ })
514
+ let j = await res.json()
515
+ if (!j.indices || !Array.isArray(j.indices) || j.indices.length != encrypted_outputs.length) {
516
+ throw new Error('failed fetching /utxos/indices')
517
+ }
518
+ for (let i = 0; i < results.length; i++) {
519
+ let utxo = results[i].utxo
520
+ if (utxo!.index !== j.indices[i] && typeof j.indices[i] == 'number') {
521
+ logger.debug(`Updated UTXO index from ${utxo!.index} to ${j.indices[i]}`);
522
+ utxo!.index = j.indices[i]
523
+ }
524
+ }
525
+ }
526
+
527
+ return results;
528
+ }