@cloak.ag/sdk 1.0.3 → 1.0.4

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.
package/dist/index.d.cts CHANGED
@@ -34,7 +34,7 @@ interface CloakNote {
34
34
  version: string;
35
35
  /** Amount in lamports */
36
36
  amount: number;
37
- /** Blake3 commitment hash (hex) */
37
+ /** Commitment hash (hex) */
38
38
  commitment: string;
39
39
  /** Spending secret key (hex, 64 chars) */
40
40
  sk_spend: string;
@@ -210,50 +210,6 @@ interface WithdrawOptions extends TransferOptions {
210
210
  /** Specific amount to withdraw in lamports (if not withdrawing all) */
211
211
  amount?: number;
212
212
  }
213
- /**
214
- * SP1 proof inputs for zero-knowledge proof generation
215
- */
216
- interface SP1ProofInputs {
217
- privateInputs: {
218
- amount: number;
219
- r: string;
220
- sk_spend: string;
221
- leaf_index: number;
222
- merkle_path: {
223
- path_elements: string[];
224
- path_indices: number[];
225
- };
226
- };
227
- publicInputs: {
228
- root: string;
229
- nf: string;
230
- outputs_hash: string;
231
- amount: number;
232
- };
233
- outputs: Array<{
234
- address: string;
235
- amount: number;
236
- }>;
237
- /**
238
- * Optional swap parameters for token swaps
239
- * When provided, the proof will be for a swap transaction
240
- */
241
- swapParams?: {
242
- output_mint: string;
243
- recipient_ata: string;
244
- min_output_amount: number;
245
- };
246
- }
247
- /**
248
- * Result from proof generation
249
- */
250
- interface SP1ProofResult {
251
- success: boolean;
252
- proof?: string;
253
- publicInputs?: string;
254
- generationTimeMs: number;
255
- error?: string;
256
- }
257
213
  /**
258
214
  * Merkle root response from indexer
259
215
  */
@@ -317,6 +273,13 @@ interface SwapOptions extends TransferOptions {
317
273
  outAmount: number;
318
274
  minOutputAmount: number;
319
275
  }>;
276
+ /**
277
+ * Recipient's associated token account for the output token.
278
+ * If not provided, will be computed automatically (requires @solana/spl-token).
279
+ * For browser environments, it's recommended to compute this in the frontend
280
+ * where @solana/spl-token is properly bundled.
281
+ */
282
+ recipientAta?: string;
320
283
  }
