@cloak.ag/sdk 1.0.1 → 1.0.3

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.js CHANGED
@@ -8,7 +8,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
  // src/core/CloakSDK.ts
9
9
  import {
10
10
  Keypair,
11
- PublicKey as PublicKey5,
11
+ PublicKey as PublicKey4,
12
12
  Transaction
13
13
  } from "@solana/web3.js";
14
14
 
@@ -28,7 +28,6 @@ import { blake3 } from "@noble/hashes/blake3.js";
28
28
  import nacl from "tweetnacl";
29
29
 
30
30
  // src/utils/crypto.ts
31
- import { PublicKey } from "@solana/web3.js";
32
31
  import { buildPoseidon } from "circomlibjs";
33
32
  var poseidon = null;
34
33
  async function getPoseidon() {
@@ -49,7 +48,7 @@ function splitTo2Limbs(value) {
49
48
  return [lo, hi];
50
49
  }
51
50
  function pubkeyToLimbs(pubkey) {
52
- const bytes = pubkey instanceof PublicKey ? pubkey.toBytes() : pubkey;
51
+ const bytes = typeof pubkey.toBytes === "function" ? pubkey.toBytes() : pubkey;
53
52
  const value = BigInt("0x" + Buffer.from(bytes).toString("hex"));
54
53
  return splitTo2Limbs(value);
55
54
  }
@@ -677,10 +676,10 @@ var LocalStorageAdapter = class {
677
676
  };
678
677
 
679
678
  // src/utils/validation.ts
680
- import { PublicKey as PublicKey2 } from "@solana/web3.js";
679
+ import { PublicKey } from "@solana/web3.js";
681
680
  function isValidSolanaAddress(address) {
682
681
  try {
683
- new PublicKey2(address);
682
+ new PublicKey(address);
684
683
  return true;
685
684
  } catch {
686
685
  return false;
@@ -779,8 +778,9 @@ function validateTransfers(recipients, totalAmount) {
779
778
  }
780
779
  for (let i = 0; i < recipients.length; i++) {
781
780
  const transfer = recipients[i];
782
- if (!transfer.recipient || !(transfer.recipient instanceof PublicKey2)) {
783
- throw new Error(`Recipient ${i} must be a PublicKey`);
781
+ const isPublicKeyLike = transfer.recipient && typeof transfer.recipient.toBase58 === "function" && typeof transfer.recipient.toBuffer === "function";
782
+ if (!isPublicKeyLike) {
783
+ throw new Error(`Recipient ${i} must be a PublicKey (got ${typeof transfer.recipient})`);
784
784
  }
785
785
  if (typeof transfer.amount !== "number" || transfer.amount <= 0) {
786
786
  throw new Error(`Recipient ${i} amount must be a positive number`);
@@ -1025,254 +1025,6 @@ var IndexerService = class {
1025
1025
  }
1026
1026
  };
1027
1027
 
1028
- // src/services/ArtifactProverService.ts
1029
- var ArtifactProverService = class {
1030
- /**
1031
- * Create a new Artifact Prover Service client
1032
- *
1033
- * @param indexerUrl - Indexer service base URL
1034
- * @param timeout - Proof generation timeout in ms (default: 5 minutes)
1035
- * @param pollInterval - Polling interval for status checks (default: 2 seconds)
1036
- */
1037
- constructor(indexerUrl, timeout = 5 * 60 * 1e3, pollInterval = 2e3) {
1038
- this.indexerUrl = indexerUrl.replace(/\/$/, "");
1039
- this.timeout = timeout;
1040
- this.pollInterval = pollInterval;
1041
- }
1042
- /**
1043
- * Generate a zero-knowledge proof using artifact-based flow
1044
- *
1045
- * This process typically takes 30-180 seconds depending on the TEE.
1046
- * Private inputs are uploaded directly to TEE, never passing through backend.
1047
- *
1048
- * @param inputs - Circuit inputs (private + public + outputs)
1049
- * @param options - Optional progress tracking and callbacks
1050
- * @returns Proof result with hex-encoded proof and public inputs
1051
- *
1052
- * @example
1053
- * ```typescript
1054
- * const result = await prover.generateProof(inputs);
1055
- * if (result.success) {
1056
- * console.log(`Proof: ${result.proof}`);
1057
- * }
1058
- * ```
1059
- */
1060
- async generateProof(inputs, options) {
1061
- const startTime = Date.now();
1062
- const actualTimeout = options?.timeout || this.timeout;
1063
- const pollInterval = options?.pollInterval || this.pollInterval;
1064
- options?.onStart?.();
1065
- options?.onProgress?.(5);
1066
- try {
1067
- options?.onProgress?.(10);
1068
- const artifactResponse = await fetch(`${this.indexerUrl}/api/v1/tee/artifact`, {
1069
- method: "POST",
1070
- headers: {
1071
- "Content-Type": "application/json"
1072
- },
1073
- body: JSON.stringify({
1074
- program_id: null
1075
- // Optional, can be null
1076
- })
1077
- });
1078
- if (!artifactResponse.ok) {
1079
- const errorText = await artifactResponse.text();
1080
- const errorMessage2 = `Failed to create artifact: ${errorText}`;
1081
- options?.onError?.(errorMessage2);
1082
- return {
1083
- success: false,
1084
- generationTimeMs: Date.now() - startTime,
1085
- error: errorMessage2
1086
- };
1087
- }
1088
- const artifactData = await artifactResponse.json();
1089
- const { artifact_id, upload_url } = artifactData;
1090
- if (!artifact_id || !upload_url) {
1091
- const errorMessage2 = "Invalid artifact response: missing artifact_id or upload_url";
1092
- options?.onError?.(errorMessage2);
1093
- return {
1094
- success: false,
1095
- generationTimeMs: Date.now() - startTime,
1096
- error: errorMessage2
1097
- };
1098
- }
1099
- const fullUploadUrl = upload_url.startsWith("http") ? upload_url : `${this.indexerUrl}${upload_url}`;
1100
- options?.onProgress?.(20);
1101
- const stdinPayload = JSON.stringify({
1102
- private: inputs.privateInputs,
1103
- public: inputs.publicInputs,
1104
- outputs: inputs.outputs,
1105
- // Include swap_params if present (for swap transactions)
1106
- ...inputs.swapParams && { swap_params: inputs.swapParams }
1107
- });
1108
- const uploadResponse = await fetch(fullUploadUrl, {
1109
- method: "POST",
1110
- headers: {
1111
- "Content-Type": "application/json"
1112
- },
1113
- body: stdinPayload
1114
- });
1115
- if (!uploadResponse.ok) {
1116
- const errorText = await uploadResponse.text();
1117
- const errorMessage2 = `Failed to upload stdin to TEE: ${errorText}`;
1118
- options?.onError?.(errorMessage2);
1119
- return {
1120
- success: false,
1121
- generationTimeMs: Date.now() - startTime,
1122
- error: errorMessage2
1123
- };
1124
- }
1125
- options?.onProgress?.(30);
1126
- const requestProofBody = {
1127
- artifact_id,
1128
- program_id: null,
1129
- public_inputs: JSON.stringify(inputs.publicInputs)
1130
- };
1131
- const requestProofResponse = await fetch(
1132
- `${this.indexerUrl}/api/v1/tee/request-proof`,
1133
- {
1134
- method: "POST",
1135
- headers: {
1136
- "Content-Type": "application/json"
1137
- },
1138
- body: JSON.stringify(requestProofBody)
1139
- }
1140
- );
1141
- if (!requestProofResponse.ok) {
1142
- const errorText = await requestProofResponse.text();
1143
- const errorMessage2 = `Failed to request proof: ${errorText}`;
1144
- options?.onError?.(errorMessage2);
1145
- return {
1146
- success: false,
1147
- generationTimeMs: Date.now() - startTime,
1148
- error: errorMessage2
1149
- };
1150
- }
1151
- const requestProofData = await requestProofResponse.json();
1152
- const { request_id } = requestProofData;
1153
- if (!request_id) {
1154
- const errorMessage2 = "Invalid proof request response: missing request_id";
1155
- options?.onError?.(errorMessage2);
1156
- return {
1157
- success: false,
1158
- generationTimeMs: Date.now() - startTime,
1159
- error: errorMessage2
1160
- };
1161
- }
1162
- options?.onProgress?.(40);
1163
- const pollStartTime = Date.now();
1164
- let lastProgress = 40;
1165
- while (Date.now() - pollStartTime < actualTimeout) {
1166
- const statusResponse = await fetch(
1167
- `${this.indexerUrl}/api/v1/tee/proof-status?request_id=${request_id}`,
1168
- {
1169
- method: "GET"
1170
- }
1171
- );
1172
- if (!statusResponse.ok) {
1173
- const errorText = await statusResponse.text();
1174
- const errorMessage2 = `Failed to check proof status: ${errorText}`;
1175
- options?.onError?.(errorMessage2);
1176
- return {
1177
- success: false,
1178
- generationTimeMs: Date.now() - startTime,
1179
- error: errorMessage2
1180
- };
1181
- }
1182
- const statusData = await statusResponse.json();
1183
- const { status, proof, public_inputs, generation_time_ms, error } = statusData;
1184
- if (status === "ready") {
1185
- options?.onProgress?.(100);
1186
- if (!proof || !public_inputs) {
1187
- const errorMessage2 = "Proof status is 'ready' but proof or public_inputs is missing";
1188
- options?.onError?.(errorMessage2);
1189
- return {
1190
- success: false,
1191
- generationTimeMs: Date.now() - startTime,
1192
- error: errorMessage2
1193
- };
1194
- }
1195
- const result = {
1196
- success: true,
1197
- proof,
1198
- publicInputs: public_inputs,
1199
- generationTimeMs: generation_time_ms || Date.now() - startTime
1200
- };
1201
- options?.onSuccess?.(result);
1202
- return result;
1203
- }
1204
- if (status === "failed") {
1205
- const errorMessage2 = error || "Proof generation failed";
1206
- options?.onError?.(errorMessage2);
1207
- return {
1208
- success: false,
1209
- generationTimeMs: Date.now() - startTime,
1210
- error: errorMessage2
1211
- };
1212
- }
1213
- const elapsed = Date.now() - pollStartTime;
1214
- const progress = Math.min(90, 40 + Math.floor(elapsed / actualTimeout * 50));
1215
- if (progress > lastProgress) {
1216
- lastProgress = progress;
1217
- options?.onProgress?.(progress);
1218
- }
1219
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
1220
- }
1221
- const errorMessage = `Proof generation timed out after ${actualTimeout}ms`;
1222
- options?.onError?.(errorMessage);
1223
- return {
1224
- success: false,
1225
- generationTimeMs: Date.now() - startTime,
1226
- error: errorMessage
1227
- };
1228
- } catch (error) {
1229
- const totalTime = Date.now() - startTime;
1230
- let errorMessage;
1231
- if (error instanceof Error && error.name === "AbortError") {
1232
- errorMessage = `Proof generation timed out after ${actualTimeout}ms`;
1233
- } else {
1234
- errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1235
- }
1236
- options?.onError?.(errorMessage);
1237
- return {
1238
- success: false,
1239
- generationTimeMs: totalTime,
1240
- error: errorMessage
1241
- };
1242
- }
1243
- }
1244
- /**
1245
- * Check if the artifact prover service is available
1246
- *
1247
- * @returns True if service is healthy
1248
- */
1249
- async healthCheck() {
1250
- try {
1251
- const response = await fetch(`${this.indexerUrl}/health`, {
1252
- method: "GET"
1253
- });
1254
- return response.ok;
1255
- } catch {
1256
- return false;
1257
- }
1258
- }
1259
- /**
1260
- * Get the configured timeout
1261
- */
1262
- getTimeout() {
1263
- return this.timeout;
1264
- }
1265
- /**
1266
- * Set a new timeout
1267
- */
1268
- setTimeout(timeout) {
1269
- if (timeout <= 0) {
1270
- throw new Error("Timeout must be positive");
1271
- }
1272
- this.timeout = timeout;
1273
- }
1274
- };
1275
-
1276
1028
  // src/services/RelayService.ts
1277
1029
  var RelayService = class {
1278
1030
  /**
@@ -1510,7 +1262,7 @@ var RelayService = class {
1510
1262
  * Sleep utility
1511
1263
  */
1512
1264
  sleep(ms) {
1513
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1265
+ return new Promise((resolve) => setTimeout(resolve, ms));
1514
1266
  }
1515
1267
  };
1516
1268
 
@@ -1769,7 +1521,7 @@ var DepositRecoveryService = class {
1769
1521
 
1770
1522
  // src/solana/instructions.ts
1771
1523
  import {
1772
- PublicKey as PublicKey3,
1524
+ PublicKey as PublicKey2,
1773
1525
  SystemProgram,
1774
1526
  TransactionInstruction
1775
1527
  } from "@solana/web3.js";
@@ -1810,16 +1562,16 @@ function createDepositInstruction(params) {
1810
1562
  });
1811
1563
  }
1812
1564
  function validateDepositParams(params) {
1813
- if (!(params.programId instanceof PublicKey3)) {
1565
+ if (!(params.programId instanceof PublicKey2)) {
1814
1566
  throw new Error("programId must be a PublicKey");
1815
1567
  }
1816
- if (!(params.payer instanceof PublicKey3)) {
1568
+ if (!(params.payer instanceof PublicKey2)) {
1817
1569
  throw new Error("payer must be a PublicKey");
1818
1570
  }
1819
- if (!(params.pool instanceof PublicKey3)) {
1571
+ if (!(params.pool instanceof PublicKey2)) {
1820
1572
  throw new Error("pool must be a PublicKey");
1821
1573
  }
1822
- if (!(params.merkleTree instanceof PublicKey3)) {
1574
+ if (!(params.merkleTree instanceof PublicKey2)) {
1823
1575
  throw new Error("merkleTree must be a PublicKey");
1824
1576
  }
1825
1577
  if (typeof params.amount !== "number" || params.amount <= 0) {
@@ -1836,34 +1588,34 @@ function validateDepositParams(params) {
1836
1588
  }
1837
1589
 
1838
1590
  // src/utils/pda.ts
1839
- import { PublicKey as PublicKey4 } from "@solana/web3.js";
1591
+ import { PublicKey as PublicKey3 } from "@solana/web3.js";
1840
1592
  function getShieldPoolPDAs(programId, mint) {
1841
1593
  const pid = programId || CLOAK_PROGRAM_ID;
1842
- const mintKey = mint ?? new PublicKey4(
1594
+ const mintKey = mint ?? new PublicKey3(
1843
1595
  // 32 zero bytes, matching Rust `Pubkey::default()`
1844
1596
  new Uint8Array(32)
1845
1597
  );
1846
- const [pool] = PublicKey4.findProgramAddressSync(
1598
+ const [pool] = PublicKey3.findProgramAddressSync(
1847
1599
  [Buffer.from("pool"), mintKey.toBytes()],
1848
1600
  pid
1849
1601
  );
1850
- const [merkleTree] = PublicKey4.findProgramAddressSync(
1602
+ const [merkleTree] = PublicKey3.findProgramAddressSync(
1851
1603
  [Buffer.from("merkle_tree"), mintKey.toBytes()],
1852
1604
  pid
1853
1605
  );
1854
- const [commitments] = PublicKey4.findProgramAddressSync(
1606
+ const [commitments] = PublicKey3.findProgramAddressSync(
1855
1607
  [Buffer.from("commitments"), mintKey.toBytes()],
1856
1608
  pid
1857
1609
  );
1858
- const [rootsRing] = PublicKey4.findProgramAddressSync(
1610
+ const [rootsRing] = PublicKey3.findProgramAddressSync(
1859
1611
  [Buffer.from("roots_ring"), mintKey.toBytes()],
1860
1612
  pid
1861
1613
  );
1862
- const [nullifierShard] = PublicKey4.findProgramAddressSync(
1614
+ const [nullifierShard] = PublicKey3.findProgramAddressSync(
1863
1615
  [Buffer.from("nullifier_shard"), mintKey.toBytes()],
1864
1616
  pid
1865
1617
  );
1866
- const [treasury] = PublicKey4.findProgramAddressSync(
1618
+ const [treasury] = PublicKey3.findProgramAddressSync(
1867
1619
  [Buffer.from("treasury"), mintKey.toBytes()],
1868
1620
  pid
1869
1621
  );
@@ -1879,16 +1631,66 @@ function getShieldPoolPDAs(programId, mint) {
1879
1631
 
1880
1632
  // src/utils/proof-generation.ts
1881
1633
  import * as snarkjs from "snarkjs";
1882
- import * as path from "path";
1883
- import * as fs from "fs";
1884
- async function generateWithdrawRegularProof(inputs, circuitsPath) {
1885
- const wasmPath = path.join(circuitsPath, "build", "withdraw_regular_js", "withdraw_regular.wasm");
1886
- const zkeyPath = path.join(circuitsPath, "build", "withdraw_regular_final.zkey");
1887
- if (!fs.existsSync(wasmPath)) {
1888
- throw new Error(`Circuit WASM not found at ${wasmPath}. Run 'just circuits-compile' in packages-new/circuits first.`);
1634
+ var path = null;
1635
+ var fs = null;
1636
+ async function loadNodeModules() {
1637
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1638
+ if (!isBrowser && typeof process !== "undefined" && process.versions?.node) {
1639
+ if (!path) {
1640
+ path = await import("path");
1641
+ }
1642
+ if (!fs) {
1643
+ fs = await import("fs");
1644
+ }
1645
+ return { path, fs };
1646
+ }
1647
+ return { path: null, fs: null };
1648
+ }
1649
+ function joinPath(...parts) {
1650
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1651
+ if (!isBrowser && path) {
1652
+ return path.join(...parts);
1653
+ }
1654
+ return parts.join("/").replace(/\/+/g, "/");
1655
+ }
1656
+ async function fileExists(filePath) {
1657
+ const { fs: fs2 } = await loadNodeModules();
1658
+ if (fs2) {
1659
+ try {
1660
+ return fs2.existsSync(filePath);
1661
+ } catch {
1662
+ return false;
1663
+ }
1664
+ }
1665
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1666
+ if (isBrowser) {
1667
+ try {
1668
+ const response = await fetch(filePath, { method: "HEAD" });
1669
+ return response.ok;
1670
+ } catch {
1671
+ return false;
1672
+ }
1889
1673
  }
1890
- if (!fs.existsSync(zkeyPath)) {
1891
- throw new Error(`Circuit zkey not found at ${zkeyPath}. Run circuit setup first.`);
1674
+ return false;
1675
+ }
1676
+ async function generateWithdrawRegularProof(inputs, circuitsPath) {
1677
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1678
+ let wasmPath;
1679
+ let zkeyPath;
1680
+ if (isBrowser) {
1681
+ wasmPath = `${circuitsPath}/withdraw_regular_js/withdraw_regular.wasm`;
1682
+ zkeyPath = `${circuitsPath}/withdraw_regular_final.zkey`;
1683
+ } else {
1684
+ wasmPath = joinPath(circuitsPath, "build", "withdraw_regular_js", "withdraw_regular.wasm");
1685
+ zkeyPath = joinPath(circuitsPath, "build", "withdraw_regular_final.zkey");
1686
+ const wasmExists = await fileExists(wasmPath);
1687
+ const zkeyExists = await fileExists(zkeyPath);
1688
+ if (!wasmExists) {
1689
+ throw new Error(`Circuit WASM not found at ${wasmPath}. Run 'just circuits-compile' in packages-new/circuits first.`);
1690
+ }
1691
+ if (!zkeyExists) {
1692
+ throw new Error(`Circuit zkey not found at ${zkeyPath}. Run circuit setup first.`);
1693
+ }
1892
1694
  }
1893
1695
  const circuitInputs = {
1894
1696
  // Public signals
@@ -1927,13 +1729,23 @@ async function generateWithdrawRegularProof(inputs, circuitsPath) {
1927
1729
  };
1928
1730
  }
1929
1731
  async function generateWithdrawSwapProof(inputs, circuitsPath) {
1930
- const wasmPath = path.join(circuitsPath, "build", "withdraw_swap_js", "withdraw_swap.wasm");
1931
- const zkeyPath = path.join(circuitsPath, "build", "withdraw_swap_final.zkey");
1932
- if (!fs.existsSync(wasmPath)) {
1933
- throw new Error(`Circuit WASM not found at ${wasmPath}. Run 'just circuits-compile' in packages-new/circuits first.`);
1934
- }
1935
- if (!fs.existsSync(zkeyPath)) {
1936
- throw new Error(`Circuit zkey not found at ${zkeyPath}. Run circuit setup first.`);
1732
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1733
+ let wasmPath;
1734
+ let zkeyPath;
1735
+ if (isBrowser) {
1736
+ wasmPath = `${circuitsPath}/withdraw_swap_js/withdraw_swap.wasm`;
1737
+ zkeyPath = `${circuitsPath}/withdraw_swap_final.zkey`;
1738
+ } else {
1739
+ wasmPath = joinPath(circuitsPath, "build", "withdraw_swap_js", "withdraw_swap.wasm");
1740
+ zkeyPath = joinPath(circuitsPath, "build", "withdraw_swap_final.zkey");
1741
+ const wasmExists = await fileExists(wasmPath);
1742
+ const zkeyExists = await fileExists(zkeyPath);
1743
+ if (!wasmExists) {
1744
+ throw new Error(`Circuit WASM not found at ${wasmPath}. Run 'just circuits-compile' in packages-new/circuits first.`);
1745
+ }
1746
+ if (!zkeyExists) {
1747
+ throw new Error(`Circuit zkey not found at ${zkeyPath}. Run circuit setup first.`);
1748
+ }
1937
1749
  }
1938
1750
  const sk = splitTo2Limbs(inputs.sk_spend);
1939
1751
  const r = splitTo2Limbs(inputs.r);
@@ -1974,21 +1786,35 @@ async function generateWithdrawSwapProof(inputs, circuitsPath) {
1974
1786
  // Not used, kept for compatibility
1975
1787
  };
1976
1788
  }
1977
- function areCircuitsAvailable(circuitsPath) {
1978
- const wasmPath = path.join(circuitsPath, "build", "withdraw_regular_js", "withdraw_regular.wasm");
1979
- const zkeyPath = path.join(circuitsPath, "build", "withdraw_regular_final.zkey");
1980
- return fs.existsSync(wasmPath) && fs.existsSync(zkeyPath);
1789
+ async function areCircuitsAvailable(circuitsPath) {
1790
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1791
+ if (isBrowser) {
1792
+ return Boolean(circuitsPath && circuitsPath !== "");
1793
+ }
1794
+ const wasmPath = joinPath(circuitsPath, "build", "withdraw_regular_js", "withdraw_regular.wasm");
1795
+ const zkeyPath = joinPath(circuitsPath, "build", "withdraw_regular_final.zkey");
1796
+ const wasmExists = await fileExists(wasmPath);
1797
+ const zkeyExists = await fileExists(zkeyPath);
1798
+ return wasmExists && zkeyExists;
1981
1799
  }
1982
- function getDefaultCircuitsPath() {
1800
+ async function getDefaultCircuitsPath() {
1801
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
1802
+ if (isBrowser) {
1803
+ return "/circuits";
1804
+ }
1805
+ const { path: path2 } = await loadNodeModules();
1806
+ if (!path2 || typeof process === "undefined" || !process.cwd) {
1807
+ return "/circuits";
1808
+ }
1983
1809
  const possiblePaths = [
1984
- path.resolve(process.cwd(), "../../packages-new/circuits"),
1985
- path.resolve(process.cwd(), "../packages-new/circuits"),
1986
- path.resolve(process.cwd(), "packages-new/circuits"),
1987
- path.resolve(process.cwd(), "../../circuits"),
1988
- path.resolve(process.cwd(), "../circuits")
1810
+ path2.resolve(process.cwd(), "../../packages-new/circuits"),
1811
+ path2.resolve(process.cwd(), "../packages-new/circuits"),
1812
+ path2.resolve(process.cwd(), "packages-new/circuits"),
1813
+ path2.resolve(process.cwd(), "../../circuits"),
1814
+ path2.resolve(process.cwd(), "../circuits")
1989
1815
  ];
1990
1816
  for (const p of possiblePaths) {
1991
- if (areCircuitsAvailable(p)) {
1817
+ if (await areCircuitsAvailable(p)) {
1992
1818
  return p;
1993
1819
  }
1994
1820
  }
@@ -1996,7 +1822,7 @@ function getDefaultCircuitsPath() {
1996
1822
  }
1997
1823
 
1998
1824
  // src/core/CloakSDK.ts
1999
- var CLOAK_PROGRAM_ID = new PublicKey5("c1oak6tetxYnNfvXKFkpn1d98FxtK7B68vBQLYQpWKp");
1825
+ var CLOAK_PROGRAM_ID = new PublicKey4("c1oak6tetxYnNfvXKFkpn1d98FxtK7B68vBQLYQpWKp");
2000
1826
  var CLOAK_API_URL = "https://api.cloak.ag";
2001
1827
  var CloakSDK = class {
2002
1828
  /**
@@ -2004,21 +1830,35 @@ var CloakSDK = class {
2004
1830
  *
2005
1831
  * @param config - Client configuration
2006
1832
  *
2007
- * @example
1833
+ * @example Node.js mode (with keypair)
2008
1834
  * ```typescript
2009
1835
  * const sdk = new CloakSDK({
2010
1836
  * keypairBytes: keypair.secretKey,
2011
1837
  * network: "devnet"
2012
- * });
1838
+ * });
1839
+ * ```
1840
+ *
1841
+ * @example Browser mode (with wallet adapter)
1842
+ * ```typescript
1843
+ * const sdk = new CloakSDK({
1844
+ * wallet: walletAdapter,
1845
+ * network: "devnet"
1846
+ * });
1847
+ * ```
2013
1848
  */
2014
1849
  constructor(config) {
2015
- this.keypair = Keypair.fromSecretKey(config.keypairBytes);
1850
+ if (!config.keypairBytes && !config.wallet) {
1851
+ throw new Error("Must provide either keypairBytes (Node.js) or wallet (Browser)");
1852
+ }
1853
+ if (config.keypairBytes) {
1854
+ this.keypair = Keypair.fromSecretKey(config.keypairBytes);
1855
+ }
1856
+ this.wallet = config.wallet;
2016
1857
  this.cloakKeys = config.cloakKeys;
2017
1858
  this.storage = config.storage || new MemoryStorageAdapter();
2018
- const indexerUrl = config.indexerUrl || process.env.CLOAK_INDEXER_URL || CLOAK_API_URL;
2019
- const relayUrl = config.relayUrl || process.env.CLOAK_RELAY_URL || CLOAK_API_URL;
1859
+ const indexerUrl = config.indexerUrl || typeof process !== "undefined" && process.env?.CLOAK_INDEXER_URL || CLOAK_API_URL;
1860
+ const relayUrl = config.relayUrl || typeof process !== "undefined" && process.env?.CLOAK_RELAY_URL || CLOAK_API_URL;
2020
1861
  this.indexer = new IndexerService(indexerUrl);
2021
- this.artifactProver = new ArtifactProverService(indexerUrl, 5 * 60 * 1e3, 2e3);
2022
1862
  this.relay = new RelayService(relayUrl);
2023
1863
  this.depositRecovery = new DepositRecoveryService(this.indexer, indexerUrl);
2024
1864
  if (!this.cloakKeys) {
@@ -2044,6 +1884,24 @@ var CloakSDK = class {
2044
1884
  treasuryAddress: treasury
2045
1885
  };
2046
1886
  }
1887
+ /**
1888
+ * Get the public key for deposits (from keypair or wallet)
1889
+ */
1890
+ getPublicKey() {
1891
+ if (this.keypair) {
1892
+ return this.keypair.publicKey;
1893
+ }
1894
+ if (this.wallet?.publicKey) {
1895
+ return this.wallet.publicKey;
1896
+ }
1897
+ throw new Error("No public key available - wallet not connected or keypair not provided");
1898
+ }
1899
+ /**
1900
+ * Check if the SDK is using a wallet adapter
1901
+ */
1902
+ isWalletMode() {
1903
+ return !!this.wallet && !this.keypair;
1904
+ }
2047
1905
  /**
2048
1906
  * Deposit SOL into the Cloak protocol
2049
1907
  *
@@ -2084,7 +1942,8 @@ var CloakSDK = class {
2084
1942
  throw new Error("Note has already been deposited");
2085
1943
  }
2086
1944
  }
2087
- const balance = await connection.getBalance(this.keypair.publicKey);
1945
+ const payerPubkey = this.getPublicKey();
1946
+ const balance = await connection.getBalance(payerPubkey);
2088
1947
  const requiredAmount = note.amount + 5e3;
2089
1948
  if (balance < requiredAmount) {
2090
1949
  throw new Error(
@@ -2095,7 +1954,7 @@ var CloakSDK = class {
2095
1954
  const programId = this.config.programId || CLOAK_PROGRAM_ID;
2096
1955
  const depositIx = createDepositInstruction({
2097
1956
  programId,
2098
- payer: this.keypair.publicKey,
1957
+ payer: payerPubkey,
2099
1958
  pool: this.config.poolAddress,
2100
1959
  merkleTree: this.config.merkleTreeAddress,
2101
1960
  amount: note.amount,
@@ -2103,26 +1962,58 @@ var CloakSDK = class {
2103
1962
  });
2104
1963
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
2105
1964
  const transaction = new Transaction({
2106
- feePayer: this.keypair.publicKey,
2107
- blockhash,
2108
- lastValidBlockHeight
1965
+ feePayer: payerPubkey,
1966
+ recentBlockhash: blockhash
2109
1967
  }).add(depositIx);
2110
- if (!options?.skipPreflight) {
2111
- const simulation = await connection.simulateTransaction(transaction);
2112
- if (simulation.value.err) {
2113
- const logs = simulation.value.logs?.join("\n") || "No logs";
2114
- throw new Error(
2115
- `Transaction simulation failed: ${JSON.stringify(simulation.value.err)}
2116
- Logs:
2117
- ${logs}`
2118
- );
1968
+ if (!transaction.feePayer) {
1969
+ throw new Error("Transaction feePayer is not set");
1970
+ }
1971
+ if (!transaction.recentBlockhash) {
1972
+ throw new Error("Transaction recentBlockhash is not set");
1973
+ }
1974
+ let signature;
1975
+ if (this.wallet) {
1976
+ if (!this.wallet.publicKey) {
1977
+ throw new Error("Wallet not connected - publicKey is null");
2119
1978
  }
1979
+ if (this.wallet.signTransaction) {
1980
+ try {
1981
+ const signedTransaction = await this.wallet.signTransaction(transaction);
1982
+ const rawTransaction = signedTransaction.serialize();
1983
+ signature = await connection.sendRawTransaction(rawTransaction, {
1984
+ skipPreflight: options?.skipPreflight || false,
1985
+ preflightCommitment: "confirmed",
1986
+ maxRetries: 3
1987
+ });
1988
+ } catch (signError) {
1989
+ if (this.wallet.sendTransaction) {
1990
+ signature = await this.wallet.sendTransaction(transaction, connection, {
1991
+ skipPreflight: options?.skipPreflight || false,
1992
+ preflightCommitment: "confirmed",
1993
+ maxRetries: 3
1994
+ });
1995
+ } else {
1996
+ throw signError;
1997
+ }
1998
+ }
1999
+ } else if (this.wallet.sendTransaction) {
2000
+ signature = await this.wallet.sendTransaction(transaction, connection, {
2001
+ skipPreflight: options?.skipPreflight || false,
2002
+ preflightCommitment: "confirmed",
2003
+ maxRetries: 3
2004
+ });
2005
+ } else {
2006
+ throw new Error("Wallet adapter must provide either sendTransaction or signTransaction");
2007
+ }
2008
+ } else if (this.keypair) {
2009
+ signature = await connection.sendTransaction(transaction, [this.keypair], {
2010
+ skipPreflight: options?.skipPreflight || false,
2011
+ preflightCommitment: "confirmed",
2012
+ maxRetries: 3
2013
+ });
2014
+ } else {
2015
+ throw new Error("No signing method available - provide keypair or wallet");
2120
2016
  }
2121
- const signature = await connection.sendTransaction(transaction, [this.keypair], {
2122
- skipPreflight: options?.skipPreflight || false,
2123
- preflightCommitment: "confirmed",
2124
- maxRetries: 3
2125
- });
2126
2017
  const confirmation = await connection.confirmTransaction({
2127
2018
  signature,
2128
2019
  blockhash,
@@ -2184,13 +2075,13 @@ ${logs}`
2184
2075
  break;
2185
2076
  } else if (response.status === 404 && attempt < maxRetries2 - 1) {
2186
2077
  const delay = Math.min(initialRetryDelay2 * (attempt + 1), 2e3);
2187
- await new Promise((resolve2) => setTimeout(resolve2, delay));
2078
+ await new Promise((resolve) => setTimeout(resolve, delay));
2188
2079
  continue;
2189
2080
  }
2190
2081
  } catch (e) {
2191
2082
  if (attempt < maxRetries2 - 1) {
2192
2083
  const delay = Math.min(initialRetryDelay2 * (attempt + 1), 2e3);
2193
- await new Promise((resolve2) => setTimeout(resolve2, delay));
2084
+ await new Promise((resolve) => setTimeout(resolve, delay));
2194
2085
  continue;
2195
2086
  }
2196
2087
  }
@@ -2198,7 +2089,7 @@ ${logs}`
2198
2089
  }
2199
2090
  if (leafIndex === null) {
2200
2091
  const programId2 = this.config.programId || CLOAK_PROGRAM_ID;
2201
- const mintForSOL = new PublicKey5(new Uint8Array(32));
2092
+ const mintForSOL = new PublicKey4(new Uint8Array(32));
2202
2093
  const { merkleTree } = getShieldPoolPDAs(programId2, mintForSOL);
2203
2094
  const merkleTreeAccount = await connection.getAccountInfo(merkleTree);
2204
2095
  if (!merkleTreeAccount) {
@@ -2223,7 +2114,7 @@ ${logs}`
2223
2114
  const errorMessage = error instanceof Error ? error.message : String(error);
2224
2115
  if (errorMessage.includes("404") && attempt < maxRetries - 1) {
2225
2116
  const delay = Math.min(initialRetryDelay * (attempt + 1), 2e3);
2226
- await new Promise((resolve2) => setTimeout(resolve2, delay));
2117
+ await new Promise((resolve) => setTimeout(resolve, delay));
2227
2118
  continue;
2228
2119
  }
2229
2120
  throw error;
@@ -2349,8 +2240,9 @@ ${logs}`
2349
2240
  throw new Error(`Merkle proof path element at position ${i} must be 64 hex characters (32 bytes)`);
2350
2241
  }
2351
2242
  }
2352
- const circuitsPath = process.env.CIRCUITS_PATH || getDefaultCircuitsPath();
2353
- const useDirectProof = areCircuitsAvailable(circuitsPath);
2243
+ const isBrowser = typeof window !== "undefined" || typeof globalThis !== "undefined" && globalThis.window;
2244
+ const circuitsPath = isBrowser ? "/circuits" : typeof process !== "undefined" && process.env?.CIRCUITS_PATH || await getDefaultCircuitsPath();
2245
+ const useDirectProof = await areCircuitsAvailable(circuitsPath);
2354
2246
  let proofHex;
2355
2247
  let finalPublicInputs;
2356
2248
  if (useDirectProof) {
@@ -2413,43 +2305,9 @@ ${logs}`
2413
2305
  amount: note.amount
2414
2306
  };
2415
2307
  } else {
2416
- const proofInputs = {
2417
- privateInputs: {
2418
- amount: note.amount,
2419
- r: note.r,
2420
- sk_spend: note.sk_spend,
2421
- leaf_index: note.leafIndex,
2422
- merkle_path: {
2423
- path_elements: merkleProof.pathElements,
2424
- path_indices: merkleProof.pathIndices
2425
- }
2426
- },
2427
- publicInputs: {
2428
- root: merkleRoot,
2429
- nf: nullifierHex,
2430
- outputs_hash: outputsHashHex,
2431
- amount: note.amount
2432
- },
2433
- outputs: recipients.map((r) => ({
2434
- address: r.recipient.toBase58(),
2435
- amount: r.amount
2436
- }))
2437
- };
2438
- const proofResult = await this.artifactProver.generateProof(proofInputs, {
2439
- onProgress: options?.onProofProgress,
2440
- onError: options?.onProgress ? (error) => options.onProgress?.(`Proof generation error: ${error}`) : void 0
2441
- });
2442
- if (!proofResult.success || !proofResult.proof) {
2443
- let errorMessage = proofResult.error || "Proof generation failed";
2444
- if (errorMessage.startsWith("Proof generation failed: ")) {
2445
- errorMessage = errorMessage.substring("Proof generation failed: ".length);
2446
- }
2447
- errorMessage += `
2448
- Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., nullifier=${nullifierHex.slice(0, 16)}...`;
2449
- throw new Error(errorMessage);
2450
- }
2451
- proofHex = proofResult.proof;
2452
- finalPublicInputs = proofInputs.publicInputs;
2308
+ throw new Error(
2309
+ `Circuits not available at ${circuitsPath}. Make sure circuits are built and accessible. In browser, circuits should be served from /circuits. In Node.js, set CIRCUITS_PATH environment variable or ensure circuits are in the expected location.`
2310
+ );
2453
2311
  }
2454
2312
  const signature = await this.relay.submitWithdraw(
2455
2313
  {
@@ -2610,7 +2468,7 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2610
2468
  if (!getAssociatedTokenAddress) {
2611
2469
  throw new Error("getAssociatedTokenAddress not found");
2612
2470
  }
2613
- const outputMint2 = new PublicKey5(options.outputMint);
2471
+ const outputMint2 = new PublicKey4(options.outputMint);
2614
2472
  recipientAta = await getAssociatedTokenAddress(outputMint2, recipient);
2615
2473
  } catch (error) {
2616
2474
  throw new Error(
@@ -2631,8 +2489,8 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2631
2489
  }
2632
2490
  const nullifier = await computeNullifierAsync(note.sk_spend, note.leafIndex);
2633
2491
  const nullifierHex = nullifier.toString(16).padStart(64, "0");
2634
- const inputMint = new PublicKey5("11111111111111111111111111111111");
2635
- const outputMint = new PublicKey5(options.outputMint);
2492
+ const inputMint = new PublicKey4("11111111111111111111111111111111");
2493
+ const outputMint = new PublicKey4(options.outputMint);
2636
2494
  const outputsHash = await computeSwapOutputsHashAsync(
2637
2495
  inputMint,
2638
2496
  outputMint,
@@ -2647,8 +2505,9 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2647
2505
  if (!merkleProof.pathElements || merkleProof.pathElements.length === 0) {
2648
2506
  throw new Error("Merkle proof is invalid: missing path elements");
2649
2507
  }
2650
- const circuitsPath = process.env.CIRCUITS_PATH || getDefaultCircuitsPath();
2651
- const useDirectProof = areCircuitsAvailable(circuitsPath);
2508
+ const envCircuitsPath = typeof window !== "undefined" ? typeof process !== "undefined" && process.env?.NEXT_PUBLIC_CIRCUITS_PATH || void 0 : typeof process !== "undefined" && process.env?.CIRCUITS_PATH || void 0;
2509
+ const circuitsPath = envCircuitsPath || await getDefaultCircuitsPath();
2510
+ const useDirectProof = await areCircuitsAvailable(circuitsPath);
2652
2511
  let proofHex;
2653
2512
  let finalPublicInputs;
2654
2513
  if (useDirectProof) {
@@ -2692,46 +2551,9 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2692
2551
  amount: note.amount
2693
2552
  };
2694
2553
  } else {
2695
- const proofInputs = {
2696
- privateInputs: {
2697
- amount: note.amount,
2698
- r: note.r,
2699
- sk_spend: note.sk_spend,
2700
- leaf_index: note.leafIndex,
2701
- merkle_path: {
2702
- path_elements: merkleProof.pathElements,
2703
- path_indices: merkleProof.pathIndices
2704
- }
2705
- },
2706
- publicInputs: {
2707
- root: merkleRoot,
2708
- nf: nullifierHex,
2709
- outputs_hash: outputsHashHex,
2710
- amount: note.amount
2711
- },
2712
- outputs: [],
2713
- // Empty for swaps
2714
- swapParams: {
2715
- output_mint: options.outputMint,
2716
- recipient_ata: recipientAta.toBase58(),
2717
- min_output_amount: minOutputAmount
2718
- }
2719
- };
2720
- const proofResult = await this.artifactProver.generateProof(proofInputs, {
2721
- onProgress: options.onProofProgress,
2722
- onError: options.onProgress ? (error) => options.onProgress?.(`Proof generation error: ${error}`) : void 0
2723
- });
2724
- if (!proofResult.success || !proofResult.proof) {
2725
- let errorMessage = proofResult.error || "Proof generation failed";
2726
- if (errorMessage.startsWith("Proof generation failed: ")) {
2727
- errorMessage = errorMessage.substring("Proof generation failed: ".length);
2728
- }
2729
- errorMessage += `
2730
- Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., nullifier=${nullifierHex.slice(0, 16)}...`;
2731
- throw new Error(errorMessage);
2732
- }
2733
- proofHex = proofResult.proof;
2734
- finalPublicInputs = proofInputs.publicInputs;
2554
+ throw new Error(
2555
+ `Circuits not available at ${circuitsPath}. Make sure circuits are built and accessible. In browser, circuits should be served from /circuits. In Node.js, set CIRCUITS_PATH environment variable or ensure circuits are in the expected location.`
2556
+ );
2735
2557
  }
2736
2558
  const signature = await this.relay.submitSwap(
2737
2559
  {
@@ -3499,7 +3321,6 @@ function keypairToAdapter(keypair) {
3499
3321
  // src/index.ts
3500
3322
  var VERSION = "1.0.0";
3501
3323
  export {
3502
- ArtifactProverService,
3503
3324
  CLOAK_PROGRAM_ID,
3504
3325
  CloakError,
3505
3326
  CloakSDK,
@@ -3552,6 +3373,8 @@ export {
3552
3373
  generateMasterSeed,
3553
3374
  generateNote,
3554
3375
  generateNoteFromWallet,
3376
+ generateWithdrawRegularProof,
3377
+ generateWithdrawSwapProof,
3555
3378
  getAddressExplorerUrl,
3556
3379
  getDistributableAmount2 as getDistributableAmount,
3557
3380
  getExplorerUrl,