@fhevm/sdk 0.14.4-0 → 0.14.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/_cjs/core/_version.js +1 -1
  2. package/_cjs/core/_version.js.map +1 -1
  3. package/_cjs/core/chains/definitions/bscTestnet.js +36 -0
  4. package/_cjs/core/chains/definitions/bscTestnet.js.map +1 -0
  5. package/_cjs/core/chains/index.js +3 -1
  6. package/_cjs/core/chains/index.js.map +1 -1
  7. package/_cjs/core/modules/relayer/cleartext/fetchDelegatedUserDecryptV1.js +40 -47
  8. package/_cjs/core/modules/relayer/cleartext/fetchDelegatedUserDecryptV1.js.map +1 -1
  9. package/_cjs/core/modules/relayer/cleartext/fetchPublicDecrypt.js +13 -7
  10. package/_cjs/core/modules/relayer/cleartext/fetchPublicDecrypt.js.map +1 -1
  11. package/_cjs/core/modules/relayer/cleartext/fetchUserDecryptV1.js +38 -45
  12. package/_cjs/core/modules/relayer/cleartext/fetchUserDecryptV1.js.map +1 -1
  13. package/_cjs/core/modules/relayer/cleartext/fetchUserDecryptV2.js +104 -2
  14. package/_cjs/core/modules/relayer/cleartext/fetchUserDecryptV2.js.map +1 -1
  15. package/_cjs/core/modules/relayer/cleartext/signers.js +35 -0
  16. package/_cjs/core/modules/relayer/cleartext/signers.js.map +1 -1
  17. package/_cjs/core/modules/relayer/module/RelayerAsyncRequest.js +12 -2
  18. package/_cjs/core/modules/relayer/module/RelayerAsyncRequest.js.map +1 -1
  19. package/_cjs/core/modules/relayer/module/fetchFheEncryptionKeySource.js +5 -3
  20. package/_cjs/core/modules/relayer/module/fetchFheEncryptionKeySource.js.map +1 -1
  21. package/_cjs/core/modules/relayer/module/relayerUrl.js +37 -0
  22. package/_cjs/core/modules/relayer/module/relayerUrl.js.map +1 -1
  23. package/_cjs/wasm/tfhe/loadTfheLib.js.map +1 -1
  24. package/_cjs/wasm/tkms/loadKmsLib.js.map +1 -1
  25. package/_esm/core/_version.js +1 -1
  26. package/_esm/core/_version.js.map +1 -1
  27. package/_esm/core/chains/definitions/bscTestnet.js +33 -0
  28. package/_esm/core/chains/definitions/bscTestnet.js.map +1 -0
  29. package/_esm/core/chains/index.js +1 -0
  30. package/_esm/core/chains/index.js.map +1 -1
  31. package/_esm/core/modules/relayer/cleartext/fetchDelegatedUserDecryptV1.js +43 -51
  32. package/_esm/core/modules/relayer/cleartext/fetchDelegatedUserDecryptV1.js.map +1 -1
  33. package/_esm/core/modules/relayer/cleartext/fetchPublicDecrypt.js +15 -9
  34. package/_esm/core/modules/relayer/cleartext/fetchPublicDecrypt.js.map +1 -1
  35. package/_esm/core/modules/relayer/cleartext/fetchUserDecryptV1.js +42 -49
  36. package/_esm/core/modules/relayer/cleartext/fetchUserDecryptV1.js.map +1 -1
  37. package/_esm/core/modules/relayer/cleartext/fetchUserDecryptV2.js +111 -3
  38. package/_esm/core/modules/relayer/cleartext/fetchUserDecryptV2.js.map +1 -1
  39. package/_esm/core/modules/relayer/cleartext/signers.js +41 -0
  40. package/_esm/core/modules/relayer/cleartext/signers.js.map +1 -1
  41. package/_esm/core/modules/relayer/module/RelayerAsyncRequest.js +14 -2
  42. package/_esm/core/modules/relayer/module/RelayerAsyncRequest.js.map +1 -1
  43. package/_esm/core/modules/relayer/module/fetchFheEncryptionKeySource.js +7 -4
  44. package/_esm/core/modules/relayer/module/fetchFheEncryptionKeySource.js.map +1 -1
  45. package/_esm/core/modules/relayer/module/relayerUrl.js +48 -1
  46. package/_esm/core/modules/relayer/module/relayerUrl.js.map +1 -1
  47. package/_types/core/_version.d.ts.map +1 -1
  48. package/_types/core/chains/definitions/bscTestnet.d.ts +3 -0
  49. package/_types/core/chains/definitions/bscTestnet.d.ts.map +1 -0
  50. package/_types/core/chains/index.d.ts +1 -0
  51. package/_types/core/chains/index.d.ts.map +1 -1
  52. package/_types/core/modules/relayer/cleartext/fetchDelegatedUserDecryptV1.d.ts.map +1 -1
  53. package/_types/core/modules/relayer/cleartext/fetchPublicDecrypt.d.ts.map +1 -1
  54. package/_types/core/modules/relayer/cleartext/fetchUserDecryptV1.d.ts.map +1 -1
  55. package/_types/core/modules/relayer/cleartext/fetchUserDecryptV2.d.ts +1 -1
  56. package/_types/core/modules/relayer/cleartext/fetchUserDecryptV2.d.ts.map +1 -1
  57. package/_types/core/modules/relayer/cleartext/signers.d.ts +13 -0
  58. package/_types/core/modules/relayer/cleartext/signers.d.ts.map +1 -1
  59. package/_types/core/modules/relayer/module/RelayerAsyncRequest.d.ts +1 -0
  60. package/_types/core/modules/relayer/module/RelayerAsyncRequest.d.ts.map +1 -1
  61. package/_types/core/modules/relayer/module/fetchFheEncryptionKeySource.d.ts.map +1 -1
  62. package/_types/core/modules/relayer/module/relayerUrl.d.ts +12 -1
  63. package/_types/core/modules/relayer/module/relayerUrl.d.ts.map +1 -1
  64. package/_types/core/types/relayer.d.ts +6 -0
  65. package/_types/core/types/relayer.d.ts.map +1 -1
  66. package/core/_version.ts +1 -1
  67. package/core/chains/definitions/bscTestnet.ts +34 -0
  68. package/core/chains/index.ts +1 -0
  69. package/core/modules/relayer/cleartext/fetchDelegatedUserDecryptV1.ts +49 -60
  70. package/core/modules/relayer/cleartext/fetchPublicDecrypt.ts +19 -9
  71. package/core/modules/relayer/cleartext/fetchUserDecryptV1.ts +48 -58
  72. package/core/modules/relayer/cleartext/fetchUserDecryptV2.ts +133 -4
  73. package/core/modules/relayer/cleartext/signers.ts +61 -0
  74. package/core/modules/relayer/module/RelayerAsyncRequest.ts +11 -2
  75. package/core/modules/relayer/module/fetchFheEncryptionKeySource.ts +12 -4
  76. package/core/modules/relayer/module/relayerUrl.ts +52 -1
  77. package/core/types/relayer.ts +6 -0
  78. package/package.json +1 -1