321
284
  /**
322
285
  * Result from a swap operation
@@ -1516,88 +1479,6 @@ declare class IndexerService {
1516
1479
  }>;
1517
1480
  }
1518
1481
 
1519
- /**
1520
- * Options for proof generation
1521
- */
1522
- interface ProofGenerationOptions {
1523
- /** Progress callback - called with percentage (0-100) */
1524
- onProgress?: (progress: number) => void;
1525
- /** Called when proof generation starts */
1526
- onStart?: () => void;
1527
- /** Called on successful proof generation */
1528
- onSuccess?: (result: SP1ProofResult) => void;
1529
- /** Called on error */
1530
- onError?: (error: string) => void;
1531
- /** Custom timeout in milliseconds */
1532
- timeout?: number;
1533
- }
1534
- /**
1535
- * Prover Service Client (Legacy)
1536
- *
1537
- * Handles zero-knowledge proof generation via the backend prover service.
1538
- *
1539
- * ⚠️ DEPRECATED: This implementation sends private inputs to a backend service.
1540
- *
1541
- * **Use ArtifactProverService instead** for privacy-preserving proof generation
1542
- * where private inputs are uploaded directly to TEE, never passing through backend.
1543
- *
1544
- * This class is kept for backward compatibility but is not used by CloakSDK anymore.
1545
- */
1546
- declare class ProverService {
1547
- private indexerUrl;
1548
- private timeout;
1549
- /**
1550
- * Create a new Prover Service client
1551
- *
1552
- * @param indexerUrl - Indexer/Prover service base URL
1553
- * @param timeout - Proof generation timeout in ms (default: 5 minutes)
1554
- */
1555
- constructor(indexerUrl: string, timeout?: number);
1556
- /**
1557
- * Generate a zero-knowledge proof for withdrawal
1558
- *
1559
- * This process typically takes 30-180 seconds depending on the backend.
1560
- *
1561
- * @param inputs - Circuit inputs (private + public + outputs)
1562
- * @param options - Optional progress tracking and callbacks
1563
- * @returns Proof result with hex-encoded proof and public inputs
1564
- *
1565
- * @example
1566
- * ```typescript
1567
- * const result = await prover.generateProof(inputs);
1568
- * if (result.success) {
1569
- * console.log(`Proof: ${result.proof}`);
1570
- * }
1571
- * ```
1572
- *
1573
- * @example
1574
- * ```typescript
1575
- * // With progress tracking
1576
- * const result = await prover.generateProof(inputs, {
1577
- * onProgress: (progress) => console.log(`Progress: ${progress}%`),
1578
- * onStart: () => console.log("Starting proof generation..."),
1579
- * onSuccess: (result) => console.log("Proof generated!"),
1580
- * onError: (error) => console.error("Failed:", error)
1581
- * });
1582
- * ```
1583
- */
1584
- generateProof(inputs: SP1ProofInputs, options?: ProofGenerationOptions): Promise<SP1ProofResult>;
1585
- /**
1586
- * Check if the prover service is available
1587
- *
1588
- * @returns True if service is healthy
1589
- */
1590
- healthCheck(): Promise<boolean>;
1591
- /**
1592
- * Get the configured timeout
1593
- */
1594
- getTimeout(): number;
1595
- /**
1596
- * Set a new timeout
1597
- */
1598
- setTimeout(timeout: number): void;
1599
- }
1600
-
1601
1482
  /**
1602
1483
  * Relay Service Client
1603
1484
  *
@@ -2007,4 +1888,4 @@ declare function generateWithdrawSwapProof(inputs: WithdrawSwapInputs, circuitsP
2007
1888
 
2008
1889
  declare const VERSION = "1.0.0";
2009
1890
 
2010
- export { CLOAK_PROGRAM_ID, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, CloakSDK, type DepositInstructionParams, type DepositOptions, DepositRecoveryService, type DepositResult, type DepositStatus, type EncryptedNote, FIXED_FEE_LAMPORTS, type Groth16Proof, IndexerService, LAMPORTS_PER_SOL, LocalStorageAdapter, type MasterKey, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, type Network, type NoteData, type NotesRangeResponse, type ProofGenerationOptions, type ProofResult, ProverService, type RecoveryOptions, type RecoveryResult, RelayService, type SP1ProofInputs, type SP1ProofResult, type ScanNotesOptions, type ScannedNote, type ShieldPoolPDAs, type SpendKey, type StorageAdapter, type SwapOptions, type SwapParams, type SwapResult, type Transfer, type TransferOptions, type TransferResult, type TxStatus, VARIABLE_FEE_RATE, VERSION, type ViewKey, type WalletAdapter, type WithdrawOptions, type WithdrawRegularInputs, type WithdrawSwapInputs, bigintToBytes32, buildPublicInputsBytes, bytesToHex, calculateFee, calculateRelayFee, computeCommitment, computeMerkleRoot, computeNullifier, computeNullifierAsync, computeNullifierSync, computeOutputsHash, computeOutputsHashAsync, computeOutputsHashSync, computeSwapOutputsHash, computeSwapOutputsHashAsync, computeSwapOutputsHashSync, copyNoteToClipboard, createCloakError, createDepositInstruction, deriveSpendKey, deriveViewKey, detectNetworkFromRpcUrl, downloadNote, encodeNoteSimple, encryptNoteForRecipient, exportKeys, exportNote, exportWalletKeys, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, formatAmount, formatErrorForLogging, generateCloakKeys, generateCommitment, generateCommitmentAsync, generateMasterSeed, generateNote, generateNoteFromWallet, generateWithdrawRegularProof, generateWithdrawSwapProof, getAddressExplorerUrl, getDistributableAmount, getExplorerUrl, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getViewKey, hexToBigint, hexToBytes, importKeys, importWalletKeys, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawable, keypairToAdapter, parseAmount, parseNote, parseTransactionError, poseidonHash, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, proofToBytes, pubkeyToLimbs, randomBytes, scanNotesForWallet, sendTransaction, serializeNote, signTransaction, splitTo2Limbs, tryDecryptNote, updateNoteWithDeposit, validateDepositParams, validateNote, validateOutputsSum, validateTransfers, validateWalletConnected, validateWithdrawableNote };
1891
+ export { CLOAK_PROGRAM_ID, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, CloakSDK, type DepositInstructionParams, type DepositOptions, DepositRecoveryService, type DepositResult, type DepositStatus, type EncryptedNote, FIXED_FEE_LAMPORTS, type Groth16Proof, IndexerService, LAMPORTS_PER_SOL, LocalStorageAdapter, type MasterKey, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, type Network, type NoteData, type NotesRangeResponse, type ProofResult, type RecoveryOptions, type RecoveryResult, RelayService, type ScanNotesOptions, type ScannedNote, type ShieldPoolPDAs, type SpendKey, type StorageAdapter, type SwapOptions, type SwapParams, type SwapResult, type Transfer, type TransferOptions, type TransferResult, type TxStatus, VARIABLE_FEE_RATE, VERSION, type ViewKey, type WalletAdapter, type WithdrawOptions, type WithdrawRegularInputs, type WithdrawSwapInputs, bigintToBytes32, buildPublicInputsBytes, bytesToHex, calculateFee, calculateRelayFee, computeCommitment, computeMerkleRoot, computeNullifier, computeNullifierAsync, computeNullifierSync, computeOutputsHash, computeOutputsHashAsync, computeOutputsHashSync, computeSwapOutputsHash, computeSwapOutputsHashAsync, computeSwapOutputsHashSync, copyNoteToClipboard, createCloakError, createDepositInstruction, deriveSpendKey, deriveViewKey, detectNetworkFromRpcUrl, downloadNote, encodeNoteSimple, encryptNoteForRecipient, exportKeys, exportNote, exportWalletKeys, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, formatAmount, formatErrorForLogging, generateCloakKeys, generateCommitment, generateCommitmentAsync, generateMasterSeed, generateNote, generateNoteFromWallet, generateWithdrawRegularProof, generateWithdrawSwapProof, getAddressExplorerUrl, getDistributableAmount, getExplorerUrl, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getViewKey, hexToBigint, hexToBytes, importKeys, importWalletKeys, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawable, keypairToAdapter, parseAmount, parseNote, parseTransactionError, poseidonHash, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, proofToBytes, pubkeyToLimbs, randomBytes, scanNotesForWallet, sendTransaction, serializeNote, signTransaction, splitTo2Limbs, tryDecryptNote, updateNoteWithDeposit, validateDepositParams, validateNote, validateOutputsSum, validateTransfers, validateWalletConnected, validateWithdrawableNote };
package/dist/index.d.ts CHANGED
@@ -34,7 +34,7 @@ interface CloakNote {
34
34
  version: string;
35
35
  /** Amount in lamports */
