@cloak.ag/sdk 1.0.4 → 1.0.5

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.ts CHANGED
@@ -156,7 +156,7 @@ interface CloakConfig {
156
156
  /**
157
157
  * Deposit progress status
158
158
  */
159
- type DepositStatus = "generating_note" | "creating_transaction" | "simulating" | "sending" | "confirming" | "submitting_to_indexer" | "fetching_proof" | "complete";
159
+ type DepositStatus = "generating_note" | "awaiting_note_acknowledgment" | "note_saved" | "creating_transaction" | "simulating" | "sending" | "confirming" | "submitting_to_indexer" | "fetching_proof" | "complete";
160
160
  /**
161
161
  * Options for deposit operation
162
162
  */
@@ -172,6 +172,31 @@ interface DepositOptions {
172
172
  onTransactionSent?: (signature: string) => void;
173
173
  /** Callback when transaction is confirmed */
174
174
  onConfirmed?: (signature: string, slot: number) => void;
175
+ /**
176
+ * CRITICAL: Callback when note is generated, BEFORE any on-chain transaction.
177
+ *
178
+ * This is your chance to safely persist the note. If you don't save the note
179
+ * and the deposit succeeds but the browser crashes, your funds could be lost!
180
+ *
181
+ * The callback receives the note with all secrets needed for withdrawal.
182
+ * The deposit will NOT proceed until this callback completes.
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * onNoteGenerated: async (note) => {
187
+ * // Save to secure storage BEFORE deposit proceeds
188
+ * await localStorage.setItem(`pending_note_${note.commitment}`, JSON.stringify(note));
189
+ * // Or show user a modal to copy/download the note
190
+ * }
191
+ * ```
192
+ */
193
+ onNoteGenerated?: (note: CloakNote) => Promise<void> | void;
194
+ /**
195
+ * If true, require user to acknowledge the note before proceeding with deposit.
196
+ * When enabled with onNoteGenerated, the deposit will wait for the callback to complete.
197
+ * Default: true when onNoteGenerated is provided
198
+ */
199
+ requireNoteAcknowledgment?: boolean;
175
200
  /** Skip simulation (default: false) */
176
201
  skipPreflight?: boolean;
177
202
  /** Compute units to request (default: auto) */
@@ -1339,9 +1364,42 @@ declare function getAddressExplorerUrl(address: string, network?: Network): stri
1339
1364
  /**
1340
1365
  * Error Utilities
1341
1366
  *
1342
- * Helper functions for parsing and presenting user-friendly error messages
1367
+ * Helper functions for parsing and presenting user-friendly error messages.
1368
+ * This is the single source of truth for error codes and messages.
1343
1369
  */
1344
1370
 
1371
+ /**
1372
+ * Shield Pool Program Error Codes
1373
+ *
1374
+ * Maps on-chain program error codes to user-friendly error messages.
1375
+ * These codes match the program's error enum.
1376
+ */
1377
+ declare const ShieldPoolErrors: Record<number, string>;
1378
+ /**
1379
+ * Error categories for UI display
1380
+ */
1381
+ type ErrorCategory = "wallet" | "network" | "validation" | "service" | "transaction" | "unknown";
1382
+ /**
1383
+ * Structured error result for UI
1384
+ */
1385
+ interface UserFriendlyError {
1386
+ /** User-facing title */
1387
+ title: string;
1388
+ /** User-facing description */
1389
+ message: string;
1390
+ /** Error category for styling */
1391
+ category: ErrorCategory;
1392
+ /** Optional suggestion for the user */
1393
+ suggestion?: string;
1394
+ /** Whether the error is recoverable (user can retry) */
1395
+ recoverable: boolean;
1396
+ /** Original error for debugging (not shown to user) */
1397
+ originalError?: string;
1398
+ }
1399
+ /**
1400
+ * Parse any error and return a user-friendly error object
1401
+ */
1402
+ declare function parseError(error: unknown): UserFriendlyError;
1345
1403
  /**
1346
1404
  * Parse transaction error and return user-friendly message
1347
1405
  *
@@ -1479,6 +1537,16 @@ declare class IndexerService {
1479
1537
  }>;
1480
1538
  }
1481
1539
 
1540
+ /**
1541
+ * Result from submitting a withdrawal that includes the request ID
1542
+ * for potential recovery/resume scenarios
1543
+ */
1544
+ interface WithdrawSubmissionResult {
1545
+ /** The relay request ID - persist this for recovery */
1546
+ requestId: string;
1547
+ /** The final transaction signature */
1548
+ signature: string;
1549
+ }
1482
1550
  /**
1483
1551
  * Relay Service Client
1484
1552
  *
@@ -1501,6 +1569,8 @@ declare class RelayService {
1501
1569
  *
1502
1570
  * @param params - Withdrawal parameters
1503
1571
  * @param onStatusUpdate - Optional callback for status updates
1572
+ * @param onRequestId - CRITICAL: Callback when request_id is received.
1573
+ * Persist this ID to recover if browser crashes during polling.
1504
1574
  * @returns Transaction signature when completed
1505
1575
  *
1506
1576
  * @example
@@ -1510,7 +1580,8 @@ declare class RelayService {
1510
1580
  * publicInputs: { root, nf, outputs_hash, amount },
1511
1581
  * outputs: [{ recipient: addr, amount: lamports }],
1512
1582
  * feeBps: 50
1513
- * }, (status) => console.log(`Status: ${status}`));
1583
+ * }, (status) => console.log(`Status: ${status}`),
1584
+ * (requestId) => localStorage.setItem('pending_withdraw', requestId));
1514
1585
  * console.log(`Transaction: ${signature}`);
1515
1586
  * ```
1516
1587
  */
@@ -1527,7 +1598,35 @@ declare class RelayService {
1527
1598
  amount: number;
1528
1599
  }>;
1529
1600
  feeBps: number;
1530
- }, onStatusUpdate?: (status: string) => void): Promise<string>;
1601
+ }, onStatusUpdate?: (status: string) => void, onRequestId?: (requestId: string) => void): Promise<string>;
1602
+ /**
1603
+ * Resume polling for a withdrawal that was previously started
1604
+ *
1605
+ * Use this after page reload to check status of a pending withdrawal.
1606
+ * The requestId should have been persisted via the onRequestId callback.
1607
+ *
1608
+ * @param requestId - Request ID from a previous submitWithdraw call
1609
+ * @param onStatusUpdate - Optional callback for status updates
1610
+ * @returns Transaction signature if completed, null if still pending/failed
1611
+ *
1612
+ * @example
1613
+ * ```typescript
1614
+ * // On page load, check for pending withdrawal
1615
+ * const pendingId = localStorage.getItem('pending_withdraw');
1616
+ * if (pendingId) {
1617
+ * const result = await relay.resumeWithdraw(pendingId);
1618
+ * if (result.status === 'completed') {
1619
+ * console.log('Withdrawal completed:', result.signature);
1620
+ * localStorage.removeItem('pending_withdraw');
1621
+ * }
1622
+ * }
1623
+ * ```
1624
+ */
1625
+ resumeWithdraw(requestId: string, onStatusUpdate?: (status: string) => void): Promise<{
1626
+ status: 'completed' | 'failed' | 'pending';
1627
+ signature?: string;
1628
+ error?: string;
1629
+ }>;
1531
1630
  /**
1532
1631
  * Poll for withdrawal completion
1533
1632
  *
@@ -1581,7 +1680,7 @@ declare class RelayService {
1581
1680
  slippage_bps: number;
1582
1681
  min_output_amount: number;
1583
1682
  };
1584
- }, onStatusUpdate?: (status: string) => void): Promise<string>;
1683
+ }, onStatusUpdate?: (status: string) => void, onRequestId?: (requestId: string) => void): Promise<string>;
1585
1684
  /**
1586
1685
  * Get transaction status
1587
1686
  *
@@ -1653,10 +1752,16 @@ declare class DepositRecoveryService {
1653
1752
  recoverDeposit(options: RecoveryOptions): Promise<RecoveryResult>;
1654
1753
  /**
1655
1754
  * Check if a deposit already exists in the indexer
1755
+ * Uses the enhanced deposit lookup endpoint with include_proof=true
1656
1756
  *
1657
1757
  * @private
1658
1758
  */