@@ -1,11 +1,140 @@
1
+ import type { BytesHex, ChecksummedAddress, Uint32BigInt } from '../../../types/primitives.js';
1
2
  import type { FetchUserDecryptParametersV2, FetchUserDecryptReturnType, RelayerClientWithRuntime } from '../types.js';
3
+ import { asUint32BigInt, tryParseUintBigIntString } from '../../../base/uint.js';
4
+ import { getTrustedClient } from '../../../runtime/CoreFhevm-p.js';
5
+ import { signKmsSigncryptedShares } from './signers.js';
6
+
7
+ ////////////////////////////////////////////////////////////////////////////////
8
+ // runUserDecryptV2OnChain
9
+ ////////////////////////////////////////////////////////////////////////////////
10
+
11
+ const userDecryptV2Abi = [
12
+ {
13
+ type: 'function',
14
+ name: 'userDecryptV2',
15
+ inputs: [
16
+ {
17
+ name: 'handles',
18
+ type: 'tuple[]',
19
+ internalType: 'struct HandleEntry[]',
20
+ components: [
21
+ { name: 'handle', type: 'bytes32', internalType: 'bytes32' },
22
+ {
23
+ name: 'contractAddress',
24
+ type: 'address',
25
+ internalType: 'address',
26
+ },
27
+ {
28
+ name: 'ownerAddress',
29
+ type: 'address',
30
+ internalType: 'address',
31
+ },
32
+ ],
33
+ },
34
+ {
35
+ name: 'permit',
36
+ type: 'tuple',
37
+ internalType: 'struct UserDecryptPermitV2',
38
+ components: [
39
+ { name: 'userAddress', type: 'address', internalType: 'address' },
40
+ { name: 'publicKey', type: 'bytes', internalType: 'bytes' },
41
+ {
42
+ name: 'allowedContracts',
43
+ type: 'address[]',
44
+ internalType: 'address[]',
45
+ },
46
+ {
47
+ name: 'startTimestamp',
48
+ type: 'uint256',
49
+ internalType: 'uint256',
50
+ },
51
+ {
52
+ name: 'durationSeconds',
53
+ type: 'uint256',
54
+ internalType: 'uint256',
55
+ },
56
+ { name: 'extraData', type: 'bytes', internalType: 'bytes' },
57
+ ],
58
+ },
59
+ { name: 'signature', type: 'bytes', internalType: 'bytes' },
60
+ ],
61
+ outputs: [
62
+ { name: 'payload', type: 'bytes', internalType: 'bytes' },
63
+ { name: 'signers', type: 'address[]', internalType: 'address[]' },
64
+ { name: 'threshold', type: 'uint256', internalType: 'uint256' },
65
+ { name: 'signedExtraData', type: 'bytes', internalType: 'bytes' },
66
+ ],
67
+ stateMutability: 'view',
68
+ },
69
+ ] as const;
70
+
71
+ async function runUserDecryptV2OnChain(
72
+ relayerClient: RelayerClientWithRuntime,
73
+ payload: FetchUserDecryptParametersV2['payload'],
74
+ ): Promise<{
75
+ readonly commonKmsSigncryptedSharePayload: BytesHex;
76
+ readonly signersAddress: readonly ChecksummedAddress[];
77
+ readonly threshold: Uint32BigInt;
78
+ readonly extraData: BytesHex;
79
+ }> {
80
+ const { kmsDecryptEip712Message, kmsDecryptEip712Signature } = payload;
81
+ const pairs = payload.handleContractPairs;
82
+ const trustedClient = getTrustedClient(relayerClient);
83
+ // The signed permit fields are passed verbatim, extraData included: the host runs the gateway's and the
84
+ // kms-worker's checks against them and returns the signers of the KMS context the extraData names.
85
+ const res = (await relayerClient.runtime.ethereum.readContract(trustedClient, {
86
+ abi: userDecryptV2Abi,
87
+ address: relayerClient.chain.fhevm.contracts.kmsVerifier.address as ChecksummedAddress,
88
+ args: [
89
+ pairs.map((p) => ({
90
+ handle: p.handle.bytes32Hex,
91
+ contractAddress: p.contractAddress,
92
+ ownerAddress: p.ownerAddress,
93
+ })),
94
+ {
95
+ userAddress: kmsDecryptEip712Message.userAddress,
96
+ publicKey: kmsDecryptEip712Message.publicKey,
97
+ allowedContracts: kmsDecryptEip712Message.allowedContracts,
98
+ startTimestamp: _parseUintBigIntString(
99
+ 'kmsDecryptEip712Message.startTimestamp',
100
+ kmsDecryptEip712Message.startTimestamp,
101
+ ),
102
+ durationSeconds: _parseUintBigIntString(
103
+ 'kmsDecryptEip712Message.durationSeconds',
104
+ kmsDecryptEip712Message.durationSeconds,
105
+ ),
106
+ extraData: kmsDecryptEip712Message.extraData,
107
+ },
108
+ kmsDecryptEip712Signature,
109
+ ],
110
+ functionName: userDecryptV2Abi[0].name,
111
+ })) as unknown[];
112
+
113
+ return {
114
+ commonKmsSigncryptedSharePayload: res[0] as BytesHex,
115
+ signersAddress: res[1] as readonly ChecksummedAddress[],
116
+ threshold: asUint32BigInt(res[2]),
117
+ extraData: res[3] as BytesHex,
118
+ };
119
+ }
2
120
 