36
36
  amount: number;
37
- /** Blake3 commitment hash (hex) */
37
+ /** Commitment hash (hex) */
38
38
  commitment: string;
39
39
  /** Spending secret key (hex, 64 chars) */
40
40
  sk_spend: string;
@@ -210,50 +210,6 @@ interface WithdrawOptions extends TransferOptions {
210
210
  /** Specific amount to withdraw in lamports (if not withdrawing all) */
211
211
  amount?: number;
212
212
  }
213
- /**
214
- * SP1 proof inputs for zero-knowledge proof generation
215
- */
216
- interface SP1ProofInputs {
217
- privateInputs: {
218
- amount: number;
219
- r: string;
220
- sk_spend: string;
221
- leaf_index: number;
222
- merkle_path: {
223
- path_elements: string[];
224
- path_indices: number[];
225
- };
226
- };
227
- publicInputs: {
228
- root: string;
229
- nf: string;
230
- outputs_hash: string;
231
- amount: number;
232
- };
233
- outputs: Array<{
234
- address: string;
235
- amount: number;
236
- }>;
237
- /**
238
- * Optional swap parameters for token swaps
239
- * When provided, the proof will be for a swap transaction
240
- */
241
- swapParams?: {
242
- output_mint: string;
243
- recipient_ata: string;
244
- min_output_amount: number;
245
- };
246
- }
247
- /**
248
- * Result from proof generation
249
- */
250
- interface SP1ProofResult {
251
- success: boolean;
252
- proof?: string;
253
- publicInputs?: string;
254
- generationTimeMs: number;
255
- error?: string;
256
- }
257
213
  /**
258
214
  * Merkle root response from indexer
259
215
  */
@@ -317,6 +273,13 @@ interface SwapOptions extends TransferOptions {
317
273
  outAmount: number;
318
274
  minOutputAmount: number;
319
275
  }>;
276
+ /**
277
+ * Recipient's associated token account for the output token.
278
+ * If not provided, will be computed automatically (requires @solana/spl-token).
279
+ * For browser environments, it's recommended to compute this in the frontend
280
+ * where @solana/spl-token is properly bundled.
281
+ */
282
+ recipientAta?: string;
320
283
  }
