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,186 @@
1
+ export const DEFAULT_ZERO = 0;
2
+ /**
3
+ * @callback hashFunction
4
+ * @param left Left leaf
5
+ * @param right Right leaf
6
+ */
7
+ /**
8
+ * Merkle tree
9
+ */
10
+ export class MerkleTree {
11
+ /**
12
+ * Constructor
13
+ * @param {number} levels Number of levels in the tree
14
+ * @param {Array} [elements] Initial elements
15
+ * @param {Object} options
16
+ * @param {hashFunction} [options.hashFunction] Function used to hash 2 leaves
17
+ * @param [options.zeroElement] Value for non-existent leaves
18
+ */
19
+ levels;
20
+ capacity;
21
+ zeroElement;
22
+ _zeros;
23
+ _layers;
24
+ _lightWasm;
25
+ constructor(levels, lightWasm, elements = [], { zeroElement = DEFAULT_ZERO } = {}) {
26
+ this.levels = levels;
27
+ this.capacity = 2 ** levels;
28
+ this.zeroElement = zeroElement.toString();
29
+ this._lightWasm = lightWasm;
30
+ if (elements.length > this.capacity) {
31
+ throw new Error("Tree is full");
32
+ }
33
+ this._zeros = [];
34
+ this._layers = [];
35
+ this._layers[0] = elements;
36
+ this._zeros[0] = this.zeroElement;
37
+ for (let i = 1; i <= levels; i++) {
38
+ this._zeros[i] = this._lightWasm.poseidonHashString([
39
+ this._zeros[i - 1],
40
+ this._zeros[i - 1],
41
+ ]);
42
+ }
43
+ this._rebuild();
44
+ }
45
+ _rebuild() {
46
+ for (let level = 1; level <= this.levels; level++) {
47
+ this._layers[level] = [];
48
+ for (let i = 0; i < Math.ceil(this._layers[level - 1].length / 2); i++) {
49
+ this._layers[level][i] = this._lightWasm.poseidonHashString([
50
+ this._layers[level - 1][i * 2],
51
+ i * 2 + 1 < this._layers[level - 1].length
52
+ ? this._layers[level - 1][i * 2 + 1]
53
+ : this._zeros[level - 1],
54
+ ]);
55
+ }
56
+ }
57
+ }
58
+ /**
59
+ * Get tree root
60
+ * @returns {*}
61
+ */
62
+ root() {
63
+ return this._layers[this.levels].length > 0
64
+ ? this._layers[this.levels][0]
65
+ : this._zeros[this.levels];
66
+ }
67
+ /**
68
+ * Insert new element into the tree
69
+ * @param element Element to insert
70
+ */
71
+ insert(element) {
72
+ if (this._layers[0].length >= this.capacity) {
73
+ throw new Error("Tree is full");
74
+ }
75
+ this.update(this._layers[0].length, element);
76
+ }
77
+ /**
78
+ * Insert multiple elements into the tree. Tree will be fully rebuilt during this operation.
79
+ * @param {Array} elements Elements to insert
80
+ */
81
+ bulkInsert(elements) {
82
+ if (this._layers[0].length + elements.length > this.capacity) {
83
+ throw new Error("Tree is full");
84
+ }
85
+ this._layers[0].push(...elements);
86
+ this._rebuild();
87
+ }
88
+ // TODO: update does not work debug
89
+ /**
90
+ * Change an element in the tree
91
+ * @param {number} index Index of element to change
92
+ * @param element Updated element value
93
+ */
94
+ update(index, element) {
95
+ // index 0 and 1 and element is the commitment hash
96
+ if (isNaN(Number(index)) ||
97
+ index < 0 ||
98
+ index > this._layers[0].length ||
99
+ index >= this.capacity) {
100
+ throw new Error("Insert index out of bounds: " + index);
101
+ }
102
+ this._layers[0][index] = element;
103
+ for (let level = 1; level <= this.levels; level++) {
104
+ index >>= 1;
105
+ this._layers[level][index] = this._lightWasm.poseidonHashString([
106
+ this._layers[level - 1][index * 2],
107
+ index * 2 + 1 < this._layers[level - 1].length
108
+ ? this._layers[level - 1][index * 2 + 1]
109
+ : this._zeros[level - 1],
110
+ ]);
111
+ }
112
+ }
113
+ /**
114
+ * Get merkle path to a leaf
115
+ * @param {number} index Leaf index to generate path for
116
+ * @returns {{pathElements: number[], pathIndex: number[]}} An object containing adjacent elements and left-right index
117
+ */
118
+ path(index) {
119
+ if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) {
120
+ throw new Error("Index out of bounds: " + index);
121
+ }
122
+ const pathElements = [];
123
+ const pathIndices = [];
124
+ for (let level = 0; level < this.levels; level++) {
125
+ pathIndices[level] = index % 2;
126
+ pathElements[level] =
127
+ (index ^ 1) < this._layers[level].length
128
+ ? this._layers[level][index ^ 1]
129
+ : this._zeros[level];
130
+ index >>= 1;
131
+ }
132
+ return {
133
+ pathElements,
134
+ pathIndices,
135
+ };
136
+ }
137
+ /**
138
+ * Find an element in the tree
139
+ * @param element An element to find
140
+ * @param comparator A function that checks leaf value equality
141
+ * @returns {number} Index if element is found, otherwise -1
142
+ */
143
+ indexOf(element, comparator = null) {
144
+ if (comparator) {
145
+ return this._layers[0].findIndex((el) => comparator(element, el));
146
+ }
147
+ else {
148
+ return this._layers[0].indexOf(element);
149
+ }
150
+ }
151
+ /**
152
+ * Returns a copy of non-zero tree elements
153
+ * @returns {Object[]}
154
+ */
155
+ elements() {
156
+ return this._layers[0].slice();
157
+ }
158
+ /**
159
+ * Serialize entire tree state including intermediate layers into a plain object
160
+ * Deserializing it back will not require to recompute any hashes
161
+ * Elements are not converted to a plain type, this is responsibility of the caller
162
+ */
163
+ serialize() {
164
+ return {
165
+ levels: this.levels,
166
+ _zeros: this._zeros,
167
+ _layers: this._layers,
168
+ };
169
+ }
170
+ /**
171
+ * Deserialize data into a MerkleTree instance
172
+ * Make sure to provide the same hashFunction as was used in the source tree,
173
+ * otherwise the tree state will be invalid
174
+ *
175
+ * @param data
176
+ * @param hashFunction
177
+ * @returns {MerkleTree}
178
+ */
179
+ static deserialize(data, hashFunction) {
180
+ const instance = Object.assign(Object.create(this.prototype), data);
181
+ instance._hash = hashFunction;
182
+ instance.capacity = 2 ** instance.levels;
183
+ instance.zeroElement = instance._zeros[0];
184
+ return instance;
185
+ }
186
+ }
@@ -0,0 +1,5 @@
1
+ import { LocalStorage } from "node-localstorage";
2
+ import path from "path";
3
+ import fs from "fs";
4
+ import { fileURLToPath } from "url";
5
+ export { LocalStorage, path, fs, fileURLToPath };
@@ -0,0 +1,5 @@
1
+ import { LocalStorage } from "node-localstorage";
2
+ import path from "path";
3
+ import fs from "fs";
4
+ import { fileURLToPath } from "url";
5
+ export { LocalStorage, path, fs, fileURLToPath };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * ZK Proof Generation Utilities
3
+ *
4
+ * This file provides functions for generating zero-knowledge proofs for privacy-preserving
5
+ * transactions on Solana. It handles both snarkjs and zkutil proof generation workflows.
6
+ *
7
+ * Inspired by: https://github.com/tornadocash/tornado-nova/blob/f9264eeffe48bf5e04e19d8086ee6ec58cdf0d9e/src/prover.js
8
+ */
9
+ interface Proof {
10
+ pi_a: string[];
11
+ pi_b: string[][];
12
+ pi_c: string[];
13
+ protocol: string;
14
+ curve: string;
15
+ }
16
+ /**
17
+ * Generates a ZK proof using snarkjs and formats it for use on-chain
18
+ *
19
+ * @param input The circuit inputs to generate a proof for
20
+ * @param keyBasePath The base path for the circuit keys (.wasm and .zkey files)
21
+ * @param options Optional proof generation options (e.g., singleThread for Deno/Bun)
22
+ * @returns A proof object with formatted proof elements and public signals
23
+ */
24
+ declare function prove(input: any, keyBasePath: string, options?: {
25
+ singleThread?: boolean;
26
+ }): Promise<{
27
+ proof: Proof;
28
+ publicSignals: string[];
29
+ }>;
30
+ export declare function parseProofToBytesArray(proof: Proof, compressed?: boolean): {
31
+ proofA: number[];
32
+ proofB: number[][];
33
+ proofC: number[];
34
+ };
35
+ export declare function parseToBytesArray(publicSignals: string[]): number[][];
36
+ export { prove, type Proof };
@@ -0,0 +1,147 @@
1
+ /**
2
+ * ZK Proof Generation Utilities
3
+ *
4
+ * This file provides functions for generating zero-knowledge proofs for privacy-preserving
5
+ * transactions on Solana. It handles both snarkjs and zkutil proof generation workflows.
6
+ *
7
+ * Inspired by: https://github.com/tornadocash/tornado-nova/blob/f9264eeffe48bf5e04e19d8086ee6ec58cdf0d9e/src/prover.js
8
+ */
9
+ /// <reference types="node" />
10
+ import * as anchor from "@coral-xyz/anchor";
11
+ import { wtns, groth16 } from 'snarkjs';
12
+ import { FIELD_SIZE } from './constants.js';
13
+ // @ts-ignore - ignore TypeScript errors for ffjavascript
14
+ import { utils } from 'ffjavascript';
15
+ // Cast imported modules to their types
16
+ const wtnsTyped = wtns;
17
+ const groth16Typed = groth16;
18
+ const utilsTyped = utils;
19
+ /**
20
+ * Generates a ZK proof using snarkjs and formats it for use on-chain
21
+ *
22
+ * @param input The circuit inputs to generate a proof for
23
+ * @param keyBasePath The base path for the circuit keys (.wasm and .zkey files)
24
+ * @param options Optional proof generation options (e.g., singleThread for Deno/Bun)
25
+ * @returns A proof object with formatted proof elements and public signals
26
+ */
27
+ async function prove(input, keyBasePath, options) {
28
+ // Detect if we should use single-threaded mode (for Deno/Bun compatibility)
29
+ const useSingleThread = options?.singleThread ?? shouldUseSingleThread();
30
+ // Single-thread options need to be passed to BOTH witness calculation AND proving
31
+ const singleThreadOpts = useSingleThread ? { singleThread: true } : undefined;
32
+ // Call fullProve with all parameters:
33
+ // 1. input, 2. wasmFile, 3. zkeyFile, 4. logger, 5. wtnsCalcOptions, 6. proverOptions
34
+ return await groth16Typed.fullProve(utilsTyped.stringifyBigInts(input), `${keyBasePath}.wasm`, `${keyBasePath}.zkey`, undefined, // logger parameter
35
+ singleThreadOpts, // wtnsCalcOptions (5th param) - for witness calculation
36
+ singleThreadOpts // proverOptions (6th param) - for proving
37
+ );
38
+ }
39
+ /**
40
+ * Detect if single-threaded mode should be used
41
+ */
42
+ function shouldUseSingleThread() {
43
+ // @ts-ignore - Deno global
44
+ if (typeof Deno !== 'undefined') {
45
+ return true; // Deno has worker issues
46
+ }
47
+ // @ts-ignore - Bun global
48
+ if (typeof Bun !== 'undefined') {
49
+ return true; // Bun may have worker issues
50
+ }
51
+ return false;
52
+ }
53
+ export function parseProofToBytesArray(proof, compressed = false) {
54
+ const proofJson = JSON.stringify(proof, null, 1);
55
+ const mydata = JSON.parse(proofJson.toString());
56
+ try {
57
+ for (const i in mydata) {
58
+ if (i == "pi_a" || i == "pi_c") {
59
+ for (const j in mydata[i]) {
60
+ mydata[i][j] = Array.from(utils.leInt2Buff(utils.unstringifyBigInts(mydata[i][j]), 32)).reverse();
61
+ }
62
+ }
63
+ else if (i == "pi_b") {
64
+ for (const j in mydata[i]) {
65
+ for (const z in mydata[i][j]) {
66
+ mydata[i][j][z] = Array.from(utils.leInt2Buff(utils.unstringifyBigInts(mydata[i][j][z]), 32));
67
+ }
68
+ }
69
+ }
70
+ }
71
+ if (compressed) {
72
+ const proofA = mydata.pi_a[0];
73
+ // negate proof by reversing the bitmask
74
+ const proofAIsPositive = yElementIsPositiveG1(new anchor.BN(mydata.pi_a[1]))
75
+ ? false
76
+ : true;
77
+ proofA[0] = addBitmaskToByte(proofA[0], proofAIsPositive);
78
+ const proofB = mydata.pi_b[0].flat().reverse();
79
+ const proofBY = mydata.pi_b[1].flat().reverse();
80
+ const proofBIsPositive = yElementIsPositiveG2(new anchor.BN(proofBY.slice(0, 32)), new anchor.BN(proofBY.slice(32, 64)));
81
+ proofB[0] = addBitmaskToByte(proofB[0], proofBIsPositive);
82
+ const proofC = mydata.pi_c[0];
83
+ const proofCIsPositive = yElementIsPositiveG1(new anchor.BN(mydata.pi_c[1]));
84
+ proofC[0] = addBitmaskToByte(proofC[0], proofCIsPositive);
85
+ return {
86
+ proofA,
87
+ proofB,
88
+ proofC,
89
+ };
90
+ }
91
+ return {
92
+ proofA: [mydata.pi_a[0], mydata.pi_a[1]].flat(),
93
+ proofB: [
94
+ mydata.pi_b[0].flat().reverse(),
95
+ mydata.pi_b[1].flat().reverse(),
96
+ ].flat(),
97
+ proofC: [mydata.pi_c[0], mydata.pi_c[1]].flat(),
98
+ };
99
+ }
100
+ catch (error) {
101
+ console.error("Error while parsing the proof.", error.message);
102
+ throw error;
103
+ }
104
+ }
105
+ // mainly used to parse the public signals of groth16 fullProve
106
+ export function parseToBytesArray(publicSignals) {
107
+ const publicInputsJson = JSON.stringify(publicSignals, null, 1);
108
+ const publicInputsBytesJson = JSON.parse(publicInputsJson.toString());
109
+ try {
110
+ const publicInputsBytes = new Array();
111
+ for (const i in publicInputsBytesJson) {
112
+ const ref = Array.from([
113
+ ...utils.leInt2Buff(utils.unstringifyBigInts(publicInputsBytesJson[i]), 32),
114
+ ]).reverse();
115
+ publicInputsBytes.push(ref);
116
+ }
117
+ return publicInputsBytes;
118
+ }
119
+ catch (error) {
120
+ console.error("Error while parsing public inputs.", error.message);
121
+ throw error;
122
+ }
123
+ }
124
+ function yElementIsPositiveG1(yElement) {
125
+ return yElement.lte(FIELD_SIZE.sub(yElement));
126
+ }
127
+ function yElementIsPositiveG2(yElement1, yElement2) {
128
+ const fieldMidpoint = FIELD_SIZE.div(new anchor.BN(2));
129
+ // Compare the first component of the y coordinate
130
+ if (yElement1.lt(fieldMidpoint)) {
131
+ return true;
132
+ }
133
+ else if (yElement1.gt(fieldMidpoint)) {
134
+ return false;
135
+ }
136
+ // If the first component is equal to the midpoint, compare the second component
137
+ return yElement2.lt(fieldMidpoint);
138
+ }
139
+ function addBitmaskToByte(byte, yIsPositive) {
140
+ if (!yIsPositive) {
141
+ return (byte |= 1 << 7);
142
+ }
143
+ else {
144
+ return byte;
145
+ }
146
+ }
147
+ export { prove };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Utility functions for ZK Cash
3
+ *
4
+ * Provides common utility functions for the ZK Cash system
5
+ * Based on: https://github.com/tornadocash/tornado-nova
6
+ */
7
+ import BN from 'bn.js';
8
+ import { Utxo } from '../models/utxo.js';
9
+ import { PublicKey } from '@solana/web3.js';
10
+ /**
11
+ * Calculate deposit fee based on deposit amount and fee rate
12
+ * @param depositAmount Amount being deposited in lamports
13
+ * @returns Fee amount in lamports
14
+ */
15
+ export declare function calculateDepositFee(depositAmount: number): Promise<number>;
16
+ /**
17
+ * Calculate withdrawal fee based on withdrawal amount and fee rate
18
+ * @param withdrawalAmount Amount being withdrawn in lamports
19
+ * @returns Fee amount in lamports
20
+ */
21
+ export declare function calculateWithdrawalFee(withdrawalAmount: number): Promise<number>;
22
+ /**
23
+ * Mock encryption function - in real implementation this would be proper encryption
24
+ * For testing, we just return a fixed prefix to ensure consistent extDataHash
25
+ * @param value Value to encrypt
26
+ * @returns Encrypted string representation
27
+ */
28
+ export declare function mockEncrypt(value: Utxo): string;
29
+ /**
30
+ * Calculates the hash of ext data using Borsh serialization
31
+ * @param extData External data object containing recipient, amount, encrypted outputs, fee, fee recipient, and mint address
32
+ * @returns The hash as a Uint8Array (32 bytes)
33
+ */
34
+ export declare function getExtDataHash(extData: {
35
+ recipient: string | PublicKey;
36
+ extAmount: string | number | BN;
37
+ encryptedOutput1?: string | Uint8Array;
38
+ encryptedOutput2?: string | Uint8Array;
39
+ fee: string | number | BN;
40
+ feeRecipient: string | PublicKey;
41
+ mintAddress: string | PublicKey;
42
+ }): Uint8Array;
43
+ export declare function fetchMerkleProof(commitment: string, tokenName?: string): Promise<{
44
+ pathElements: string[];
45
+ pathIndices: number[];
46
+ }>;
47
+ export declare function findNullifierPDAs(proof: any): {
48
+ nullifier0PDA: PublicKey;
49
+ nullifier1PDA: PublicKey;
50
+ };
51
+ export declare function queryRemoteTreeState(tokenName?: string): Promise<{
52
+ root: string;
53
+ nextIndex: number;
54
+ }>;
55
+ export declare function getProgramAccounts(): {
56
+ treeAccount: PublicKey;
57
+ treeTokenAccount: PublicKey;
58
+ globalConfigAccount: PublicKey;
59
+ };
60
+ /**
61
+ * Get tree account address for a given token/mint
62
+ * Uses specific addresses for SOL (NOVASOL), NOVA, and other tokens
63
+ */
64
+ export declare function getTreeAccountForToken(mintAddress?: PublicKey): PublicKey;
65
+ export declare function findCrossCheckNullifierPDAs(proof: any): {
66
+ nullifier2PDA: PublicKey;
67
+ nullifier3PDA: PublicKey;
68
+ };
69
+ export declare function getMintAddressField(mint: PublicKey): string;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Utility functions for ZK Cash
3
+ *
4
+ * Provides common utility functions for the ZK Cash system
5
+ * Based on: https://github.com/tornadocash/tornado-nova
6
+ */
7
+ import BN from 'bn.js';
8
+ import * as borsh from 'borsh';
9
+ import { sha256 } from '@ethersproject/sha2';
10
+ import { PublicKey } from '@solana/web3.js';
11
+ import { RELAYER_API_URL, PROGRAM_ID, NOVA_MINT, NOVA_TREE_ADDRESS, NOVASOL_TREE_ADDRESS } from './constants.js';
12
+ import { logger } from './logger.js';
13
+ import { getConfig } from '../config.js';
14
+ /**
15
+ * Calculate deposit fee based on deposit amount and fee rate
16
+ * @param depositAmount Amount being deposited in lamports
17
+ * @returns Fee amount in lamports
18
+ */
19
+ export async function calculateDepositFee(depositAmount) {
20
+ return Math.floor(depositAmount * (await getConfig('deposit_fee_rate')) / 10000);
21
+ }
22
+ /**
23
+ * Calculate withdrawal fee based on withdrawal amount and fee rate
24
+ * @param withdrawalAmount Amount being withdrawn in lamports
25
+ * @returns Fee amount in lamports
26
+ */
27
+ export async function calculateWithdrawalFee(withdrawalAmount) {
28
+ return Math.floor(withdrawalAmount * (await getConfig('withdraw_fee_rate')) / 10000);
29
+ }
30
+ /**
31
+ * Mock encryption function - in real implementation this would be proper encryption
32
+ * For testing, we just return a fixed prefix to ensure consistent extDataHash
33
+ * @param value Value to encrypt
34
+ * @returns Encrypted string representation
35
+ */
36
+ export function mockEncrypt(value) {
37
+ return JSON.stringify(value);
38
+ }
39
+ /**
40
+ * Calculates the hash of ext data using Borsh serialization
41
+ * @param extData External data object containing recipient, amount, encrypted outputs, fee, fee recipient, and mint address
42
+ * @returns The hash as a Uint8Array (32 bytes)
43
+ */
44
+ export function getExtDataHash(extData) {
45
+ // Convert all inputs to their appropriate types
46
+ const recipient = extData.recipient instanceof PublicKey
47
+ ? extData.recipient
48
+ : new PublicKey(extData.recipient);
49
+ const feeRecipient = extData.feeRecipient instanceof PublicKey
50
+ ? extData.feeRecipient
51
+ : new PublicKey(extData.feeRecipient);
52
+ const mintAddress = extData.mintAddress instanceof PublicKey
53
+ ? extData.mintAddress
54
+ : new PublicKey(extData.mintAddress);
55
+ // Convert to BN for proper i64/u64 handling
56
+ const extAmount = new BN(extData.extAmount.toString());
57
+ const fee = new BN(extData.fee.toString());
58
+ // Handle encrypted outputs - they might not be present in Account Data Separation approach
59
+ const encryptedOutput1 = extData.encryptedOutput1
60
+ ? Buffer.from(extData.encryptedOutput1)
61
+ : Buffer.alloc(0); // Empty buffer if not provided
62
+ const encryptedOutput2 = extData.encryptedOutput2
63
+ ? Buffer.from(extData.encryptedOutput2)
64
+ : Buffer.alloc(0); // Empty buffer if not provided
65
+ // Define the borsh schema matching the Rust struct
66
+ const schema = {
67
+ struct: {
68
+ recipient: { array: { type: 'u8', len: 32 } },
69
+ extAmount: 'i64',
70
+ encryptedOutput1: { array: { type: 'u8' } },
71
+ encryptedOutput2: { array: { type: 'u8' } },
72
+ fee: 'u64',
73
+ feeRecipient: { array: { type: 'u8', len: 32 } },
74
+ mintAddress: { array: { type: 'u8', len: 32 } },
75
+ }
76
+ };
77
+ const value = {
78
+ recipient: recipient.toBytes(),
79
+ extAmount: extAmount, // BN instance - Borsh handles it correctly with i64 type
80
+ encryptedOutput1: encryptedOutput1,
81
+ encryptedOutput2: encryptedOutput2,
82
+ fee: fee, // BN instance - Borsh handles it correctly with u64 type
83
+ feeRecipient: feeRecipient.toBytes(),
84
+ mintAddress: mintAddress.toBytes(),
85
+ };
86
+ // Serialize with Borsh
87
+ const serializedData = borsh.serialize(schema, value);
88
+ // Calculate the SHA-256 hash
89
+ const hashHex = sha256(serializedData);
90
+ // Convert from hex string to Uint8Array
91
+ return Buffer.from(hashHex.slice(2), 'hex');
92
+ }
93
+ // Function to fetch Merkle proof from API for a given commitment
94
+ export async function fetchMerkleProof(commitment, tokenName) {
95
+ try {
96
+ logger.debug(`Fetching Merkle proof for commitment: ${commitment}`);
97
+ let url = `${RELAYER_API_URL}/merkle/proof/${commitment}`;
98
+ if (tokenName) {
99
+ url += '?token=' + tokenName;
100
+ }
101
+ const response = await fetch(url);
102
+ if (!response.ok) {
103
+ throw new Error(`Failed to fetch Merkle proof: ${url}`);
104
+ }
105
+ const data = await response.json();
106
+ logger.debug(`✓ Fetched Merkle proof with ${data.pathElements.length} elements`);
107
+ return data;
108
+ }
109
+ catch (error) {
110
+ console.error(`Failed to fetch Merkle proof for commitment ${commitment}:`, error);
111
+ throw error;
112
+ }
113
+ }
114
+ // Find nullifier PDAs for the given proof
115
+ export function findNullifierPDAs(proof) {
116
+ const [nullifier0PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier0"), Buffer.from(proof.inputNullifiers[0])], PROGRAM_ID);
117
+ const [nullifier1PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier1"), Buffer.from(proof.inputNullifiers[1])], PROGRAM_ID);
118
+ return { nullifier0PDA, nullifier1PDA };
119
+ }
120
+ // Function to query remote tree state from indexer API
121
+ export async function queryRemoteTreeState(tokenName) {
122
+ try {
123
+ logger.debug('Fetching Merkle root and nextIndex from API...');
124
+ let url = `${RELAYER_API_URL}/merkle/root`;
125
+ if (tokenName) {
126
+ url += '?token=' + tokenName;
127
+ }
128
+ const response = await fetch(url);
129
+ if (!response.ok) {
130
+ throw new Error(`Failed to fetch Merkle root and nextIndex: ${response.status} ${response.statusText}`);
131
+ }
132
+ const data = await response.json();
133
+ logger.debug(`Fetched root from API: ${data.root}`);
134
+ logger.debug(`Fetched nextIndex from API: ${data.nextIndex}`);
135
+ return data;
136
+ }
137
+ catch (error) {
138
+ console.error('Failed to fetch root and nextIndex from API:', error);
139
+ throw error;
140
+ }
141
+ }
142
+ export function getProgramAccounts() {
143
+ // Use NOVASOL tree address for SOL transactions (NOVA's SOL tree)
144
+ const treeAccount = NOVASOL_TREE_ADDRESS;
145
+ const [treeTokenAccount] = PublicKey.findProgramAddressSync([Buffer.from('tree_token')], PROGRAM_ID);
146
+ const [globalConfigAccount] = PublicKey.findProgramAddressSync([Buffer.from('global_config')], PROGRAM_ID);
147
+ return { treeAccount, treeTokenAccount, globalConfigAccount };
148
+ }
149
+ /**
150
+ * Get tree account address for a given token/mint
151
+ * Uses specific addresses for SOL (NOVASOL), NOVA, and other tokens
152
+ */
153
+ export function getTreeAccountForToken(mintAddress) {
154
+ if (!mintAddress) {
155
+ // SOL tree - use NOVASOL tree address
156
+ return NOVASOL_TREE_ADDRESS;
157
+ }
158
+ // Check if it's NOVA token and use specific tree address
159
+ if (mintAddress.equals(NOVA_MINT)) {
160
+ return NOVA_TREE_ADDRESS;
161
+ }
162
+ // For other SPL tokens, derive PDA with mint address
163
+ const [treeAccount] = PublicKey.findProgramAddressSync([Buffer.from('merkle_tree'), mintAddress.toBuffer()], PROGRAM_ID);
164
+ return treeAccount;
165
+ }
166
+ export function findCrossCheckNullifierPDAs(proof) {
167
+ const [nullifier2PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier0"), Buffer.from(proof.inputNullifiers[1])], PROGRAM_ID);
168
+ const [nullifier3PDA] = PublicKey.findProgramAddressSync([Buffer.from("nullifier1"), Buffer.from(proof.inputNullifiers[0])], PROGRAM_ID);
169
+ return { nullifier2PDA, nullifier3PDA };
170
+ }
171
+ export function getMintAddressField(mint) {
172
+ const mintStr = mint.toString();
173
+ // Special case for SOL (system program)
174
+ if (mintStr === '11111111111111111111111111111112') {
175
+ return mintStr;
176
+ }
177
+ // For SPL tokens (USDC, USDT, etc): use first 31 bytes (248 bits)
178
+ // This provides better collision resistance than 8 bytes while still fitting in the field
179
+ // We will only suppport private SOL, USDC and USDT send, so there won't be any collision.
180
+ const mintBytes = mint.toBytes();
181
+ return new BN(mintBytes.slice(0, 31), 'be').toString();
182
+ }
@@ -0,0 +1,21 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ import * as hasher from '@lightprotocol/hasher.rs';
3
+ import { EncryptionService } from './utils/encryption.js';
4
+ type WithdrawParams = {
5
+ publicKey: PublicKey;
6
+ connection: Connection;
7
+ amount_in_lamports: number;
8
+ keyBasePath: string;
9
+ encryptionService: EncryptionService;
10
+ lightWasm: hasher.LightWasm;
11
+ recipient: PublicKey;
12
+ storage: Storage;
13
+ };
14
+ export declare function withdraw({ recipient, lightWasm, storage, publicKey, connection, amount_in_lamports, encryptionService, keyBasePath }: WithdrawParams): Promise<{
15
+ isPartial: boolean;
16
+ tx: string;
17
+ recipient: string;
18
+ amount_in_lamports: number;
19
+ fee_in_lamports: number;
20
+ }>;
21
+ export {};