3
121
  ////////////////////////////////////////////////////////////////////////////////
4
122
 
5
- // eslint-disable-next-line @typescript-eslint/require-await
6
123
  export async function fetchUserDecryptV2(
7
- _relayerClient: RelayerClientWithRuntime,
8
- _parameters: FetchUserDecryptParametersV2,
124
+ relayerClient: RelayerClientWithRuntime,
125
+ parameters: FetchUserDecryptParametersV2,
9
126
  ): Promise<FetchUserDecryptReturnType> {
10
- throw new Error('Not yet implemented');
127
+ // On chain only: forge-fhevm v1 has no unified (V2) decryption permit path.
128
+ const res = await runUserDecryptV2OnChain(relayerClient, parameters.payload);
129
+ return signKmsSigncryptedShares(relayerClient, { ...res, threshold: Number(res.threshold) });
130
+ }
131
+
132
+ ////////////////////////////////////////////////////////////////////////////////
133
+
134
+ function _parseUintBigIntString(label: string, value: string): bigint {
135
+ const bn = tryParseUintBigIntString(value);
136
+ if (bn === undefined) {
137
+ throw new Error(`${label} is not a valid uint string, got ${JSON.stringify(value)}`);
138
+ }
139
+ return bn;
11
140
  }
@@ -1,6 +1,11 @@
1
1
  import type { BytesHex, ChecksummedAddress } from '../../../types/primitives.js';