1659
1759
  private checkExistingDeposit;
1760
+ /**
1761
+ * Recover deposit by transaction signature
1762
+ * Uses the indexer's signature lookup endpoint
1763
+ */
1764
+ recoverBySignature(signature: string): Promise<RecoveryResult>;
1660
1765
  /**
1661
1766
  * Finalize a deposit via server API (alternative recovery method)
1662
1767
  *
@@ -1879,6 +1984,175 @@ declare function generateWithdrawRegularProof(inputs: WithdrawRegularInputs, cir
1879
1984
  * @param circuitsPath - Path or URL to circuits directory. In browser, use URL like '/circuits' or full URL.
1880
1985
  */
1881
1986
  declare function generateWithdrawSwapProof(inputs: WithdrawSwapInputs, circuitsPath: string): Promise<ProofResult>;
1987
+ /**
1988
+ * Expected circuit hashes for verification
1989
+ * These are computed from the verification key files to ensure circuits match on-chain vkeys
1990
+ *
1991
+ * To regenerate these hashes, run:
1992
+ * node -e "const fs=require('fs'); const data=fs.readFileSync('path/to/vkey.json'); console.log(require('crypto').createHash('sha256').update(data).digest('hex'));"
1993
+ */
1994
+ declare const EXPECTED_CIRCUIT_HASHES: {
1995
+ withdraw_regular_vkey: string | null;
1996
+ withdraw_swap_vkey: string | null;
1997
+ };
1998
+ /**
1999
+ * Circuit verification result
2000
+ */
2001
+ interface CircuitVerificationResult {
2002
+ /** Whether verification passed */
2003
+ valid: boolean;
2004
+ /** Which circuit was checked */
2005
+ circuit: 'withdraw_regular' | 'withdraw_swap';
2006
+ /** Error message if verification failed */
2007
+ error?: string;
2008
+ /** Computed hash (for debugging) */
2009
+ computedHash?: string;
2010
+ /** Expected hash (for debugging) */
2011
+ expectedHash?: string;
2012
+ }
2013
+ /**
2014
+ * Verify circuit integrity by checking verification key hashes
2015
+ *
2016
+ * This function fetches the verification key and computes its hash,
2017
+ * then compares against the expected hash embedded in the SDK.
2018
+ *
2019
+ * IMPORTANT: If the hashes don't match, the circuit may produce proofs
2020
+ * that will be rejected by the on-chain verifier!
2021
+ *
2022
+ * @param circuitsPath - Path to circuits directory
2023
+ * @param circuit - Which circuit to verify ('withdraw_regular' or 'withdraw_swap')
2024
+ * @returns Verification result
2025
+ *
2026
+ * @example
2027
+ * ```typescript
2028
+ * const result = await verifyCircuitIntegrity('/circuits', 'withdraw_regular');
2029
+ * if (!result.valid) {
2030
+ * console.error('Circuit verification failed:', result.error);
2031
+ * // Don't proceed with proof generation!
2032
+ * }
2033
+ * ```
2034
+ */
2035
+ declare function verifyCircuitIntegrity(circuitsPath: string, circuit: 'withdraw_regular' | 'withdraw_swap'): Promise<CircuitVerificationResult>;
2036
+ /**
2037
+ * Verify all circuits before use
2038
+ *
2039
+ * Call this at SDK initialization to ensure circuits are valid.
2040
+ *
2041
+ * @param circuitsPath - Path to circuits directory
2042
+ * @returns Array of verification results (one per circuit)
2043
+ */
2044
+ declare function verifyAllCircuits(circuitsPath: string): Promise<CircuitVerificationResult[]>;
2045
+
2046
+ /**
2047
+ * Pending Operations Manager
2048
+ *
2049
+ * Utility for persisting pending deposit/withdrawal operations in browser storage.
2050
+ * This enables recovery if the browser crashes or user navigates away mid-operation.
2051
+ *
2052
+ * IMPORTANT: This uses localStorage by default which has security implications.
2053
+ * Notes contain sensitive spending keys - consider using more secure storage
2054
+ * in production (e.g., encrypted IndexedDB, secure enclave).
2055
+ */
2056
+
2057
+ /**
2058
+ * Pending deposit record
2059
+ */
2060
+ interface PendingDeposit {
2061
+ /** The note (contains spending secrets!) */
2062
+ note: CloakNote;
2063
+ /** When the deposit was initiated */
2064
+ startedAt: number;
2065
+ /** Transaction signature if available */
2066
+ txSignature?: string;
2067
+ /** Status of the deposit */
2068
+ status: "pending" | "tx_sent" | "confirmed" | "failed";
2069
+ /** Error message if failed */
2070
+ error?: string;
2071
+ }
2072
+ /**
2073
+ * Pending withdrawal record
2074
+ */
2075
+ interface PendingWithdrawal {
2076
+ /** The relay request ID (for resumption) */
2077
+ requestId: string;
2078
+ /** The note commitment being withdrawn */
2079
+ commitment: string;
2080
+ /** The nullifier being used */
2081
+ nullifier: string;
2082
+ /** When the withdrawal was initiated */
2083
+ startedAt: number;
2084
+ /** Status of the withdrawal */
2085
+ status: "pending" | "processing" | "completed" | "failed";
2086
+ /** Transaction signature if completed */
2087
+ txSignature?: string;
2088
+ /** Error message if failed */
2089
+ error?: string;
2090
+ }
2091
+ /**
2092
+ * Save a pending deposit
2093
+ * Call this BEFORE sending the on-chain transaction to ensure note is persisted
2094
+ */
2095
+ declare function savePendingDeposit(deposit: PendingDeposit): void;
2096
+ /**
2097
+ * Load all pending deposits
2098
+ */
2099
+ declare function loadPendingDeposits(): PendingDeposit[];
2100
+ /**
2101
+ * Update a pending deposit status
2102
+ */
2103
+ declare function updatePendingDeposit(commitment: string, updates: Partial<PendingDeposit>): void;
2104
+ /**
2105
+ * Remove a pending deposit (e.g., after successful confirmation)
2106
+ */
2107
+ declare function removePendingDeposit(commitment: string): void;
2108
+ /**
2109
+ * Clear all pending deposits
2110
+ */
2111
+ declare function clearPendingDeposits(): void;
2112
+ /**
2113
+ * Save a pending withdrawal
2114
+ * Call this when you receive the request_id from the relay
2115
+ */
2116
+ declare function savePendingWithdrawal(withdrawal: PendingWithdrawal): void;
2117
+ /**
2118
+ * Load all pending withdrawals
2119
+ */
2120
+ declare function loadPendingWithdrawals(): PendingWithdrawal[];
2121
+ /**
2122
+ * Update a pending withdrawal status
2123
+ */
2124
+ declare function updatePendingWithdrawal(requestId: string, updates: Partial<PendingWithdrawal>): void;
2125
+ /**
2126
+ * Remove a pending withdrawal (e.g., after successful completion)
2127
+ */
2128
+ declare function removePendingWithdrawal(requestId: string): void;
2129
+ /**
2130
+ * Clear all pending withdrawals
2131
+ */
2132
+ declare function clearPendingWithdrawals(): void;
2133
+ /**
2134
+ * Check if there are any pending operations that need recovery
2135
+ * Call this on page load to determine if recovery UI should be shown
2136
+ */
2137
+ declare function hasPendingOperations(): boolean;
2138
+ /**
2139
+ * Get summary of pending operations for recovery UI
2140
+ */
2141
+ declare function getPendingOperationsSummary(): {
2142
+ deposits: PendingDeposit[];
2143
+ withdrawals: PendingWithdrawal[];
2144
+ totalPending: number;
2145
+ };
2146
+ /**
2147
+ * Clean up stale pending operations
2148
+ * Call this periodically to remove old failed/completed operations
2149
+ *
2150
+ * @param maxAgeMs Maximum age in milliseconds before an operation is removed (default: 24 hours)
2151
+ */
2152
+ declare function cleanupStalePendingOperations(maxAgeMs?: number): {
2153
+ removedDeposits: number;
2154
+ removedWithdrawals: number;
2155
+ };
1882
2156
 
