@zama-fhe/relayer-sdk 0.4.0-alpha.0 → 0.4.0-alpha.1

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/lib/node.cjs CHANGED
@@ -28,31 +28,9 @@ const SERIALIZED_SIZE_LIMIT_CIPHERTEXT = BigInt(1024 * 1024 * 512);
28
28
  const SERIALIZED_SIZE_LIMIT_PK = BigInt(1024 * 1024 * 512);
29
29
  const SERIALIZED_SIZE_LIMIT_CRS = BigInt(1024 * 1024 * 512);
30
30
 
31
- function setAuth(init, auth) {
32
- if (auth) {
33
- switch (auth.__type) {
34
- case 'BearerToken':
35
- init.headers['Authorization'] =
36
- `Bearer ${auth.token}`;
37
- break;
38
- case 'ApiKeyHeader':
39
- init.headers[auth.header || 'x-api-key'] =
40
- auth.value;
41
- break;
42
- case 'ApiKeyCookie':
43
- if (typeof window !== 'undefined') {
44
- document.cookie = `${auth.cookie || 'x-api-key'}=${auth.value}; path=/; SameSite=Lax; Secure; HttpOnly;`;
45
- init.credentials = 'include';
46
- }
47
- else {
48
- let cookie = `${auth.cookie || 'x-api-key'}=${auth.value};`;
49
- init.headers['Cookie'] = cookie;
50
- }
51
- break;
52
- }
53
- }
54
- return init;
55
- }
31
+ // This file is auto-generated
32
+ const version = '0.4.0-alpha.1';
33
+ const sdkName = '@zama-fhe/relayer-sdk';
56
34
 
57
35
  function getErrorCause(e) {
58
36
  if (e instanceof Error && typeof e.cause === 'object' && e.cause !== null) {
@@ -234,7 +212,39 @@ function throwRelayerUnknownError(operation, error, message) {
234
212
  });
235
213
  }
236
214
 