321
284
  /**
322
285
  * Result from a swap operation
@@ -1516,88 +1479,6 @@ declare class IndexerService {
1516
1479
  }>;
1517
1480
  }
1518
1481
 
1519
- /**
1520
- * Options for proof generation
1521
- */
1522
- interface ProofGenerationOptions {
1523
- /** Progress callback - called with percentage (0-100) */
1524
- onProgress?: (progress: number) => void;
1525
- /** Called when proof generation starts */
1526
- onStart?: () => void;
1527
- /** Called on successful proof generation */
1528
- onSuccess?: (result: SP1ProofResult) => void;
1529
- /** Called on error */
1530
- onError?: (error: string) => void;
1531
- /** Custom timeout in milliseconds */
1532
- timeout?: number;
1533
- }
1534
- /**
1535
- * Prover Service Client (Legacy)
1536
- *
1537
- * Handles zero-knowledge proof generation via the backend prover service.
1538
- *
1539
- * ⚠️ DEPRECATED: This implementation sends private inputs to a backend service.
1540
- *
1541
- * **Use ArtifactProverService instead** for privacy-preserving proof generation
1542
- * where private inputs are uploaded directly to TEE, never passing through backend.
1543
- *
1544
- * This class is kept for backward compatibility but is not used by CloakSDK anymore.
1545
- */
1546
- declare class ProverService {
1547
- private indexerUrl;
1548
- private timeout;
1549
- /**
1550
- * Create a new Prover Service client
1551
- *
1552
- * @param indexerUrl - Indexer/Prover service base URL
1553
- * @param timeout - Proof generation timeout in ms (default: 5 minutes)
1554
- */
1555
- constructor(indexerUrl: string, timeout?: number);
1556
- /**
1557
- * Generate a zero-knowledge proof for withdrawal
1558
- *
1559
- * This process typically takes 30-180 seconds depending on the backend.
1560
- *
1561
- * @param inputs - Circuit inputs (private + public + outputs)
1562
- * @param options - Optional progress tracking and callbacks
1563
- * @returns Proof result with hex-encoded proof and public inputs
1564
- *
1565
- * @example
1566
- * ```typescript
1567
- * const result = await prover.generateProof(inputs);
1568
- * if (result.success) {
1569
- * console.log(`Proof: ${result.proof}`);
1570
- * }
1571
- * ```
1572
- *
1573
- * @example
1574
- * ```typescript
1575
- * // With progress tracking
1576
- * const result = await prover.generateProof(inputs, {
1577
- * onProgress: (progress) => console.log(`Progress: ${progress}%`),
1578
- * onStart: () => console.log("Starting proof generation..."),
1579
- * onSuccess: (result) => console.log("Proof generated!"),
1580
- * onError: (error) => console.error("Failed:", error)
1581
- * });
1582
- * ```
1583
- */
1584
- generateProof(inputs: SP1ProofInputs, options?: ProofGenerationOptions): Promise<SP1ProofResult>;
1585
- /**
1586
- * Check if the prover service is available
1587
- *
1588
- * @returns True if service is healthy
1589
- */
1590
- healthCheck(): Promise<boolean>;
1591
- /**
1592
- * Get the configured timeout
1593
- */
1594
- getTimeout(): number;
1595
- /**
1596
- * Set a new timeout
1597
- */
1598
- setTimeout(timeout: number): void;
1599
- }
1600
-
1601
1482
  /**
1602
1483
  * Relay Service Client
1603
1484
  *
@@ -2007,4 +1888,4 @@ declare function generateWithdrawSwapProof(inputs: WithdrawSwapInputs, circuitsP
2007
1888
 
2008
1889
  declare const VERSION = "1.0.0";
2009
1890
 
2010
- export { CLOAK_PROGRAM_ID, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, CloakSDK, type DepositInstructionParams, type DepositOptions, DepositRecoveryService, type DepositResult, type DepositStatus, type EncryptedNote, FIXED_FEE_LAMPORTS, type Groth16Proof, IndexerService, LAMPORTS_PER_SOL, LocalStorageAdapter, type MasterKey, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, type Network, type NoteData, type NotesRangeResponse, type ProofGenerationOptions, type ProofResult, ProverService, type RecoveryOptions, type RecoveryResult, RelayService, type SP1ProofInputs, type SP1ProofResult, type ScanNotesOptions, type ScannedNote, type ShieldPoolPDAs, type SpendKey, type StorageAdapter, type SwapOptions, type SwapParams, type SwapResult, type Transfer, type TransferOptions, type TransferResult, type TxStatus, VARIABLE_FEE_RATE, VERSION, type ViewKey, type WalletAdapter, type WithdrawOptions, type WithdrawRegularInputs, type WithdrawSwapInputs, bigintToBytes32, buildPublicInputsBytes, bytesToHex, calculateFee, calculateRelayFee, computeCommitment, computeMerkleRoot, computeNullifier, computeNullifierAsync, computeNullifierSync, computeOutputsHash, computeOutputsHashAsync, computeOutputsHashSync, computeSwapOutputsHash, computeSwapOutputsHashAsync, computeSwapOutputsHashSync, copyNoteToClipboard, createCloakError, createDepositInstruction, deriveSpendKey, deriveViewKey, detectNetworkFromRpcUrl, downloadNote, encodeNoteSimple, encryptNoteForRecipient, exportKeys, exportNote, exportWalletKeys, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, formatAmount, formatErrorForLogging, generateCloakKeys, generateCommitment, generateCommitmentAsync, generateMasterSeed, generateNote, generateNoteFromWallet, generateWithdrawRegularProof, generateWithdrawSwapProof, getAddressExplorerUrl, getDistributableAmount, getExplorerUrl, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getViewKey, hexToBigint, hexToBytes, importKeys, importWalletKeys, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawable, keypairToAdapter, parseAmount, parseNote, parseTransactionError, poseidonHash, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, proofToBytes, pubkeyToLimbs, randomBytes, scanNotesForWallet, sendTransaction, serializeNote, signTransaction, splitTo2Limbs, tryDecryptNote, updateNoteWithDeposit, validateDepositParams, validateNote, validateOutputsSum, validateTransfers, validateWalletConnected, validateWithdrawableNote };
1891
+ export { CLOAK_PROGRAM_ID, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, CloakSDK, type DepositInstructionParams, type DepositOptions, DepositRecoveryService, type DepositResult, type DepositStatus, type EncryptedNote, FIXED_FEE_LAMPORTS, type Groth16Proof, IndexerService, LAMPORTS_PER_SOL, LocalStorageAdapter, type MasterKey, type MaxLengthArray, MemoryStorageAdapter, type MerkleProof, type MerkleRootResponse, type Network, type NoteData, type NotesRangeResponse, type ProofResult, type RecoveryOptions, type RecoveryResult, RelayService, type ScanNotesOptions, type ScannedNote, type ShieldPoolPDAs, type SpendKey, type StorageAdapter, type SwapOptions, type SwapParams, type SwapResult, type Transfer, type TransferOptions, type TransferResult, type TxStatus, VARIABLE_FEE_RATE, VERSION, type ViewKey, type WalletAdapter, type WithdrawOptions, type WithdrawRegularInputs, type WithdrawSwapInputs, bigintToBytes32, buildPublicInputsBytes, bytesToHex, calculateFee, calculateRelayFee, computeCommitment, computeMerkleRoot, computeNullifier, computeNullifierAsync, computeNullifierSync, computeOutputsHash, computeOutputsHashAsync, computeOutputsHashSync, computeSwapOutputsHash, computeSwapOutputsHashAsync, computeSwapOutputsHashSync, copyNoteToClipboard, createCloakError, createDepositInstruction, deriveSpendKey, deriveViewKey, detectNetworkFromRpcUrl, downloadNote, encodeNoteSimple, encryptNoteForRecipient, exportKeys, exportNote, exportWalletKeys, filterNotesByNetwork, filterWithdrawableNotes, findNoteByCommitment, formatAmount, formatErrorForLogging, generateCloakKeys, generateCommitment, generateCommitmentAsync, generateMasterSeed, generateNote, generateNoteFromWallet, generateWithdrawRegularProof, generateWithdrawSwapProof, getAddressExplorerUrl, getDistributableAmount, getExplorerUrl, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getViewKey, hexToBigint, hexToBytes, importKeys, importWalletKeys, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawable, keypairToAdapter, parseAmount, parseNote, parseTransactionError, poseidonHash, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, proofToBytes, pubkeyToLimbs, randomBytes, scanNotesForWallet, sendTransaction, serializeNote, signTransaction, splitTo2Limbs, tryDecryptNote, updateNoteWithDeposit, validateDepositParams, validateNote, validateOutputsSum, validateTransfers, validateWalletConnected, validateWithdrawableNote };
package/dist/index.js CHANGED
@@ -1714,11 +1714,7 @@ async function generateWithdrawRegularProof(inputs, circuitsPath) {
1714
1714
  var_fee: inputs.var_fee.toString(),
1715
1715
  rem: inputs.rem.toString()
1716
1716
  };
1717
- const { proof, publicSignals } = await snarkjs.groth16.fullProve(
1718
- circuitInputs,
1719
- wasmPath,
1720
- zkeyPath
1721
- );
1717
+ const { proof, publicSignals } = await snarkjs.groth16.fullProve(circuitInputs, wasmPath, zkeyPath);
1722
1718
  const proofBytes = proofToBytes(proof);
1723
1719
  return {
1724
1720
  proof,
@@ -2194,17 +2190,10 @@ var CloakSDK = class {
2194
2190
  const feeBps = Math.ceil(protocolFee * 1e4 / note.amount);
2195
2191
  const distributableAmount = getDistributableAmount2(note.amount);
2196
2192
  validateTransfers(recipients, distributableAmount);
2197
- let merkleProof;
2198
- let merkleRoot;
2199
- if (note.merkleProof && note.root) {
2200
- merkleProof = {
2201
- pathElements: note.merkleProof.pathElements,
2202
- pathIndices: note.merkleProof.pathIndices
2203
- };
2204
- merkleRoot = note.root;
2205
- } else {
2206
- merkleProof = await this.indexer.getMerkleProof(note.leafIndex);
2207
- merkleRoot = merkleProof.root || (await this.indexer.getMerkleRoot()).root;
2193
+ const merkleProof = await this.indexer.getMerkleProof(note.leafIndex);
2194
+ const merkleRoot = merkleProof.root || (await this.indexer.getMerkleRoot()).root;
2195
+ if (!merkleRoot) {
2196
+ throw new Error("Failed to get Merkle root from indexer");
2208
2197
  }
2209
2198
  const nullifier = await computeNullifierAsync(note.sk_spend, note.leafIndex);
2210
2199
  const nullifierHex = nullifier.toString(16).padStart(64, "0");
@@ -2278,6 +2267,13 @@ var CloakSDK = class {
2278
2267
  }
2279
2268
  const sk = splitTo2Limbs(sk_spend_bigint);
2280
2269
  const r = splitTo2Limbs(r_bigint);
2270
+ const computedCommitment = await computeCommitment(amount_bigint, r_bigint, sk_spend_bigint);
2271
+ const noteCommitment = BigInt("0x" + note.commitment);
2272
+ if (computedCommitment !== noteCommitment) {
2273
+ throw new Error(
2274
+ `Commitment mismatch! Computed: ${computedCommitment.toString(16)}, Note: ${note.commitment}. This means the note's sk_spend, r, or amount doesn't match what was deposited.`
2275
+ );
2276
+ }
2281
2277
  const proofInputs = {
2282
2278
  root: root_bigint,
2283
2279
  nullifier: nullifier_bigint,
@@ -2296,7 +2292,9 @@ var CloakSDK = class {
2296
2292
  var_fee: varFee,
2297
2293
  rem
2298
2294
  };
2295
+ options?.onProgress?.("proof_generating");
2299
2296
  const proofResult = await generateWithdrawRegularProof(proofInputs, circuitsPath);
2297
+ options?.onProgress?.("proof_complete");
2300
2298
  proofHex = Buffer.from(proofResult.proofBytes).toString("hex");
2301
2299
  finalPublicInputs = {
2302
2300
  root: merkleRoot,
@@ -2462,30 +2460,27 @@ var CloakSDK = class {
2462
2460
  );
2463
2461
  }
2464
2462
  let recipientAta;
2465
- try {
2466
- const splTokenModule = await import("@solana/spl-token");
2467
- const getAssociatedTokenAddress = splTokenModule.getAssociatedTokenAddress;
2468
- if (!getAssociatedTokenAddress) {
2469
- throw new Error("getAssociatedTokenAddress not found");
2463
+ if (options.recipientAta) {
2464
+ recipientAta = new PublicKey4(options.recipientAta);
2465
+ } else {
2466
+ try {
2467
+ const splTokenModule = await import("@solana/spl-token");
2468
+ const getAssociatedTokenAddress = splTokenModule.getAssociatedTokenAddress;
2469
+ if (!getAssociatedTokenAddress) {
2470
+ throw new Error("getAssociatedTokenAddress not found");
2471
+ }
2472
+ const outputMint2 = new PublicKey4(options.outputMint);
2473
+ recipientAta = await getAssociatedTokenAddress(outputMint2, recipient);
2474
+ } catch (error) {
2475
+ throw new Error(
2476
+ `Failed to get associated token account: ${error instanceof Error ? error.message : String(error)}. Please install @solana/spl-token or provide recipientAta in options.`
2477
+ );
2470
2478
  }
2471
- const outputMint2 = new PublicKey4(options.outputMint);
2472
- recipientAta = await getAssociatedTokenAddress(outputMint2, recipient);
2473
- } catch (error) {
2474
- throw new Error(
2475
- `Failed to get associated token account: ${error instanceof Error ? error.message : String(error)}. Please install @solana/spl-token or provide recipientAta in options.`
2476
- );
2477
2479
  }
2478
- let merkleProof;
2479
- let merkleRoot;
2480
- if (note.merkleProof && note.root) {
2481
- merkleProof = {
2482
- pathElements: note.merkleProof.pathElements,
2483
- pathIndices: note.merkleProof.pathIndices
2484
- };
2485
- merkleRoot = note.root;
2486
- } else {
2487
- merkleProof = await this.indexer.getMerkleProof(note.leafIndex);
2488
- merkleRoot = merkleProof.root || (await this.indexer.getMerkleRoot()).root;
2480
+ const merkleProof = await this.indexer.getMerkleProof(note.leafIndex);
2481
+ const merkleRoot = merkleProof.root || (await this.indexer.getMerkleRoot()).root;
2482
+ if (!merkleRoot) {
2483
+ throw new Error("Failed to get Merkle root from indexer");
2489
2484
  }
2490
2485
  const nullifier = await computeNullifierAsync(note.sk_spend, note.leafIndex);
2491
2486
  const nullifierHex = nullifier.toString(16).padStart(64, "0");
@@ -2521,6 +2516,13 @@ var CloakSDK = class {
2521
2516
  const inputMintLimbs = pubkeyToLimbs(inputMint.toBytes());
2522
2517
  const outputMintLimbs = pubkeyToLimbs(outputMint.toBytes());
2523
2518
  const recipientAtaLimbs = pubkeyToLimbs(recipientAta.toBytes());
2519
+ const computedCommitment = await computeCommitment(amount_bigint, r_bigint, sk_spend_bigint);
2520
+ const noteCommitment = BigInt("0x" + note.commitment);
2521
+ if (computedCommitment !== noteCommitment) {
2522
+ throw new Error(
2523
+ `Commitment mismatch! Computed: ${computedCommitment.toString(16)}, Note: ${note.commitment}. This means the note's sk_spend, r, or amount doesn't match what was deposited.`
2524
+ );
2525
+ }
2524
2526
  const t = amount_bigint * 5n;
2525
2527
  const varFee = t / 1000n;
2526
2528
  const rem = t % 1000n;
@@ -2542,7 +2544,9 @@ var CloakSDK = class {
2542
2544
  var_fee: varFee,
2543
2545
  rem
2544
2546
  };
2547
+ options?.onProgress?.("proof_generating");
2545
2548
  const proofResult = await generateWithdrawSwapProof(proofInputs, circuitsPath);
2549
+ options?.onProgress?.("proof_complete");
2546
2550
  proofHex = Buffer.from(proofResult.proofBytes).toString("hex");
2547
2551
  finalPublicInputs = {
2548
2552
  root: merkleRoot,
@@ -3062,188 +3066,6 @@ function formatErrorForLogging(error) {
3062
3066
  return String(error);
3063
3067
  }
3064
3068
 
3065
- // src/services/ProverService.ts
3066
- var ProverService = class {
3067
- /**
3068
- * Create a new Prover Service client
3069
- *
3070
- * @param indexerUrl - Indexer/Prover service base URL
3071
- * @param timeout - Proof generation timeout in ms (default: 5 minutes)
3072
- */
3073
- constructor(indexerUrl, timeout = 5 * 60 * 1e3) {
3074
- this.indexerUrl = indexerUrl.replace(/\/$/, "");
3075
- this.timeout = timeout;
3076
- }
3077
- /**
3078
- * Generate a zero-knowledge proof for withdrawal
3079
- *
3080
- * This process typically takes 30-180 seconds depending on the backend.
3081
- *
3082
- * @param inputs - Circuit inputs (private + public + outputs)
3083
- * @param options - Optional progress tracking and callbacks
3084
- * @returns Proof result with hex-encoded proof and public inputs
3085
- *
3086
- * @example
3087
- * ```typescript
3088
- * const result = await prover.generateProof(inputs);
3089
- * if (result.success) {
3090
- * console.log(`Proof: ${result.proof}`);
3091
- * }
3092
- * ```
3093
- *
3094
- * @example
3095
- * ```typescript
3096
- * // With progress tracking
3097
- * const result = await prover.generateProof(inputs, {
3098
- * onProgress: (progress) => console.log(`Progress: ${progress}%`),
3099
- * onStart: () => console.log("Starting proof generation..."),
3100
- * onSuccess: (result) => console.log("Proof generated!"),
3101
- * onError: (error) => console.error("Failed:", error)
3102
- * });
3103
- * ```
3104
- */
3105
- async generateProof(inputs, options) {
3106
- const startTime = Date.now();
3107
- const actualTimeout = options?.timeout || this.timeout;
3108
- options?.onStart?.();
3109
- let progressInterval;
3110
- try {
3111
- const requestBody = {
3112
- private_inputs: JSON.stringify(inputs.privateInputs),
3113
- public_inputs: JSON.stringify(inputs.publicInputs),
3114
- outputs: JSON.stringify(inputs.outputs)
3115
- };
3116
- if (inputs.swapParams) {
3117
- requestBody.swap_params = inputs.swapParams;
3118
- }
3119
- const controller = new AbortController();
3120
- const timeoutId = setTimeout(() => controller.abort(), actualTimeout);
3121
- if (options?.onProgress) {
3122
- let progress = 0;
3123
- progressInterval = setInterval(() => {
3124
- progress = Math.min(90, progress + Math.random() * 10);
3125
- options.onProgress(Math.floor(progress));
3126
- }, 2e3);
3127
- }
3128
- const response = await fetch(`${this.indexerUrl}/api/v1/prove`, {
3129
- method: "POST",
3130
- headers: {
3131
- "Content-Type": "application/json"
3132
- },
3133
- body: JSON.stringify(requestBody),
3134
- signal: controller.signal
3135
- });
3136
- clearTimeout(timeoutId);
3137
- if (progressInterval) clearInterval(progressInterval);
3138
- if (!response.ok) {
3139
- let errorMessage = `${response.status} ${response.statusText}`;
3140
- try {
3141
- const errorText = await response.text();
3142
- try {
3143
- const errorJson = JSON.parse(errorText);
3144
- errorMessage = errorJson.error || errorJson.message || errorText;
3145
- } catch {
3146
- errorMessage = errorText || errorMessage;
3147
- }
3148
- } catch {
3149
- }
3150
- options?.onError?.(errorMessage);
3151
- return {
3152
- success: false,
3153
- generationTimeMs: Date.now() - startTime,
3154
- error: errorMessage
3155
- };
3156
- }
3157
- options?.onProgress?.(100);
3158
- const rawData = await response.json();
3159
- const result = {
3160
- success: rawData.success,
3161
- proof: rawData.proof,
3162
- publicInputs: rawData.public_inputs,
3163
- // Map snake_case
3164
- generationTimeMs: rawData.generation_time_ms || Date.now() - startTime,
3165
- error: rawData.error
3166
- };
3167
- if (!result.success && rawData.execution_report) {
3168
- }
3169
- if (!result.success && result.error) {
3170
- try {
3171
- const errorObj = typeof result.error === "string" ? JSON.parse(result.error) : result.error;
3172
- if (errorObj?.error && typeof errorObj.error === "string") {
3173
- result.error = errorObj.error;
3174
- } else if (typeof errorObj === "string") {
3175
- result.error = errorObj;
3176
- }
3177
- if (errorObj?.execution_report && typeof errorObj.execution_report === "string") {
3178
- result.error += `
3179
- Execution report: ${errorObj.execution_report}`;
3180
- }
3181
- if (errorObj?.total_cycles !== void 0) {
3182
- result.error += `
3183
- Total cycles: ${errorObj.total_cycles}`;
3184
- }
3185
- if (errorObj?.total_syscalls !== void 0) {
3186
- result.error += `
3187
- Total syscalls: ${errorObj.total_syscalls}`;
3188
- }
3189
- } catch {
3190
- }
3191
- }
3192
- if (result.success) {
3193
- options?.onSuccess?.(result);
3194
- } else if (result.error) {
3195
- options?.onError?.(result.error);
3196
- }
3197
- return result;
3198
- } catch (error) {
3199
- const totalTime = Date.now() - startTime;
3200
- if (progressInterval) clearInterval(progressInterval);
3201
- let errorMessage;
3202
- if (error instanceof Error && error.name === "AbortError") {
3203
- errorMessage = `Proof generation timed out after ${actualTimeout}ms`;
3204
- } else {
3205
- errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
3206
- }
3207
- options?.onError?.(errorMessage);
3208
- return {
3209
- success: false,
3210
- generationTimeMs: totalTime,
3211
- error: errorMessage
3212
- };
3213
- }
3214
- }
3215
- /**
3216
- * Check if the prover service is available
3217
- *
3218
- * @returns True if service is healthy
3219
- */
3220
- async healthCheck() {
3221
- try {
3222
- const response = await fetch(`${this.indexerUrl}/health`, {
3223
- method: "GET"
3224
- });
3225
- return response.ok;
3226
- } catch {
3227
- return false;
3228
- }
3229
- }
3230
- /**
3231
- * Get the configured timeout
3232
- */
3233
- getTimeout() {
3234
- return this.timeout;
3235
- }
3236
- /**
3237
- * Set a new timeout
3238
- */
3239
- setTimeout(timeout) {
3240
- if (timeout <= 0) {
3241
- throw new Error("Timeout must be positive");
3242
- }
3243
- this.timeout = timeout;
3244
- }
3245
- };
3246
-
3247
3069
  // src/helpers/wallet-integration.ts
3248
3070
  import {
3249
3071
  Keypair as Keypair2
@@ -3330,7 +3152,6 @@ export {
3330
3152
  LAMPORTS_PER_SOL,
3331
3153
  LocalStorageAdapter,
3332
3154
  MemoryStorageAdapter,
3333
- ProverService,
3334
3155
  RelayService,
3335
3156
  VARIABLE_FEE_RATE,
3336
3157
  VERSION,