1883
2157
  /**
1884
2158
  * Cloak SDK - TypeScript SDK for Private Transactions on Solana
@@ -1888,4 +2162,4 @@ declare function generateWithdrawSwapProof(inputs: WithdrawSwapInputs, circuitsP
1888
2162
 
1889
2163
  declare const VERSION = "1.0.0";
1890
2164
 
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 };
2165
+ export { CLOAK_PROGRAM_ID, type CircuitVerificationResult, type CloakConfig, CloakError, type CloakKeyPair, type CloakNote, CloakSDK, type DepositInstructionParams, type DepositOptions, DepositRecoveryService, type DepositResult, type DepositStatus, EXPECTED_CIRCUIT_HASHES, type EncryptedNote, type ErrorCategory, 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 PendingDeposit, type PendingWithdrawal, type ProofResult, type RecoveryOptions, type RecoveryResult, RelayService, type ScanNotesOptions, type ScannedNote, ShieldPoolErrors, type ShieldPoolPDAs, type SpendKey, type StorageAdapter, type SwapOptions, type SwapParams, type SwapResult, type Transfer, type TransferOptions, type TransferResult, type TxStatus, type UserFriendlyError, VARIABLE_FEE_RATE, VERSION, type ViewKey, type WalletAdapter, type WithdrawOptions, type WithdrawRegularInputs, type WithdrawSubmissionResult, type WithdrawSwapInputs, bigintToBytes32, buildPublicInputsBytes, bytesToHex, calculateFee, calculateRelayFee, cleanupStalePendingOperations, clearPendingDeposits, clearPendingWithdrawals, 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, getPendingOperationsSummary, getPublicKey, getPublicViewKey, getRecipientAmount, getRpcUrlForNetwork, getShieldPoolPDAs, getViewKey, hasPendingOperations, hexToBigint, hexToBytes, importKeys, importWalletKeys, isValidHex, isValidRpcUrl, isValidSolanaAddress, isWithdrawable, keypairToAdapter, loadPendingDeposits, loadPendingWithdrawals, parseAmount, parseError, parseNote, parseTransactionError, poseidonHash, prepareEncryptedOutput, prepareEncryptedOutputForRecipient, proofToBytes, pubkeyToLimbs, randomBytes, removePendingDeposit, removePendingWithdrawal, savePendingDeposit, savePendingWithdrawal, scanNotesForWallet, sendTransaction, serializeNote, signTransaction, splitTo2Limbs, tryDecryptNote, updateNoteWithDeposit, updatePendingDeposit, updatePendingWithdrawal, validateDepositParams, validateNote, validateOutputsSum, validateTransfers, validateWalletConnected, validateWithdrawableNote, verifyAllCircuits, verifyCircuitIntegrity };