237
- ////////////////////////////////////////////////////////////////////////////////
215
+ /**
216
+ * Set the authentication method for the request. The default is no authentication.
217
+ * It supports:
218
+ * - Bearer Token
219
+ * - Custom header
220
+ * - Custom cookie
221
+ */
222
+ function setAuth(init, auth) {
223
+ if (auth) {
224
+ switch (auth.__type) {
225
+ case 'BearerToken':
226
+ init.headers['Authorization'] =
227
+ `Bearer ${auth.token}`;
228
+ break;
229
+ case 'ApiKeyHeader':
230
+ init.headers[auth.header || 'x-api-key'] =
231
+ auth.value;
232
+ break;
233
+ case 'ApiKeyCookie':
234
+ if (typeof window !== 'undefined') {
235
+ document.cookie = `${auth.cookie || 'x-api-key'}=${auth.value}; path=/; SameSite=Lax; Secure; HttpOnly;`;
236
+ init.credentials = 'include';
237
+ }
238
+ else {
239
+ let cookie = `${auth.cookie || 'x-api-key'}=${auth.value};`;
240
+ init.headers['Cookie'] = cookie;
241
+ }
242
+ break;
243
+ }
244
+ }
245
+ return init;
246
+ }
247
+
238
248
  function assertIsRelayerV1FetchResponseJson(json) {
239
249
  if (!json || typeof json !== 'object') {
240
250
  throw new Error('Unexpected response JSON.');
@@ -245,11 +255,13 @@ function assertIsRelayerV1FetchResponseJson(json) {
245
255
  throw new Error("Unexpected response JSON format: missing 'response' property.");
246
256
  }
247
257
  }
248
- async function fetchRelayerJsonRpcPost(relayerOperation, url, payload, options) {
258
+ async function fetchRelayerV1Post(relayerOperation, url, payload, options) {
249
259
  const init = setAuth({
250
260
  method: 'POST',
251
261
  headers: {
252
262
  'Content-Type': 'application/json',
263
+ 'ZAMA-SDK-VERSION': `${version}`,
264
+ 'ZAMA-SDK-NAME': `${sdkName}`,
253
265
  },
254
266
  body: JSON.stringify(payload),
255
267
  }, options?.auth);
@@ -280,14 +292,20 @@ async function fetchRelayerJsonRpcPost(relayerOperation, url, payload, options)
280
292
  }
281
293
  return json;
282
294
  }
283
- async function fetchRelayerGet(relayerOperation, url) {
295
+ async function fetchRelayerV1Get(relayerOperation, url) {
296
+ const init = {
297
+ method: 'GET',
298
+ headers: {
299
+ 'ZAMA-SDK-VERSION': `${version}`,
300
+ 'ZAMA-SDK-NAME': `${sdkName}`,
301
+ },
302
+ };
284
303
  let response;
285
304
  let json;
286
305
  try {
287
- response = await fetch(url);
306
+ response = await fetch(url, init);
288
307
  }
289
308
  catch (e) {
290
- console.log(e);
291
309
  throwRelayerUnknownError(relayerOperation, e);
292
310
  }
293
311
  if (!response.ok) {
@@ -315,7 +333,7 @@ const getKeysFromRelayer = async (versionUrl, publicKeyId) => {
315
333
  if (keyurlCache[versionUrl]) {
316
334
  return keyurlCache[versionUrl];
317
335
  }
318
- const data = await fetchRelayerGet('KEY_URL', `${versionUrl}/keyurl`);
336
+ const data = await fetchRelayerV1Get('KEY_URL', `${versionUrl}/keyurl`);
319
337
  try {
320
338
  let pubKeyUrl;
321
339
  // If no publicKeyId is provided, use the first one
@@ -404,7 +422,7 @@ class RelayerErrorBase extends Error {
404
422
  _docsPath;
405
423
  _docsUrl;
406
424
  _version;
407
- static VERSION = '0.3.0-6';
425
+ static VERSION = version;
408
426
  static DEFAULT_DOCS_BASE_URL = 'https//docs.zama.org';
409
427
  static FULL_VERSION = `@zama-fhe/relayer-sdk@${RelayerErrorBase.VERSION}`;
410
428
  constructor(params) {
@@ -813,6 +831,14 @@ function assertRecordStringArrayProperty(o, property, objName) {
813
831
  }
814
832
  }
815
833
  }
834
+ function safeJSONstringify(o) {
835
+ try {
836
+ return JSON.stringify(o, (_, v) => typeof v === 'bigint' ? v.toString() : v);
837
+ }
838
+ catch {
839
+ return '';
840
+ }
841
+ }
816
842
 
817
843
  const abiKmsVerifier = [
818
844
  'function getKmsSigners() view returns (address[])',
@@ -912,6 +938,7 @@ const getCoprocessorSignersThreshold = async (provider, inputVerifierContractAdd
912
938
  return Number(threshold); // threshold is always supposed to fit in a number
913
939
  };
914
940
 
941
+ // This file contains common utilities for both user and public decryption requests
915
942
  const NumEncryptedBits = {
916
943
  0: 2, // ebool
917
944
  2: 8, // euint8
@@ -922,17 +949,6 @@ const NumEncryptedBits = {
922
949
  7: 160, // eaddress
923
950
  8: 256, // euint256
924
951
  };
925
- function getHandleType(handle) {
926
- if (handle.length !== 66) {
927
- throw new Error(`Handle ${handle} is not of valid length`);
928
- }
929
- const hexPair = handle.slice(-4, -2).toLowerCase();
930
- const typeDiscriminant = parseInt(hexPair, 16);
931
- if (!(typeDiscriminant in NumEncryptedBits)) {
932
- throw new Error(`Handle ${handle} is not of valid type`);
933
- }
934
- return typeDiscriminant;
935
- }
936
952
  function checkEncryptedBits(handles) {
937
953
  let total = 0;
938
954
  for (const handle of handles) {
@@ -1342,9 +1358,7 @@ function checkDeadlineValidity(startTimestamp, durationDays) {
1342
1358
  throw Error('User decrypt request has expired');
1343
1359
  }
1344
1360
  }
1345
- const userDecryptRequest = (kmsSigners, gatewayChainId, chainId, verifyingContractAddress, aclContractAddress,
1346
- //relayerUrl: string,
1347
- relayerProvider, provider, instanceOptions) => async (_handles, privateKey, publicKey, signature, contractAddresses, userAddress, startTimestamp, durationDays, options) => {
1361
+ const userDecryptRequest = (kmsSigners, gatewayChainId, chainId, verifyingContractAddress, aclContractAddress, relayerProvider, provider, defaultOptions) => async (_handles, privateKey, publicKey, signature, contractAddresses, userAddress, startTimestamp, durationDays, options) => {
1348
1362
  const extraData = '0x00';
1349
1363
  let pubKey;
1350
1364
  let privKey;
@@ -1358,16 +1372,16 @@ relayerProvider, provider, instanceOptions) => async (_handles, privateKey, publ
1358
1372
  // Casting handles if string
1359
1373
  const signatureSanitized = signature.replace(/^(0x)/, '');
1360
1374
  const publicKeySanitized = publicKey.replace(/^(0x)/, '');
1361
- const handles = _handles.map((h) => ({
1375
+ const handleContractPairs = _handles.map((h) => ({
1362
1376
  handle: typeof h.handle === 'string'
1363
1377
  ? toHexString(hexToBytes(h.handle), true)
1364
1378
  : toHexString(h.handle, true),
1365
1379
  contractAddress: getAddress$1(h.contractAddress),
1366
1380
  }));
1367
- checkEncryptedBits(handles.map((h) => h.handle));
1381
+ checkEncryptedBits(handleContractPairs.map((h) => h.handle));
1368
1382
  checkDeadlineValidity(BigInt(startTimestamp), BigInt(durationDays));
1369
- const acl = new ethers.ethers.Contract(aclContractAddress, aclABI$1, provider);
1370
- const verifications = handles.map(async ({ handle, contractAddress }) => {
1383
+ const acl = new ethers.Contract(aclContractAddress, aclABI$1, provider);
1384
+ const verifications = handleContractPairs.map(async ({ handle, contractAddress }) => {
1371
1385
  const userAllowed = await acl.persistAllowed(handle, userAddress);
1372
1386
  const contractAllowed = await acl.persistAllowed(handle, contractAddress);
1373
1387
  if (!userAllowed) {
@@ -1391,7 +1405,7 @@ relayerProvider, provider, instanceOptions) => async (_handles, privateKey, publ
1391
1405
  throw e;
1392
1406
  });
1393
1407
  const payloadForRequest = {
1394
- handleContractPairs: handles,
1408
+ handleContractPairs,
1395
1409
  requestValidity: {
1396
1410
  startTimestamp: startTimestamp.toString(), // Convert to string
1397
1411
  durationDays: durationDays.toString(), // Convert to string
@@ -1403,13 +1417,10 @@ relayerProvider, provider, instanceOptions) => async (_handles, privateKey, publ
1403
1417
  publicKey: publicKeySanitized,
1404
1418
  extraData,
1405
1419
  };
1406
- const json = await relayerProvider.fetchPostUserDecrypt(payloadForRequest, options ?? instanceOptions);
1407
- // const json = await fetchRelayerJsonRpcPost(
1408
- // 'USER_DECRYPT',
1409
- // `${relayerUrl}/v1/user-decrypt`,
1410
- // payloadForRequest,
1411
- // instanceOptions ?? options,
1412
- // );
1420
+ const json = await relayerProvider.fetchPostUserDecrypt(payloadForRequest, {
1421
+ ...defaultOptions,
1422
+ ...options,
1423
+ });
1413
1424
  // assume the KMS Signers have the correct order
1414
1425
  let indexedKmsSigners = kmsSigners.map((signer, index) => {
1415
1426
  return TKMS.new_server_id_addr(index + 1, signer);
@@ -1431,13 +1442,13 @@ relayerProvider, provider, instanceOptions) => async (_handles, privateKey, publ
1431
1442
  signature: signatureSanitized,
1432
1443
  client_address: userAddress,
1433
1444
  enc_key: publicKeySanitized,
1434
- ciphertext_handles: handles.map((h) => h.handle.replace(/^0x/, '')),
1445
+ ciphertext_handles: handleContractPairs.map((h) => h.handle.replace(/^0x/, '')),
1435
1446
  eip712_verifying_contract: verifyingContractAddress,
1436
1447
  };
1437
1448
  const decryption = TKMS.process_user_decryption_resp_from_js(client, payloadForVerification, eip712Domain, json, //json.response,
1438
1449
  pubKey, privKey, true);
1439
1450
  const listBigIntDecryptions = decryption.map((d) => bytesToBigInt(d.bytes));
1440
- const results = buildUserDecryptResults(handles.map((h) => h.handle), listBigIntDecryptions);
1451
+ const results = buildUserDecryptResults(handleContractPairs.map((h) => h.handle), listBigIntDecryptions);
1441
1452
  return results;
1442
1453
  }
1443
1454
  catch (e) {
@@ -1729,6 +1740,15 @@ function checksummedAddressToBytes20(address) {
1729
1740
  return bytes;
1730
1741
  }
1731
1742
 
1743
+ class FhevmHandleError extends RelayerErrorBase {
1744
+ constructor({ handle, message }) {
1745
+ super({
1746
+ message: message ?? `FHEVM Handle "${handle}" is invalid.`,
1747
+ name: 'FhevmHandleError',
1748
+ });
1749
+ }
1750
+ }
1751
+
1732
1752
  ////////////////////////////////////////////////////////////////////////////////
1733
1753
  // FhevmHandle
1734
1754
  ////////////////////////////////////////////////////////////////////////////////
@@ -1761,6 +1781,16 @@ class FhevmHandle {
1761
1781
  160: 7,
1762
1782
  256: 8,
1763
1783
  };
1784
+ static FheTypeIdToSolidityPrimitiveType = {
1785
+ 0: 'bool',
1786
+ 2: 'uint256',
1787
+ 3: 'uint256',
1788
+ 4: 'uint256',
1789
+ 5: 'uint256',
1790
+ 6: 'uint256',
1791
+ 7: 'address',
1792
+ 8: 'uint256',
1793
+ };
1764
1794
  static {
1765
1795
  Object.freeze(FhevmHandle.FheTypeIdToEncryptionBitwidths);
1766
1796
  Object.freeze(FhevmHandle.FheTypeEncryptionBitwidthsToId);
@@ -1895,6 +1925,41 @@ class FhevmHandle {
1895
1925
  toBytes32Hex() {
1896
1926
  return bytesToHex(this.toBytes32());
1897
1927
  }
1928
+ static checkHandleHex(handle) {
1929
+ if (!isBytes32Hex(handle)) {
1930
+ throw new FhevmHandleError({ handle });
1931
+ }
1932
+ }
1933
+ static isFheTypeId(value) {
1934
+ switch (value) {
1935
+ case 0:
1936
+ // 1: euint4 is deprecated
1937
+ case 2:
1938
+ case 3:
1939
+ case 4:
1940
+ case 5:
1941
+ case 6:
1942
+ case 7:
1943
+ case 8:
1944
+ return true;
1945
+ default:
1946
+ return false;
1947
+ }
1948
+ }
1949
+ static getFheTypeId(handle) {
1950
+ if (!isBytes32Hex(handle)) {
1951
+ throw new FhevmHandleError({ handle });
1952
+ }
1953
+ const hexPair = handle.slice(-4, -2).toLowerCase();
1954
+ const typeDiscriminant = parseInt(hexPair, 16);
1955
+ if (!FhevmHandle.isFheTypeId(typeDiscriminant)) {
1956
+ throw new FhevmHandleError({
1957
+ handle,
1958
+ message: `FHEVM Handle "${handle}" is invalid. Unknown FheType: ${typeDiscriminant}`,
1959
+ });
1960
+ }
1961
+ return typeDiscriminant;
1962
+ }
1898
1963
  }
1899
1964
 
1900
1965
  // Add type checking
@@ -1933,9 +1998,7 @@ function isFhevmRelayerInputProofResponse(json) {
1933
1998
  return (response.signatures.every((s) => typeof s === 'string') &&
1934
1999
  response.handles.every((h) => typeof h === 'string'));
1935
2000
  }
1936
- const createRelayerEncryptedInput = (aclContractAddress, verifyingContractAddressInputVerification, chainId, gatewayChainId,
1937
- //relayerUrl: string,
1938
- relayerProvider, tfheCompactPublicKey, publicParams, coprocessorSigners, thresholdCoprocessorSigners, instanceOptions) => (contractAddress, userAddress) => {
2001
+ const createRelayerEncryptedInput = (aclContractAddress, verifyingContractAddressInputVerification, chainId, gatewayChainId, relayerProvider, tfheCompactPublicKey, publicParams, coprocessorSigners, thresholdCoprocessorSigners, defaultOptions) => (contractAddress, userAddress) => {
1939
2002
  if (!ethers.isAddress(contractAddress)) {
1940
2003
  throw new Error('Contract address is not a valid address.');
1941
2004
  }
@@ -1987,11 +2050,13 @@ relayerProvider, tfheCompactPublicKey, publicParams, coprocessorSigners, thresho
1987
2050
  getBits() {
1988
2051
  return input.getBits();
1989
2052
  },
2053
+ getCiphertextWithInputVerification() {
2054
+ return input.encrypt();
2055
+ },
1990
2056
  encrypt: async (options) => {
1991
2057
  const extraData = '0x00';
1992
2058
  const bits = input.getBits();
1993
2059
  const ciphertext = input.encrypt();
1994
- //console.log(`ciphertext=${toHexString(ciphertext)}`);
1995
2060
  const payload = {
1996
2061
  contractAddress: getAddress(contractAddress),
1997
2062
  userAddress: getAddress(userAddress),
@@ -1999,13 +2064,10 @@ relayerProvider, tfheCompactPublicKey, publicParams, coprocessorSigners, thresho
1999
2064
  contractChainId: ('0x' + chainId.toString(16)),
2000
2065
  extraData,
2001
2066
  };
2002
- const json = await relayerProvider.fetchPostInputProof(payload, options ?? instanceOptions);
2003
- // const json = await fetchRelayerJsonRpcPost(
2004
- // 'INPUT_PROOF',
2005
- // `${relayerUrl}/v1/input-proof`,
2006
- // payload,
2007
- // options ?? instanceOptions,
2008
- // );
2067
+ const json = await relayerProvider.fetchPostInputProof(payload, {
2068
+ ...defaultOptions,
2069
+ ...options,
2070
+ });
2009
2071
  if (!isFhevmRelayerInputProofResponse(json)) {
2010
2072
  throwRelayerInternalError('INPUT_PROOF', json);
2011
2073
  }
@@ -2017,7 +2079,6 @@ relayerProvider, tfheCompactPublicKey, publicParams, coprocessorSigners, thresho
2017
2079
  fheTypeEncryptionBitwidths: bits,
2018
2080
  });
2019
2081
  const handles = fhevmHandles.map((h) => h.toBytes32());
2020
- //const result = json.response;
2021
2082
  const result = json;
2022
2083
  // Note that the hex strings returned by the relayer do have have the 0x prefix
2023
2084
  if (result.handles && result.handles.length > 0) {
@@ -2084,6 +2145,21 @@ relayerProvider, tfheCompactPublicKey, publicParams, coprocessorSigners, thresho
2084
2145
  };
2085
2146
  };
2086
2147
 
2148
+ function ensureError(e) {
2149
+ if (e instanceof Error) {
2150
+ return e;
2151
+ }
2152
+ const message = e.message ?? 'Non-Error value caught in exception handler';
2153
+ const name = e.name ?? 'ErrorWrapper';
2154
+ const cause = e.cause ?? e;
2155
+ const err = new Error(message, { cause });
2156
+ err.name = name;
2157
+ return err;
2158
+ }
2159
+ function assertNever(value, message) {
2160
+ throw new InternalError({ message });
2161
+ }
2162
+
2087
2163
  const aclABI = [
2088
2164
  'function isAllowedForDecryption(bytes32 handle) view returns (bool)',
2089
2165
  ];
@@ -2109,7 +2185,7 @@ function abiEncodeClearValues(clearValues) {
2109
2185
  const abiValues = [];
2110
2186
  for (let i = 0; i < handlesBytes32Hex.length; ++i) {
2111
2187
  const handle = handlesBytes32Hex[i];
2112
- const handleType = getHandleType(handle);
2188
+ const handleType = FhevmHandle.getFheTypeId(handle);
2113
2189
  let clearTextValue = clearValues[handle];
2114
2190
  if (typeof clearTextValue === 'boolean') {
2115
2191
  clearTextValue = clearTextValue ? '0x01' : '0x00';
@@ -2146,7 +2222,7 @@ function abiEncodeClearValues(clearValues) {
2146
2222
  break;
2147
2223
  }
2148
2224
  default: {
2149
- throw new Error(`Unsupported Fhevm primitive type id: ${handleType}`);
2225
+ assertNever(handleType, `Unsupported Fhevm primitive type id: ${handleType}`);
2150
2226
  }
2151
2227
  }
2152
2228
  }
@@ -2171,21 +2247,11 @@ function buildDecryptionProof(kmsSignatures, extraData) {
2171
2247
  ]);
2172
2248
  return decryptionProof;
2173
2249
  }
2174
- const CiphertextType = {
2175
- 0: 'bool',
2176
- 2: 'uint256',
2177
- 3: 'uint256',
2178
- 4: 'uint256',
2179
- 5: 'uint256',
2180
- 6: 'uint256',
2181
- 7: 'address',
2182
- 8: 'uint256',
2183
- };
2184
2250
  function deserializeClearValues(handles, decryptedResult) {
2185
2251
  let typesList = [];
2186
2252
  for (const handle of handles) {
2187
- const hexPair = handle.slice(-4, -2).toLowerCase();
2188
- const typeDiscriminant = parseInt(hexPair, 16);
2253
+ const typeDiscriminant = FhevmHandle.getFheTypeId(handle);
2254
+ assertRelayer(FhevmHandle.isFheTypeId(typeDiscriminant));
2189
2255
  typesList.push(typeDiscriminant);
2190
2256
  }
2191
2257
  const restoredEncoded = '0x' +
@@ -2193,7 +2259,7 @@ function deserializeClearValues(handles, decryptedResult) {
2193
2259
  decryptedResult.slice(2) +
2194
2260
  '00'.repeat(32); // dummy empty bytes[] length (ignored)
2195
2261
  const abiTypes = typesList.map((t) => {
2196
- const abiType = CiphertextType[t]; // all types are valid because this was supposedly checked already inside the `checkEncryptedBits` function
2262
+ const abiType = FhevmHandle.FheTypeIdToSolidityPrimitiveType[t]; // all types are valid because this was supposedly checked already inside the `checkEncryptedBits` function
2197
2263
  return abiType;
2198
2264
  });
2199
2265
  const coder = new ethers.AbiCoder();
@@ -2204,9 +2270,7 @@ function deserializeClearValues(handles, decryptedResult) {
2204
2270
  handles.forEach((handle, idx) => (results[handle] = rawValues[idx]));
2205
2271
  return results;
2206
2272
  }
2207
- const publicDecryptRequest = (kmsSigners, thresholdSigners, gatewayChainId, verifyingContractAddress, aclContractAddress,
2208
- //relayerUrl: string,
2209
- relayerProvider, provider, instanceOptions) => async (_handles, options) => {
2273
+ const publicDecryptRequest = (kmsSigners, thresholdSigners, gatewayChainId, verifyingContractAddress, aclContractAddress, relayerProvider, provider, defaultOptions) => async (_handles, options) => {
2210
2274
  const extraData = '0x00';
2211
2275
  const acl = new ethers.ethers.Contract(aclContractAddress, aclABI, provider);
2212
2276
  let handles;
@@ -2231,13 +2295,10 @@ relayerProvider, provider, instanceOptions) => async (_handles, options) => {
2231
2295
  ciphertextHandles: handles,
2232
2296
  extraData,
2233
2297
  };
2234
- const json = await relayerProvider.fetchPostPublicDecrypt(payloadForRequest, options ?? instanceOptions);
2235
- // const json = await fetchRelayerJsonRpcPost(
2236
- // 'PUBLIC_DECRYPT',
2237
- // `${relayerUrl}/v1/public-decrypt`,
2238
- // payloadForRequest,
2239
- // options ?? instanceOptions,
2240
- // );
2298
+ const json = await relayerProvider.fetchPostPublicDecrypt(payloadForRequest, {
2299
+ ...defaultOptions,
2300
+ ...options,
2301
+ });
2241
2302
  // verify signatures on decryption:
2242
2303
  const domain = {
2243
2304
  name: 'Decryption',
@@ -2433,7 +2494,7 @@ class RelayerV1Provider extends AbstractRelayerProvider {
2433
2494
  return 1;
2434
2495
  }
2435
2496
  async fetchGetKeyUrl() {
2436
- const response = await fetchRelayerGet('KEY_URL', this.keyUrl);
2497
+ const response = await fetchRelayerV1Get('KEY_URL', this.keyUrl);
2437
2498
  return response;
2438
2499
  }
2439
2500
  async fetchPostInputProof(payload, options) {
@@ -2451,12 +2512,12 @@ class RelayerV1Provider extends AbstractRelayerProvider {
2451
2512
  }
2452
2513
  }
2453
2514
  */
2454
- const json = await fetchRelayerJsonRpcPost('INPUT_PROOF', this.inputProof, payload, options);
2515
+ const json = await fetchRelayerV1Post('INPUT_PROOF', this.inputProof, payload, options);
2455
2516
  assertIsRelayerInputProofResult(json.response, 'fetchPostInputProof()');
2456
2517
  return json.response;
2457
2518
  }
2458
2519
  async fetchPostPublicDecrypt(payload, options) {
2459
- const json = await fetchRelayerJsonRpcPost('PUBLIC_DECRYPT', this.publicDecrypt, payload, options);
2520
+ const json = await fetchRelayerV1Post('PUBLIC_DECRYPT', this.publicDecrypt, payload, options);
2460
2521
  const response = json.response[0];
2461
2522
  const result = {
2462
2523
  signatures: response.signatures,
@@ -2467,24 +2528,12 @@ class RelayerV1Provider extends AbstractRelayerProvider {
2467
2528
  return result;
2468
2529
  }
2469
2530
  async fetchPostUserDecrypt(payload, options) {
2470
- const json = await fetchRelayerJsonRpcPost('USER_DECRYPT', this.userDecrypt, payload, options);
2531
+ const json = await fetchRelayerV1Post('USER_DECRYPT', this.userDecrypt, payload, options);
2471
2532
  assertIsRelayerUserDecryptResult(json.response, 'RelayerUserDecryptResult()');
2472
2533
  return json.response;
2473
2534
  }
2474
2535
  }
2475
2536
 
2476
- function ensureError(e) {
2477
- if (e instanceof Error) {
2478
- return e;
2479
- }
2480
- const message = e.message ?? 'Non-Error value caught in exception handler';
2481
- const name = e.name ?? 'ErrorWrapper';
2482
- const cause = e.cause ?? e;
2483
- const err = new Error(message, { cause });
2484
- err.name = name;
2485
- return err;
2486
- }
2487
-
2488
2537
  class RelayerV2ProviderError extends RelayerErrorBase {
2489
2538
  _operation;
2490
2539
  constructor(params) {
@@ -2961,22 +3010,6 @@ class RelayerV2RequestInternalError extends RelayerV2RequestErrorBase {
2961
3010
  }
2962
3011
  }
2963
3012
 
2964
- function assertIsRelayerV2ResultQueued(value, name) {
2965
- assertRecordStringProperty(value, 'jobId', name);
2966
- }
2967
-
2968
- /*
2969
- type RelayerV2ResponseQueued = {
2970
- status: "queued";
2971
- result: RelayerV2ResultQueued;
2972
- }
2973
- */
2974
- function assertIsRelayerV2ResponseQueued(value, name) {
2975
- assertRecordStringProperty(value, 'status', name, 'queued');
2976
- assertNonNullableRecordProperty(value, 'result', name);
2977
- assertIsRelayerV2ResultQueued(value.result, `${name}.result`);
2978
- }
2979
-
2980
3013
  class RelayerV2ResponseApiError extends RelayerV2ResponseErrorBase {
2981
3014
  constructor(params) {
2982
3015
  super({
@@ -3038,6 +3071,36 @@ class RelayerV2MaxRetryError extends RelayerV2FetchErrorBase {
3038
3071
  }
3039
3072
  }
3040
3073
 
3074
+ function assertIsRelayerV2PostResultQueued(value, name) {
3075
+ assertRecordStringProperty(value, 'jobId', name);
3076
+ }
3077
+
3078
+ /*
3079
+ {
3080
+ status: 'queued';
3081
+ requestId: string;
3082
+ result: {
3083
+ jobId: string;
3084
+ };
3085
+ }
3086
+ */
3087
+ function assertIsRelayerV2PostResponseQueued(value, name) {
3088
+ assertRecordStringProperty(value, 'status', name, 'queued');
3089
+ assertRecordStringProperty(value, 'requestId', name);
3090
+ assertNonNullableRecordProperty(value, 'result', name);
3091
+ assertIsRelayerV2PostResultQueued(value.result, `${name}.result`);
3092
+ }
3093
+ /*
3094
+ {
3095
+ status: 'queued';
3096
+ requestId: string;
3097
+ }
3098
+ */
3099
+ function assertIsRelayerV2GetResponseQueued(value, name) {
3100
+ assertRecordStringProperty(value, 'status', name, 'queued');
3101
+ assertRecordStringProperty(value, 'requestId', name);
3102
+ }
3103
+
3041
3104
  class RelayerV2AsyncRequest {
3042
3105
  _jobId;
3043
3106
  _jobIdTimestamp;
@@ -3282,14 +3345,15 @@ class RelayerV2AsyncRequest {
3282
3345
  // - SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2) at JSON.parse (<anonymous>)
3283
3346
  const bodyJson = await this._getResponseJson(response);
3284
3347
  try {
3285
- assertIsRelayerV2ResponseQueued(bodyJson, 'body');
3348
+ assertIsRelayerV2PostResponseQueued(bodyJson, 'body');
3286
3349
  }
3287
3350
  catch (cause) {
3288
- this._throwInvalidResponseError({
3351
+ this._throwResponseInvalidBodyError({
3289
3352
  fetchMethod: 'POST',
3290
3353
  status: responseStatus,
3291
3354
  cause: cause,
3292
3355
  elapsed,
3356
+ bodyJson: safeJSONstringify(bodyJson),
3293
3357
  });
3294
3358
  }
3295
3359
  let retry_after_sec = this._getRetryAfterHeaderValueInSecs(response);
@@ -3324,11 +3388,12 @@ class RelayerV2AsyncRequest {
3324
3388
  assertIsRelayerV2ResponseFailedWithError400(bodyJson, 'body');
3325
3389
  }
3326
3390
  catch (cause) {
3327
- this._throwInvalidResponseError({
3391
+ this._throwResponseInvalidBodyError({
3328
3392
  fetchMethod: 'POST',
3329
3393
  status: responseStatus,
3330
3394
  cause: cause,
3331
3395
  elapsed,
3396
+ bodyJson: safeJSONstringify(bodyJson),
3332
3397
  });
3333
3398
  }
3334
3399
  this._throwRelayerV2ResponseApiError({
@@ -3348,11 +3413,12 @@ class RelayerV2AsyncRequest {
3348
3413
  assertIsRelayerV2ResponseFailedWithError429(bodyJson, 'body');
3349
3414
  }
3350
3415
  catch (cause) {
3351
- this._throwInvalidResponseError({
3416
+ this._throwResponseInvalidBodyError({
3352
3417
  fetchMethod: 'POST',
3353
3418
  status: responseStatus,
3354
3419
  cause: cause,
3355
3420
  elapsed,
3421
+ bodyJson: safeJSONstringify(bodyJson),
3356
3422
  });
3357
3423
  }
3358
3424
  let retry_after_sec = this._getRetryAfterHeaderValueInSecs(response);
@@ -3383,11 +3449,12 @@ class RelayerV2AsyncRequest {
3383
3449
  assertIsRelayerV2ResponseFailedWithError500(bodyJson, 'body');
3384
3450
  }
3385
3451
  catch (cause) {
3386
- this._throwInvalidResponseError({
3452
+ this._throwResponseInvalidBodyError({
3387
3453
  fetchMethod: 'POST',
3388
3454
  status: responseStatus,
3389
3455
  cause: cause,
3390
3456
  elapsed,
3457
+ bodyJson: safeJSONstringify(bodyJson),
3391
3458
  });
3392
3459
  }
3393
3460
  this._throwRelayerV2ResponseApiError({
@@ -3407,11 +3474,12 @@ class RelayerV2AsyncRequest {
3407
3474
  assertIsRelayerV2ResponseFailedWithError503(bodyJson, 'body');
3408
3475
  }
3409
3476
  catch (cause) {
3410
- this._throwInvalidResponseError({
3477
+ this._throwResponseInvalidBodyError({
3411
3478
  fetchMethod: 'POST',
3412
3479
  status: responseStatus,
3413
3480
  cause: cause,
3414
3481
  elapsed,
3482
+ bodyJson: safeJSONstringify(bodyJson),
3415
3483
  });
3416
3484
  }
3417
3485
  this._throwRelayerV2ResponseApiError({
@@ -3535,6 +3603,7 @@ class RelayerV2AsyncRequest {
3535
3603
  status: responseStatus,
3536
3604
  elapsed,
3537
3605
  cause: cause,
3606
+ bodyJson: safeJSONstringify(bodyJson),
3538
3607
  });
3539
3608
  }
3540
3609
  // RelayerV2ResultPublicDecrypt
@@ -3546,7 +3615,7 @@ class RelayerV2AsyncRequest {
3546
3615
  case 202: {
3547
3616
  const bodyJson = await this._getResponseJson(response);
3548
3617
  try {
3549
- assertIsRelayerV2ResponseQueued(bodyJson, 'body');
3618
+ assertIsRelayerV2GetResponseQueued(bodyJson, 'body');
3550
3619
  }
3551
3620
  catch (cause) {
3552
3621
  this._throwResponseInvalidBodyError({
@@ -3554,6 +3623,7 @@ class RelayerV2AsyncRequest {
3554
3623
  status: responseStatus,
3555
3624
  elapsed,
3556
3625
  cause: cause,
3626
+ bodyJson: safeJSONstringify(bodyJson),
3557
3627
  });
3558
3628
  }
3559
3629
  let retry_after_sec = this._getRetryAfterHeaderValueInSecs(response);
@@ -3589,6 +3659,7 @@ class RelayerV2AsyncRequest {
3589
3659
  status: responseStatus,
3590
3660
  elapsed,
3591
3661
  cause: cause,
3662
+ bodyJson: safeJSONstringify(bodyJson),
3592
3663
  });
3593
3664
  }
3594
3665
  this._throwRelayerV2ResponseApiError({
@@ -3611,6 +3682,7 @@ class RelayerV2AsyncRequest {
3611
3682
  status: responseStatus,
3612
3683
  elapsed,
3613
3684
  cause: cause,
3685
+ bodyJson: safeJSONstringify(bodyJson),
3614
3686
  });
3615
3687
  }
3616
3688
  this._throwRelayerV2ResponseApiError({
@@ -3635,6 +3707,7 @@ class RelayerV2AsyncRequest {
3635
3707
  status: responseStatus,
3636
3708
  elapsed,
3637
3709
  cause: cause,
3710
+ bodyJson: safeJSONstringify(bodyJson),
3638
3711
  });
3639
3712
  }
3640
3713
  this._throwRelayerV2ResponseApiError({
@@ -3659,6 +3732,7 @@ class RelayerV2AsyncRequest {
3659
3732
  status: responseStatus,
3660
3733
  elapsed,
3661
3734
  cause: cause,
3735
+ bodyJson: safeJSONstringify(bodyJson),
3662
3736
  });
3663
3737
  }
3664
3738
  this._throwRelayerV2ResponseApiError({
@@ -3683,6 +3757,7 @@ class RelayerV2AsyncRequest {
3683
3757
  status: responseStatus,
3684
3758
  elapsed,
3685
3759
  cause: cause,
3760
+ bodyJson: safeJSONstringify(bodyJson),
3686
3761
  });
3687
3762
  }
3688
3763
  this._throwRelayerV2ResponseApiError({
@@ -3783,6 +3858,8 @@ class RelayerV2AsyncRequest {
3783
3858
  method: 'POST',
3784
3859
  headers: {
3785
3860
  'Content-Type': 'application/json',
3861
+ 'ZAMA-SDK-VERSION': `${version}`,
3862
+ 'ZAMA-SDK-NAME': `${sdkName}`,
3786
3863
  },
3787
3864
  body: JSON.stringify(this._payload),
3788
3865
  ...(this._internalAbortSignal
@@ -3832,9 +3909,16 @@ class RelayerV2AsyncRequest {
3832
3909
  this._assert(!this._state.terminated, '!this._state.terminated');
3833
3910
  this._assert(!this._state.fetching, '!this._state.fetching');
3834
3911
  this._trace('_fetchGet', `jobId=${this.jobId}`);
3835
- const init = this._internalAbortSignal
3836
- ? { signal: this._internalAbortSignal }
3837
- : undefined;
3912
+ const init = {
3913
+ method: 'GET',
3914
+ headers: {
3915
+ 'ZAMA-SDK-VERSION': `${version}`,
3916
+ 'ZAMA-SDK-NAME': `${sdkName}`,
3917
+ },
3918
+ ...(this._internalAbortSignal
3919
+ ? { signal: this._internalAbortSignal }
3920
+ : {}),
3921
+ };
3838
3922
  this._state.fetching = true;
3839
3923
  let response;
3840
3924
  try {
@@ -4087,20 +4171,11 @@ class RelayerV2AsyncRequest {
4087
4171
  elapsed,
4088
4172
  });
4089
4173
  }
4090
- _throwInvalidResponseError(params) {
4091
- throw new RelayerV2ResponseInvalidBodyError({
4092
- ...params,
4093
- url: this._url,
4094
- operation: this._relayerOperation,
4095
- state: { ...this._state },
4096
- retryCount: this._retryCount,
4097
- });
4098
- }
4099
4174
  _throwResponseInvalidBodyError(params) {
4100
4175
  throw new RelayerV2ResponseInvalidBodyError({
4101
4176
  ...params,
4102
4177
  url: this._url,
4103
- jobId: this.jobId,
4178
+ jobId: this._jobId,
4104
4179
  operation: this._relayerOperation,
4105
4180
  state: { ...this._state },
4106
4181
  retryCount: this._retryCount,
@@ -4171,7 +4246,7 @@ function assertIsRelayerV2KeyData(value, name) {
4171
4246
  assertRecordStringProperty(value, 'dataId', name);
4172
4247
  assertRecordStringArrayProperty(value, 'urls', name);
4173
4248
  }
4174
- function toRelayerKeyUrlResponse(response) {
4249
+ function toRelayerV1KeyUrlResponse(response) {
4175
4250
  const fheKeyInfoV1 = response.response.fheKeyInfo.map((v2Info) => ({
4176
4251
  fhe_public_key: {
4177
4252
  data_id: v2Info.fhePublicKey.dataId,
@@ -4201,7 +4276,7 @@ class RelayerV2Provider extends AbstractRelayerProvider {
4201
4276
  return 2;
4202
4277
  }
4203
4278
  async fetchGetKeyUrlV2() {
4204
- const response = await fetchRelayerGet('KEY_URL', this.keyUrl);
4279
+ const response = await fetchRelayerV1Get('KEY_URL', this.keyUrl);
4205
4280
  // Relayer error
4206
4281
  try {
4207
4282
  assertIsRelayerV2GetResponseKeyUrl(response, 'fetchGetKeyUrl()');
@@ -4215,7 +4290,7 @@ class RelayerV2Provider extends AbstractRelayerProvider {
4215
4290
  }
4216
4291
  async fetchGetKeyUrl() {
4217
4292
  const response = await this.fetchGetKeyUrlV2();
4218
- return toRelayerKeyUrlResponse(response);
4293
+ return toRelayerV1KeyUrlResponse(response);
4219
4294
  }
4220
4295
  async fetchPostInputProof(payload, instanceOptions, fetchOptions) {
4221
4296
  const request = new RelayerV2AsyncRequest({
@@ -4905,60 +4980,39 @@ function _resolveRelayerUrl(value, defaultVersion) {
4905
4980
  };
4906
4981
  }
4907
4982
 
4908
- /**
4909
- * **FHE Type Mapping for Input Builders**
4910
- * * Maps the **number of encrypted bits** used by a FHEVM primary type
4911
- * to its corresponding **FheTypeId**. This constant is primarily used by
4912
- * `EncryptedInput` and `RelayerEncryptedInput` builders to determine the correct
4913
- * input type and calculate the total required bit-length.
4914
- *
4915
- * **Structure: \{ Encrypted Bit Length: FheTypeId \}**
4916
- *
4917
- * | Bits | FheTypeId | FHE Type Name | Note |
4918
- * | :--- | :-------- | :------------ | :--- |
4919
- * | 2 | 0 | `ebool` | The boolean type. |
4920
- * | (N/A)| 1 | `euint4` | **Deprecated** and omitted from this map. |
4921
- * | 8 | 2 | `euint8` | |
4922
- * | 16 | 3 | `euint16` | |
4923
- * | 32 | 4 | `euint32` | |
4924
- * | 64 | 5 | `euint64` | |
4925
- * | 128 | 6 | `euint128` | |
4926
- * | 160 | 7 | `eaddress` | Used for encrypted Ethereum addresses. |
4927
- * | 256 | 8 | `euint256` | The maximum supported integer size. |
4928
- */
4929
- const ENCRYPTION_TYPES = {
4930
- 2: 0, // ebool (FheTypeId=0) is using 2 encrypted bits
4931
- // euint4 (FheTypeId=1) is deprecated
4932
- 8: 2, // euint8 (FheTypeId=2) is using 8 encrypted bits
4933
- 16: 3, // euint16 (FheTypeId=3) is using 16 encrypted bits
4934
- 32: 4, // euint32 (FheTypeId=4) is using 32 encrypted bits
4935
- 64: 5, // euint64 (FheTypeId=5) is using 64 encrypted bits
4936
- 128: 6, // euint128 (FheTypeId=128) is using 128 encrypted bits
4937
- 160: 7, // eaddress (FheTypeId=7) is using 160 encrypted bits
4938
- 256: 8, // euint256 (FheTypeId=8) is using 256 encrypted bits
4983
+ ////////////////////////////////////////////////////////////////////////////////
4984
+ // MainnetConfig
4985
+ ////////////////////////////////////////////////////////////////////////////////
4986
+ const MainnetConfig = {
4987
+ aclContractAddress: '0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6',
4988
+ kmsContractAddress: '0x77627828a55156b04Ac0DC0eb30467f1a552BB03',
4989
+ inputVerifierContractAddress: '0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2',
4990
+ verifyingContractAddressDecryption: '0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24',
4991
+ verifyingContractAddressInputVerification: '0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287',
4992
+ chainId: 1,
4993
+ gatewayChainId: 261131,
4994
+ network: 'https://ethereum-rpc.publicnode.com',
4995
+ relayerUrl: 'https://relayer.mainnet.zama.org',
4939
4996
  };
4940
-
4997
+ Object.freeze(MainnetConfig);
4998
+ ////////////////////////////////////////////////////////////////////////////////
4999
+ // SepoliaConfig
5000
+ ////////////////////////////////////////////////////////////////////////////////
4941
5001
  const SepoliaConfig = {
4942
- // ACL_CONTRACT_ADDRESS (FHEVM Host chain)
4943
5002
  aclContractAddress: '0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D',
4944
- // KMS_VERIFIER_CONTRACT_ADDRESS (FHEVM Host chain)
4945
5003
  kmsContractAddress: '0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A',
4946
- // INPUT_VERIFIER_CONTRACT_ADDRESS (FHEVM Host chain)
4947
5004
  inputVerifierContractAddress: '0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0',
4948
- // DECRYPTION_ADDRESS (Gateway chain)
4949
5005
  verifyingContractAddressDecryption: '0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478',
4950
- // INPUT_VERIFICATION_ADDRESS (Gateway chain)
4951
5006
  verifyingContractAddressInputVerification: '0x483b9dE06E4E4C7D35CCf5837A1668487406D955',
4952
- // FHEVM Host chain id
4953
5007
  chainId: 11155111,
4954
- // Gateway chain id
4955
5008
  gatewayChainId: 10901,
4956
- // Optional RPC provider to host chain
4957
5009
  network: 'https://ethereum-sepolia-rpc.publicnode.com',
4958
- // Relayer URL
4959
5010
  relayerUrl: 'https://relayer.testnet.zama.org',
4960
5011
  };
4961
5012
  Object.freeze(SepoliaConfig);
5013
+ ////////////////////////////////////////////////////////////////////////////////
5014
+ // createInstance
5015
+ ////////////////////////////////////////////////////////////////////////////////
4962
5016
  const createInstance = async (config) => {
4963
5017
  const { verifyingContractAddressDecryption, verifyingContractAddressInputVerification, publicKey, inputVerifierContractAddress, kmsContractAddress, aclContractAddress, gatewayChainId, auth, } = config;
4964
5018
  if (!isChecksummedAddress(aclContractAddress)) {
@@ -4990,29 +5044,12 @@ const createInstance = async (config) => {
4990
5044
  defaultRelayerVersion: 1,
4991
5045
  });
4992
5046
  const chainId = await getChainId(provider, config);
4993
- // const relayerVersionUrl = `${config.relayerUrl!}/v1`;
4994
- // const publicKeyData = await getTfheCompactPublicKey({
4995
- // relayerVersionUrl: relayerFhevm.relayerVersionUrl,
4996
- // publicKey: config.publicKey,
4997
- // });
4998
- //const aaa = relayerFhevm.getPublicKey();
4999
- // const publicParamsData = await getPublicParams({
5000
- // relayerVersionUrl,
5001
- // publicParams: config.publicParams,
5002
- // });
5003
5047
  const kmsSigners = await getKMSSigners(provider, kmsContractAddress);
5004
5048
  const thresholdKMSSigners = await getKMSSignersThreshold(provider, kmsContractAddress);
5005
5049
  const coprocessorSigners = await getCoprocessorSigners(provider, inputVerifierContractAddress);
5006
5050
  const thresholdCoprocessorSigners = await getCoprocessorSignersThreshold(provider, inputVerifierContractAddress);
5007
5051
  return {
5008
- createEncryptedInput: createRelayerEncryptedInput(aclContractAddress, verifyingContractAddressInputVerification, chainId, gatewayChainId,
5009
- //cleanURL(config.relayerUrl),
5010
- //relayerFhevm.relayerVersionUrl,
5011
- relayerFhevm.relayerProvider,
5012
- //publicKeyData.publicKey,
5013
- relayerFhevm.getPublicKeyWasm().publicKey,
5014
- //publicParamsData,
5015
- { 2048: relayerFhevm.getPublicParamsWasm(2048) }, coprocessorSigners, thresholdCoprocessorSigners),
5052
+ createEncryptedInput: createRelayerEncryptedInput(aclContractAddress, verifyingContractAddressInputVerification, chainId, gatewayChainId, relayerFhevm.relayerProvider, relayerFhevm.getPublicKeyWasm().publicKey, { 2048: relayerFhevm.getPublicParamsWasm(2048) }, coprocessorSigners, thresholdCoprocessorSigners, auth && { auth }),
5016
5053
  generateKeypair,
5017
5054
  createEIP712: createEIP712(verifyingContractAddressDecryption, chainId),
5018
5055
  publicDecrypt: publicDecryptRequest(kmsSigners, thresholdKMSSigners, gatewayChainId, verifyingContractAddressDecryption, aclContractAddress,
@@ -5066,7 +5103,7 @@ const createTfhePublicKey = () => {
5066
5103
  global.TFHE = TFHEPkg__namespace;
5067
5104
  global.TKMS = TKMSPkg__namespace;
5068
5105
 
5069
- exports.ENCRYPTION_TYPES = ENCRYPTION_TYPES;
5106
+ exports.MainnetConfig = MainnetConfig;
5070
5107
  exports.SepoliaConfig = SepoliaConfig;
5071
5108
  exports.createEIP712 = createEIP712;
5072
5109
  exports.createInstance = createInstance;