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