2
+ import type { KmsSigncryptedShare } from '../../../types/kms-p.js';
3
+ import type { FetchUserDecryptResultItem } from '../../../types/relayer.js';
2
4
  import type { CleartextEthereumModule } from '../../ethereum/types-ct.js';
3
5
  import type { RelayerClientWithRuntime } from '../types.js';
6
+ import { remove0x } from '../../../base/string.js';
7
+ import { randomUniqueUints } from '../../../base/uint.js';
8
+ import { userDecryptResultToKmsSigncryptedShares } from '../utils.js';
4
9
 
5
10
  ////////////////////////////////////////////////////////////////////////////////
6
11
 
@@ -70,6 +75,62 @@ export function getKmsSignersPrivateKeyMap(relayerClient: RelayerClientWithRunti
70
75
 
71
76
  ////////////////////////////////////////////////////////////////////////////////
72
77
 
78
+ /**
79
+ * The KMS nodes that answer a request, as a relayer forwards one response per node: a random subset of
80
+ * `signersAddress`, of random size between `threshold` and all of them.
81
+ */
82
+ export function pickRespondingKmsSigners(
83
+ signersAddress: readonly ChecksummedAddress[],
84
+ threshold: number,
85
+ ): ChecksummedAddress[] {
86
+ const n = signersAddress.length;
87
+ if (!Number.isInteger(threshold) || threshold < 1 || threshold > n) {
88
+ throw new Error(`Invalid KMS threshold ${threshold} for ${n} signers`);
89
+ }
90
+ let count = threshold + Math.floor(Math.random() * (n - threshold + 1));
91
+ // Defensive: the guard above already keeps count within [threshold, n].
92
+ if (count < 1) {
93
+ count = 1;
94
+ }
95
+ if (count > n) {
96
+ count = n;
97
+ }
98
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
99
+ return randomUniqueUints(n, count).map((i) => signersAddress[i]!);
100
+ }
101
+
102
+ /** One signcrypted share per responding KMS node, each signing the common payload. */
103
+ export async function signKmsSigncryptedShares(
104
+ relayerClient: RelayerClientWithRuntime,
105
+ parameters: {
106
+ readonly commonKmsSigncryptedSharePayload: BytesHex;
107
+ readonly extraData: BytesHex;
108
+ readonly signersAddress: readonly ChecksummedAddress[];
109
+ readonly threshold: number;
110
+ },
111
+ ): Promise<readonly KmsSigncryptedShare[]> {
112
+ const cleartextEthereumModule = relayerClient.runtime.ethereum as CleartextEthereumModule;
113
+ const { commonKmsSigncryptedSharePayload: payload, extraData, signersAddress, threshold } = parameters;
114
+ const privateKeys = getKmsSignersPrivateKeyMap(relayerClient);
115
+ const responders = pickRespondingKmsSigners(signersAddress, threshold);
116
+
117
+ const result: FetchUserDecryptResultItem[] = [];
118
+ for (const signerAddress of responders) {
119
+ const privateKey = privateKeys.get(signerAddress);
120
+ if (privateKey === undefined) {
121
+ throw new Error(
122
+ `Unable to find KMS signer for address ${signerAddress} (${responders.length} of ${signersAddress.length} responding)`,
123
+ );
124
+ }
125
+ const signature = await cleartextEthereumModule.sign({ hash: payload, privateKey });
126
+ result.push({ signature: remove0x(signature), payload: remove0x(payload), extraData });
127
+ }
128
+
129
+ return userDecryptResultToKmsSigncryptedShares(result);
130
+ }
131
+
132
+ ////////////////////////////////////////////////////////////////////////////////
133
+
73
134
  function _fillSignersPrivateKey(
74
135
  relayerClient: RelayerClientWithRuntime,
75
136
  hdPathSuffix: string,
@@ -67,6 +67,7 @@ import {
67
67
  } from './guards/RelayerResponseQueued.js';
68
68
  import { assertIsRelayerUserDecryptSucceeded } from './guards/RelayerUserDecryptSucceeded.js';
69
69
  import { readErrorMessage } from './readErrorMessage.js';
70
+ import { appendRelayerQuery, normalizeRelayerQuery } from './relayerUrl.js';
70
71
 
71
72
  /*
72
73
  Actions:
@@ -144,6 +145,7 @@ export class RelayerAsyncRequest {
144
145
  private readonly _payload: Record<string, unknown>;
145
146
  private readonly _fhevmAuth: Auth | undefined;
146
147
  private readonly _customHeaders: Record<string, string> | undefined;
148
+ private readonly _query: Readonly<Record<string, string>> | undefined;
147
149
  private _retryAfterTimeoutPromiseFuncReject?: ((reason?: unknown) => void) | undefined;
148
150
  private readonly _onProgress?:
149
151
  | ((
@@ -213,6 +215,7 @@ export class RelayerAsyncRequest {
213
215
  this._logger = params.logger;
214
216
  this._fhevmAuth = params.options?.auth;
215
217
  this._customHeaders = normalizeHeaders(params.options?.headers);
218
+ this._query = normalizeRelayerQuery(params.options?.query);
216
219
  this._onProgress = params.options?.onProgress as typeof this._onProgress;
217
220
  this._state = {
218
221
  aborted: false,
@@ -1255,11 +1258,14 @@ export class RelayerAsyncRequest {
1255
1258
  this._fhevmAuth, // -> the API key
1256
1259
  );
1257
1260
 
1261
+ // Build the URL outside the `try`, so an internal error is not reported as a fetch failure.
1262
+ const fetchUrl = appendRelayerQuery(this._url, this._query);
1263
+
1258
1264
  this._state.fetching = true;
1259
1265
 
1260
1266
  let response;
1261
1267
  try {
1262
- response = await fetch(this._url, init);
1268
+ response = await fetch(fetchUrl, init);
1263
1269
  } catch (cause) {
1264
1270
  this._state.fetching = false;
1265
1271
 
@@ -1326,11 +1332,14 @@ export class RelayerAsyncRequest {
1326
1332
  this._fhevmAuth,
1327
1333
  );
1328
1334
 
1335
+ // Build the URL outside the `try`, so an internal error is not reported as a fetch failure.
1336
+ const fetchUrl = appendRelayerQuery(`${this._url}/${this.jobId}`, this._query);
1337
+
1329
1338
  this._state.fetching = true;
1330
1339
 
1331
1340
  let response;
1332
1341
  try {
1333
- response = await fetch(`${this._url}/${this.jobId}`, init);
1342
+ response = await fetch(fetchUrl, init);
1334
1343
  } catch (cause) {
1335
1344
  this._state.fetching = false;
1336
1345
  // Warning: `terminated` can be `true` here!
@@ -10,7 +10,12 @@ import { assertRecordArrayProperty, assertRecordNonNullableProperty } from '../.
10
10
  import { fetchWithRetry, normalizeHeaders } from '../../../base/fetch.js';
11
11
  import { sdkName, version } from '../../../_version.js';
12
12
  import { assertRecordStringArrayProperty, assertRecordStringProperty } from '../../../base/string.js';
13
- import { buildRelayerUrlString, validateRelayerBaseUrl } from './relayerUrl.js';
13
+ import {
14
+ appendRelayerQuery,
15
+ buildRelayerUrlString,
16
+ normalizeRelayerQuery,
17
+ validateRelayerBaseUrl,
18
+ } from './relayerUrl.js';
14
19
  import { readErrorMessage } from './readErrorMessage.js';
15
20
  import { assert } from '../../../base/errors/InternalError.js';
16
21
 
@@ -25,6 +30,7 @@ export async function fetchFheEncryptionKeySource(
25
30
  const { options } = parameters;
26
31
  const relayerBaseUrl: URL = validateRelayerBaseUrl(relayerClient.relayerUrl, options?.auth !== undefined);
27
32
  const customHeaders = normalizeHeaders(options?.headers);
33
+ const query = normalizeRelayerQuery(options?.query);
28
34
  const init = setAuth(
29
35
  {
30
36
  method: 'GET',
@@ -38,12 +44,14 @@ export async function fetchFheEncryptionKeySource(
38
44
  );
39
45
 
40
46
  assert(relayerBaseUrl.pathname.endsWith('/'));
47
+ // Keep `url` query-less so errors and logs show the endpoint, not per-request metadata.
41
48
  const url = buildRelayerUrlString(relayerBaseUrl, 'v2/keyurl');
49
+ const fetchUrl = appendRelayerQuery(url, query);
42
50
 
43
51
  let response;
44
52
  try {
45
53
  response = await fetchWithRetry({
46
- url,
54
+ url: fetchUrl,
47
55
  init,
48
56
  retries: options?.fetchRetries,
49
57
  retryDelayMs: options?.fetchRetryDelayInMilliseconds,
@@ -68,8 +76,8 @@ export async function fetchFheEncryptionKeySource(
68
76
  url,
69
77
  message:
70
78
  message !== undefined
71
- ? `HTTP error! status: ${response.status} on ${response.url}: ${message}`
72
- : `HTTP error! status: ${response.status} on ${response.url}`,
79
+ ? `HTTP error! status: ${response.status} on ${url}: ${message}`
80
+ : `HTTP error! status: ${response.status} on ${url}`,
73
81
  });
74
82
  }
75
83
 
@@ -10,7 +10,6 @@ import { removePrefix, removeSuffix } from '../../../base/string.js';
10
10
  * - parses as a URL
11
11
  * - protocol is `http:` or `https:`
12
12
  * - contains no userinfo (`user:pass@host`)
13
- * - contains no query string or fragment (they would corrupt path concatenation)
14
13
  * - if `hasAuth` is true, requires `https:` unless the host is localhost
15
14
  *
16
15
  * Normalization (via WHATWG `URL`):
@@ -18,6 +17,7 @@ import { removePrefix, removeSuffix } from '../../../base/string.js';
18
17
  * - default ports collapsed (`:443` for https, `:80` for http)
19
18
  * - path percent-encoded canonically
20
19
  * - bare-origin URLs get a single trailing `/` (`https://x` → `https://x/`)
20
+ * - query string and fragment dropped, with a warning (use `options.query` instead)
21
21
  *
22
22
  * Throws {@link InvalidUrlError} on any failure so the caller surfaces a
23
23
  * uniform error type.
@@ -50,6 +50,17 @@ export function validateRelayerBaseUrl(relayerUrl: unknown, hasAuth: boolean): U
50
50
  );
51
51
  }
52
52
 
53
+ // Patch releases keep the old behavior: drop the query and fragment instead of throwing.
54
+ // The warning leaves out the value, which may hold a secret (`?apikey=...`).
55
+ // Check `href`, not `search` / `hash`, which are '' for a bare trailing `?` or `#`.
56
+ if (parsed.href.includes('?') || parsed.href.includes('#')) {
57
+ console.warn(
58
+ 'relayerUrl contains a query string or fragment, which is ignored. Use options.query to add query parameters.',
59
+ );
60
+ parsed.search = '';
61
+ parsed.hash = '';
62
+ }
63
+
53
64
  if (hasAuth && parsed.protocol === 'http:') {
54
65
  const isLocalhost =
55
66
  parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]';
@@ -75,3 +86,43 @@ export function buildRelayerUrlString(relayerBaseUrl: URL, path: string): string
75
86
  const url = new URL(sanitizedPath, relayerBaseUrl).toString();
76
87
  return removeSuffix(url, '/');
77
88
  }
89
+
90
+ /**
91
+ * Validates `options.query` once at intake and returns a detached copy of its string entries.
92
+ *
93
+ * @throws If a key or value cannot be percent-encoded, so a bad query fails here and not as a generic fetch error.
94
+ */
95
+ export function normalizeRelayerQuery(query: unknown): Readonly<Record<string, string>> | undefined {
96
+ if (query === null || typeof query !== 'object' || Array.isArray(query)) {
97
+ return undefined;
98
+ }
99
+ const result: Record<string, string> = {};
100
+ for (const [key, value] of Object.entries(query)) {
101
+ if (typeof value !== 'string') {
102
+ continue;
103
+ }
104
+ try {
105
+ encodeURIComponent(key);
106
+ encodeURIComponent(value);
107
+ } catch (cause) {
108
+ throw new Error(`normalizeRelayerQuery: query parameter '${key}' cannot be percent-encoded`, { cause });
109
+ }
110
+ result[key] = value;
111
+ }
112
+ return result;
113
+ }
114
+
115
+ /**
116
+ * Use the result only as the URL passed to `fetch()`. Keep the query-less `url`
117
+ * for errors, logs and callbacks, so they show the endpoint, not per-request metadata.
118
+ */
119
+ export function appendRelayerQuery(url: string, query: Readonly<Record<string, string>> | undefined): string {
120
+ const search = Object.entries(query ?? {})
121
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
122
+ .join('&');
123
+ if (search === '') {
124
+ return url;
125
+ }
126
+ assert(!url.includes('?'));
127
+ return `${url}?${search}`;
128
+ }
@@ -35,6 +35,12 @@ export type FetchDelegatedUserDecryptResult = readonly FetchUserDecryptResultIte
35
35
  export type RelayerCommonOptions = {
36
36
  auth?: Auth | undefined;
37
37
  headers?: Record<string, string>;
38
+ /**
39
+ * Extra query parameters sent with job requests and the key-URL lookup.
40
+ * Used by the Zama SDK to send its metadata (`zama_*`) when a proxy in front
41
+ * of the relayer doesn't forward custom headers. Prefer `headers`.
42
+ */
43
+ query?: Record<string, string> | undefined;
38
44
  debug?: boolean | undefined;
39
45
  fetchRetries?: number | undefined;
40
46
  fetchRetryDelayInMilliseconds?: number | undefined;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fhevm/sdk",
3
3
  "description": "TypeScript Interface for FHEVM",
4
- "version": "0.14.4-0",
4
+ "version": "0.14.5",
5
5
  "type": "module",
6
6
  "main": "./_cjs/index.js",
7
7
  "module": "./_esm/index.js",