@cloak.ag/sdk 1.0.2 → 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((resolve) => setTimeout(resolve, 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
  /**
@@ -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
  );
@@ -1910,6 +1662,15 @@ async function fileExists(filePath) {
1910
1662
  return false;
1911
1663
  }
1912
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
+ }
1673
+ }
1913
1674
  return false;
1914
1675
  }
1915
1676
  async function generateWithdrawRegularProof(inputs, circuitsPath) {
@@ -2026,6 +1787,10 @@ async function generateWithdrawSwapProof(inputs, circuitsPath) {
2026
1787
  };
2027
1788
  }
2028
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
+ }
2029
1794
  const wasmPath = joinPath(circuitsPath, "build", "withdraw_regular_js", "withdraw_regular.wasm");
2030
1795
  const zkeyPath = joinPath(circuitsPath, "build", "withdraw_regular_final.zkey");
2031
1796
  const wasmExists = await fileExists(wasmPath);
@@ -2057,11 +1822,11 @@ async function getDefaultCircuitsPath() {
2057
1822
  }
2058
1823
 
2059
1824
  // src/core/CloakSDK.ts
2060
- var CLOAK_PROGRAM_ID = new PublicKey5("c1oak6tetxYnNfvXKFkpn1d98FxtK7B68vBQLYQpWKp");
1825
+ var CLOAK_PROGRAM_ID = new PublicKey4("c1oak6tetxYnNfvXKFkpn1d98FxtK7B68vBQLYQpWKp");
2061
1826
  var CLOAK_API_URL = "https://api.cloak.ag";
2062
1827
  var CloakSDK = class {
2063
1828
  /**
2064
- * Create a new Cloak SDK client
1829
+ * Create a new Cloak SDK client
2065
1830
  *
2066
1831
  * @param config - Client configuration
2067
1832
  *
@@ -2094,7 +1859,6 @@ var CloakSDK = class {
2094
1859
  const indexerUrl = config.indexerUrl || typeof process !== "undefined" && process.env?.CLOAK_INDEXER_URL || CLOAK_API_URL;
2095
1860
  const relayUrl = config.relayUrl || typeof process !== "undefined" && process.env?.CLOAK_RELAY_URL || CLOAK_API_URL;
2096
1861
  this.indexer = new IndexerService(indexerUrl);
2097
- this.artifactProver = new ArtifactProverService(indexerUrl, 5 * 60 * 1e3, 2e3);
2098
1862
  this.relay = new RelayService(relayUrl);
2099
1863
  this.depositRecovery = new DepositRecoveryService(this.indexer, indexerUrl);
2100
1864
  if (!this.cloakKeys) {
@@ -2199,27 +1963,48 @@ var CloakSDK = class {
2199
1963
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
2200
1964
  const transaction = new Transaction({
2201
1965
  feePayer: payerPubkey,
2202
- blockhash,
2203
- lastValidBlockHeight
1966
+ recentBlockhash: blockhash
2204
1967
  }).add(depositIx);
2205
- if (!options?.skipPreflight) {
2206
- const simulation = await connection.simulateTransaction(transaction);
2207
- if (simulation.value.err) {
2208
- const logs = simulation.value.logs?.join("\n") || "No logs";
2209
- throw new Error(
2210
- `Transaction simulation failed: ${JSON.stringify(simulation.value.err)}
2211
- Logs:
2212
- ${logs}`
2213
- );
2214
- }
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");
2215
1973
  }
2216
1974
  let signature;
2217
- if (this.wallet?.sendTransaction) {
2218
- signature = await this.wallet.sendTransaction(transaction, connection, {
2219
- skipPreflight: options?.skipPreflight || false,
2220
- preflightCommitment: "confirmed",
2221
- maxRetries: 3
2222
- });
1975
+ if (this.wallet) {
1976
+ if (!this.wallet.publicKey) {
1977
+ throw new Error("Wallet not connected - publicKey is null");
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
+ }
2223
2008
  } else if (this.keypair) {
2224
2009
  signature = await connection.sendTransaction(transaction, [this.keypair], {
2225
2010
  skipPreflight: options?.skipPreflight || false,
@@ -2304,7 +2089,7 @@ ${logs}`
2304
2089
  }
2305
2090
  if (leafIndex === null) {
2306
2091
  const programId2 = this.config.programId || CLOAK_PROGRAM_ID;
2307
- const mintForSOL = new PublicKey5(new Uint8Array(32));
2092
+ const mintForSOL = new PublicKey4(new Uint8Array(32));
2308
2093
  const { merkleTree } = getShieldPoolPDAs(programId2, mintForSOL);
2309
2094
  const merkleTreeAccount = await connection.getAccountInfo(merkleTree);
2310
2095
  if (!merkleTreeAccount) {
@@ -2455,7 +2240,8 @@ ${logs}`
2455
2240
  throw new Error(`Merkle proof path element at position ${i} must be 64 hex characters (32 bytes)`);
2456
2241
  }
2457
2242
  }
2458
- const circuitsPath = typeof process !== "undefined" && process.env?.CIRCUITS_PATH || await getDefaultCircuitsPath();
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();
2459
2245
  const useDirectProof = await areCircuitsAvailable(circuitsPath);
2460
2246
  let proofHex;
2461
2247
  let finalPublicInputs;
@@ -2519,43 +2305,9 @@ ${logs}`
2519
2305
  amount: note.amount
2520
2306
  };
2521
2307
  } else {
2522
- const proofInputs = {
2523
- privateInputs: {
2524
- amount: note.amount,
2525
- r: note.r,
2526
- sk_spend: note.sk_spend,
2527
- leaf_index: note.leafIndex,
2528
- merkle_path: {
2529
- path_elements: merkleProof.pathElements,
2530
- path_indices: merkleProof.pathIndices
2531
- }
2532
- },
2533
- publicInputs: {
2534
- root: merkleRoot,
2535
- nf: nullifierHex,
2536
- outputs_hash: outputsHashHex,
2537
- amount: note.amount
2538
- },
2539
- outputs: recipients.map((r) => ({
2540
- address: r.recipient.toBase58(),
2541
- amount: r.amount
2542
- }))
2543
- };
2544
- const proofResult = await this.artifactProver.generateProof(proofInputs, {
2545
- onProgress: options?.onProofProgress,
2546
- onError: options?.onProgress ? (error) => options.onProgress?.(`Proof generation error: ${error}`) : void 0
2547
- });
2548
- if (!proofResult.success || !proofResult.proof) {
2549
- let errorMessage = proofResult.error || "Proof generation failed";
2550
- if (errorMessage.startsWith("Proof generation failed: ")) {
2551
- errorMessage = errorMessage.substring("Proof generation failed: ".length);
2552
- }
2553
- errorMessage += `
2554
- Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., nullifier=${nullifierHex.slice(0, 16)}...`;
2555
- throw new Error(errorMessage);
2556
- }
2557
- proofHex = proofResult.proof;
2558
- 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
+ );
2559
2311
  }
2560
2312
  const signature = await this.relay.submitWithdraw(
2561
2313
  {
@@ -2716,7 +2468,7 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2716
2468
  if (!getAssociatedTokenAddress) {
2717
2469
  throw new Error("getAssociatedTokenAddress not found");
2718
2470
  }
2719
- const outputMint2 = new PublicKey5(options.outputMint);
2471
+ const outputMint2 = new PublicKey4(options.outputMint);
2720
2472
  recipientAta = await getAssociatedTokenAddress(outputMint2, recipient);
2721
2473
  } catch (error) {
2722
2474
  throw new Error(
@@ -2737,8 +2489,8 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2737
2489
  }
2738
2490
  const nullifier = await computeNullifierAsync(note.sk_spend, note.leafIndex);
2739
2491
  const nullifierHex = nullifier.toString(16).padStart(64, "0");
2740
- const inputMint = new PublicKey5("11111111111111111111111111111111");
2741
- const outputMint = new PublicKey5(options.outputMint);
2492
+ const inputMint = new PublicKey4("11111111111111111111111111111111");
2493
+ const outputMint = new PublicKey4(options.outputMint);
2742
2494
  const outputsHash = await computeSwapOutputsHashAsync(
2743
2495
  inputMint,
2744
2496
  outputMint,
@@ -2753,7 +2505,8 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2753
2505
  if (!merkleProof.pathElements || merkleProof.pathElements.length === 0) {
2754
2506
  throw new Error("Merkle proof is invalid: missing path elements");
2755
2507
  }
2756
- const circuitsPath = typeof process !== "undefined" && process.env?.CIRCUITS_PATH || await getDefaultCircuitsPath();
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();
2757
2510
  const useDirectProof = await areCircuitsAvailable(circuitsPath);
2758
2511
  let proofHex;
2759
2512
  let finalPublicInputs;
@@ -2798,46 +2551,9 @@ Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., n
2798
2551
  amount: note.amount
2799
2552
  };
2800
2553
  } else {
2801
- const proofInputs = {
2802
- privateInputs: {
2803
- amount: note.amount,
2804
- r: note.r,
2805
- sk_spend: note.sk_spend,
2806
- leaf_index: note.leafIndex,
2807
- merkle_path: {
2808
- path_elements: merkleProof.pathElements,
2809
- path_indices: merkleProof.pathIndices
2810
- }
2811
- },
2812
- publicInputs: {
2813
- root: merkleRoot,
2814
- nf: nullifierHex,
2815
- outputs_hash: outputsHashHex,
2816
- amount: note.amount
2817
- },
2818
- outputs: [],
2819
- // Empty for swaps
2820
- swapParams: {
2821
- output_mint: options.outputMint,
2822
- recipient_ata: recipientAta.toBase58(),
2823
- min_output_amount: minOutputAmount
2824
- }
2825
- };
2826
- const proofResult = await this.artifactProver.generateProof(proofInputs, {
2827
- onProgress: options.onProofProgress,
2828
- onError: options.onProgress ? (error) => options.onProgress?.(`Proof generation error: ${error}`) : void 0
2829
- });
2830
- if (!proofResult.success || !proofResult.proof) {
2831
- let errorMessage = proofResult.error || "Proof generation failed";
2832
- if (errorMessage.startsWith("Proof generation failed: ")) {
2833
- errorMessage = errorMessage.substring("Proof generation failed: ".length);
2834
- }
2835
- errorMessage += `
2836
- Note details: leafIndex=${note.leafIndex}, root=${merkleRoot.slice(0, 16)}..., nullifier=${nullifierHex.slice(0, 16)}...`;
2837
- throw new Error(errorMessage);
2838
- }
2839
- proofHex = proofResult.proof;
2840
- 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
+ );
2841
2557
  }
2842
2558
  const signature = await this.relay.submitSwap(
2843
2559
  {
@@ -3605,7 +3321,6 @@ function keypairToAdapter(keypair) {
3605
3321
  // src/index.ts
3606
3322
  var VERSION = "1.0.0";
3607
3323
  export {
3608
- ArtifactProverService,
3609
3324
  CLOAK_PROGRAM_ID,
3610
3325
  CloakError,
3611
3326
  CloakSDK,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloak.ag/sdk",
3
3
  "description": "TypeScript SDK for Cloak",
4
- "version": "1.0.2",
4
+ "version": "1.0.3",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",