@interfold/sdk 0.2.0

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.
@@ -0,0 +1,320 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/contracts/index.ts
21
+ var contracts_exports = {};
22
+ __export(contracts_exports, {
23
+ ContractClient: () => ContractClient,
24
+ E3Stage: () => E3Stage,
25
+ FailureReason: () => FailureReason
26
+ });
27
+ module.exports = __toCommonJS(contracts_exports);
28
+
29
+ // src/contracts/contract-client.ts
30
+ var import_viem2 = require("viem");
31
+ var import_accounts = require("viem/accounts");
32
+ var import_types = require("@interfold/contracts/types");
33
+
34
+ // src/utils.ts
35
+ var import_viem = require("viem");
36
+ var SDKError = class extends Error {
37
+ constructor(message, code) {
38
+ super(message);
39
+ this.code = code;
40
+ this.name = "SDKError";
41
+ }
42
+ };
43
+ function isValidAddress(address) {
44
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
45
+ }
46
+
47
+ // src/contracts/contract-client.ts
48
+ var ContractClient = class _ContractClient {
49
+ publicClient;
50
+ walletClient;
51
+ contracts;
52
+ contractInfo;
53
+ constructor(config) {
54
+ const { publicClient, walletClient, contracts } = config;
55
+ if (!isValidAddress(contracts.interfold)) {
56
+ throw new SDKError("Invalid Interfold contract address", "INVALID_ADDRESS");
57
+ }
58
+ if (!isValidAddress(contracts.ciphernodeRegistry)) {
59
+ throw new SDKError("Invalid CiphernodeRegistry contract address", "INVALID_ADDRESS");
60
+ }
61
+ if (!isValidAddress(contracts.feeToken)) {
62
+ throw new SDKError("Invalid FeeToken contract address", "INVALID_ADDRESS");
63
+ }
64
+ this.publicClient = publicClient;
65
+ this.walletClient = walletClient;
66
+ this.contracts = contracts;
67
+ this.contractInfo = {
68
+ interfold: {
69
+ address: contracts.interfold,
70
+ abi: import_types.Interfold__factory.abi
71
+ },
72
+ ciphernodeRegistry: {
73
+ address: contracts.ciphernodeRegistry,
74
+ abi: import_types.CiphernodeRegistryOwnable__factory.abi
75
+ },
76
+ feeToken: {
77
+ address: contracts.feeToken,
78
+ abi: import_types.InterfoldToken__factory.abi
79
+ }
80
+ };
81
+ }
82
+ static create(options) {
83
+ const isWebSocket = options.rpcUrl.startsWith("ws://") || options.rpcUrl.startsWith("wss://");
84
+ const transport = isWebSocket ? (0, import_viem2.webSocket)(options.rpcUrl, {
85
+ keepAlive: { interval: 3e4 },
86
+ reconnect: { attempts: 5, delay: 2e3 }
87
+ }) : (0, import_viem2.http)(options.rpcUrl);
88
+ const publicClient = (0, import_viem2.createPublicClient)({
89
+ chain: options.chain,
90
+ transport
91
+ });
92
+ let walletClient;
93
+ if (options.privateKey) {
94
+ const account = (0, import_accounts.privateKeyToAccount)(options.privateKey);
95
+ walletClient = (0, import_viem2.createWalletClient)({
96
+ account,
97
+ chain: options.chain,
98
+ transport
99
+ });
100
+ }
101
+ return new _ContractClient({ publicClient, walletClient, contracts: options.contracts });
102
+ }
103
+ getPublicClient() {
104
+ return this.publicClient;
105
+ }
106
+ async approveFeeToken(amount) {
107
+ if (!this.walletClient) {
108
+ throw new SDKError("Wallet client required for write operations", "NO_WALLET");
109
+ }
110
+ try {
111
+ const account = this.walletClient.account;
112
+ if (!account) {
113
+ throw new SDKError("No account connected", "NO_ACCOUNT");
114
+ }
115
+ const { request } = await this.publicClient.simulateContract({
116
+ address: this.contracts.feeToken,
117
+ abi: import_types.InterfoldToken__factory.abi,
118
+ functionName: "approve",
119
+ args: [this.contracts.interfold, amount],
120
+ account
121
+ });
122
+ return await this.walletClient.writeContract(request);
123
+ } catch (error) {
124
+ throw new SDKError(`Failed to approve fee token: ${error}`, "APPROVE_FEE_TOKEN_FAILED");
125
+ }
126
+ }
127
+ async requestE3(params) {
128
+ if (!this.walletClient) {
129
+ throw new SDKError("Wallet client required for write operations", "NO_WALLET");
130
+ }
131
+ try {
132
+ const account = this.walletClient.account;
133
+ if (!account) {
134
+ throw new SDKError("No account connected", "NO_ACCOUNT");
135
+ }
136
+ const { request } = await this.publicClient.simulateContract({
137
+ address: this.contracts.interfold,
138
+ abi: import_types.Interfold__factory.abi,
139
+ functionName: "request",
140
+ args: [
141
+ {
142
+ committeeSize: params.committeeSize,
143
+ inputWindow: params.inputWindow,
144
+ e3Program: params.e3Program,
145
+ paramSet: params.paramSet,
146
+ computeProviderParams: params.computeProviderParams,
147
+ customParams: params.customParams || "0x",
148
+ proofAggregationEnabled: params.proofAggregationEnabled ?? true
149
+ }
150
+ ],
151
+ account,
152
+ gas: params.gasLimit
153
+ });
154
+ return await this.walletClient.writeContract(request);
155
+ } catch (error) {
156
+ throw new SDKError(`Failed to request E3: ${error}`, "REQUEST_E3_FAILED");
157
+ }
158
+ }
159
+ async publishCiphertextOutput(e3Id, ciphertextOutput, proof, gasLimit) {
160
+ if (!this.walletClient) {
161
+ throw new SDKError("Wallet client required for write operations", "NO_WALLET");
162
+ }
163
+ try {
164
+ const account = this.walletClient.account;
165
+ if (!account) {
166
+ throw new SDKError("No account connected", "NO_ACCOUNT");
167
+ }
168
+ const { request } = await this.publicClient.simulateContract({
169
+ address: this.contracts.interfold,
170
+ abi: import_types.Interfold__factory.abi,
171
+ functionName: "publishCiphertextOutput",
172
+ args: [e3Id, ciphertextOutput, proof],
173
+ account,
174
+ gas: gasLimit
175
+ });
176
+ return await this.walletClient.writeContract(request);
177
+ } catch (error) {
178
+ throw new SDKError(`Failed to publish ciphertext output: ${error}`, "PUBLISH_CIPHERTEXT_OUTPUT_FAILED");
179
+ }
180
+ }
181
+ async getE3(e3Id) {
182
+ try {
183
+ const result = await this.publicClient.readContract({
184
+ address: this.contracts.interfold,
185
+ abi: import_types.Interfold__factory.abi,
186
+ functionName: "getE3",
187
+ args: [e3Id]
188
+ });
189
+ return result;
190
+ } catch (error) {
191
+ throw new SDKError(`Failed to get E3: ${error}`, "GET_E3_FAILED");
192
+ }
193
+ }
194
+ async getE3Quote(requestParams) {
195
+ try {
196
+ return this.publicClient.readContract({
197
+ address: this.contracts.interfold,
198
+ abi: import_types.Interfold__factory.abi,
199
+ functionName: "getE3Quote",
200
+ args: [
201
+ {
202
+ committeeSize: requestParams.committeeSize,
203
+ inputWindow: requestParams.inputWindow,
204
+ e3Program: requestParams.e3Program,
205
+ paramSet: requestParams.paramSet,
206
+ computeProviderParams: requestParams.computeProviderParams,
207
+ customParams: requestParams.customParams || "0x",
208
+ proofAggregationEnabled: requestParams.proofAggregationEnabled ?? true
209
+ }
210
+ ]
211
+ });
212
+ } catch (error) {
213
+ throw new SDKError(`Failed to get E3 quote: ${error}`, "GET_E3_QUOTE_FAILED");
214
+ }
215
+ }
216
+ async getFailureReason(e3Id) {
217
+ try {
218
+ return this.publicClient.readContract({
219
+ address: this.contracts.interfold,
220
+ abi: import_types.Interfold__factory.abi,
221
+ functionName: "getFailureReason",
222
+ args: [e3Id]
223
+ });
224
+ } catch (error) {
225
+ throw new SDKError(`Failed to get failure reason: ${error}`, "GET_FAILURE_REASON_FAILED");
226
+ }
227
+ }
228
+ async getE3PublicKey(e3Id) {
229
+ try {
230
+ const result = await this.publicClient.readContract({
231
+ address: this.contracts.ciphernodeRegistry,
232
+ abi: import_types.CiphernodeRegistryOwnable__factory.abi,
233
+ functionName: "committeePublicKey",
234
+ args: [e3Id]
235
+ });
236
+ return result;
237
+ } catch (error) {
238
+ throw new SDKError(`Failed to get E3 public key: ${error}`, "GET_E3_PUBLIC_KEY_FAILED");
239
+ }
240
+ }
241
+ async getE3Stage(e3Id) {
242
+ try {
243
+ return this.publicClient.readContract({
244
+ address: this.contracts.interfold,
245
+ abi: import_types.Interfold__factory.abi,
246
+ functionName: "getE3Stage",
247
+ args: [e3Id]
248
+ });
249
+ } catch (error) {
250
+ throw new SDKError(`Failed to get E3 stage: ${error}`, "GET_E3_STAGE_FAILED");
251
+ }
252
+ }
253
+ async estimateGas(functionName, args, contractAddress, abi, value) {
254
+ if (!this.walletClient) {
255
+ throw new SDKError("Wallet client required for gas estimation", "NO_WALLET");
256
+ }
257
+ try {
258
+ const account = this.walletClient.account;
259
+ if (!account) {
260
+ throw new SDKError("No account connected", "NO_ACCOUNT");
261
+ }
262
+ const estimateParams = {
263
+ address: contractAddress,
264
+ abi,
265
+ functionName,
266
+ args,
267
+ account,
268
+ ...value !== void 0 && { value }
269
+ };
270
+ return await this.publicClient.estimateContractGas(estimateParams);
271
+ } catch (error) {
272
+ throw new SDKError(`Failed to estimate gas: ${error}`, "GAS_ESTIMATION_FAILED");
273
+ }
274
+ }
275
+ async waitForTransaction(hash) {
276
+ try {
277
+ return await this.publicClient.waitForTransactionReceipt({
278
+ hash,
279
+ confirmations: 1
280
+ });
281
+ } catch (error) {
282
+ throw new SDKError(`Failed to wait for transaction: ${error}`, "TRANSACTION_WAIT_FAILED");
283
+ }
284
+ }
285
+ };
286
+
287
+ // src/contracts/types.ts
288
+ var E3Stage = /* @__PURE__ */ ((E3Stage2) => {
289
+ E3Stage2[E3Stage2["None"] = 0] = "None";
290
+ E3Stage2[E3Stage2["Requested"] = 1] = "Requested";
291
+ E3Stage2[E3Stage2["CommitteeFinalized"] = 2] = "CommitteeFinalized";
292
+ E3Stage2[E3Stage2["KeyPublished"] = 3] = "KeyPublished";
293
+ E3Stage2[E3Stage2["CiphertextReady"] = 4] = "CiphertextReady";
294
+ E3Stage2[E3Stage2["Complete"] = 5] = "Complete";
295
+ E3Stage2[E3Stage2["Failed"] = 6] = "Failed";
296
+ return E3Stage2;
297
+ })(E3Stage || {});
298
+ var FailureReason = /* @__PURE__ */ ((FailureReason2) => {
299
+ FailureReason2[FailureReason2["None"] = 0] = "None";
300
+ FailureReason2[FailureReason2["CommitteeFormationTimeout"] = 1] = "CommitteeFormationTimeout";
301
+ FailureReason2[FailureReason2["InsufficientCommitteeMembers"] = 2] = "InsufficientCommitteeMembers";
302
+ FailureReason2[FailureReason2["DKGTimeout"] = 3] = "DKGTimeout";
303
+ FailureReason2[FailureReason2["DKGInvalidShares"] = 4] = "DKGInvalidShares";
304
+ FailureReason2[FailureReason2["NoInputsReceived"] = 5] = "NoInputsReceived";
305
+ FailureReason2[FailureReason2["ComputeTimeout"] = 6] = "ComputeTimeout";
306
+ FailureReason2[FailureReason2["ComputeProviderExpired"] = 7] = "ComputeProviderExpired";
307
+ FailureReason2[FailureReason2["ComputeProviderFailed"] = 8] = "ComputeProviderFailed";
308
+ FailureReason2[FailureReason2["RequesterCancelled"] = 9] = "RequesterCancelled";
309
+ FailureReason2[FailureReason2["DecryptionTimeout"] = 10] = "DecryptionTimeout";
310
+ FailureReason2[FailureReason2["DecryptionInvalidShares"] = 11] = "DecryptionInvalidShares";
311
+ FailureReason2[FailureReason2["VerificationFailed"] = 12] = "VerificationFailed";
312
+ return FailureReason2;
313
+ })(FailureReason || {});
314
+ // Annotate the CommonJS export names for ESM import in node:
315
+ 0 && (module.exports = {
316
+ ContractClient,
317
+ E3Stage,
318
+ FailureReason
319
+ });
320
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/index.ts","../../src/contracts/contract-client.ts","../../src/utils.ts","../../src/contracts/types.ts"],"sourcesContent":["// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nexport { ContractClient } from './contract-client'\nexport type { ContractClientConfig } from './contract-client'\nexport type { ContractAddresses, E3, E3RequestParams } from './types'\nexport { E3Stage, FailureReason } from './types'\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport {\n type Abi,\n type Chain,\n type Hash,\n type PublicClient,\n type TransactionReceipt,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n webSocket,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\n\nimport { CiphernodeRegistryOwnable__factory, Interfold__factory, InterfoldToken__factory } from '@interfold/contracts/types'\nimport type { ContractAddresses, E3, E3RequestParams, E3Stage, FailureReason } from './types'\nimport { SDKError, isValidAddress } from '../utils'\n\nexport interface ContractClientConfig {\n publicClient: PublicClient\n walletClient?: WalletClient\n contracts: ContractAddresses\n}\n\nexport class ContractClient {\n private publicClient: PublicClient\n private walletClient?: WalletClient\n private contracts: ContractAddresses\n private contractInfo: {\n interfold: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n }\n\n constructor(config: ContractClientConfig) {\n const { publicClient, walletClient, contracts } = config\n\n if (!isValidAddress(contracts.interfold)) {\n throw new SDKError('Invalid Interfold contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n this.publicClient = publicClient\n this.walletClient = walletClient\n this.contracts = contracts\n\n this.contractInfo = {\n interfold: {\n address: contracts.interfold,\n abi: Interfold__factory.abi,\n },\n ciphernodeRegistry: {\n address: contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n },\n }\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: ContractAddresses\n privateKey?: `0x${string}`\n chain: Chain\n }): ContractClient {\n const isWebSocket = options.rpcUrl.startsWith('ws://') || options.rpcUrl.startsWith('wss://')\n const transport = isWebSocket\n ? webSocket(options.rpcUrl, {\n keepAlive: { interval: 30_000 },\n reconnect: { attempts: 5, delay: 2_000 },\n })\n : http(options.rpcUrl)\n\n const publicClient = createPublicClient({\n chain: options.chain,\n transport,\n }) as PublicClient\n\n let walletClient: WalletClient | undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain: options.chain,\n transport,\n })\n }\n\n return new ContractClient({ publicClient, walletClient, contracts: options.contracts })\n }\n\n public getPublicClient(): PublicClient {\n return this.publicClient\n }\n\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n functionName: 'approve',\n args: [this.contracts.interfold, amount],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n public async requestE3(params: E3RequestParams): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'request',\n args: [\n {\n committeeSize: params.committeeSize,\n inputWindow: params.inputWindow,\n e3Program: params.e3Program,\n paramSet: params.paramSet,\n computeProviderParams: params.computeProviderParams,\n customParams: params.customParams || '0x',\n proofAggregationEnabled: params.proofAggregationEnabled ?? true,\n },\n ],\n account,\n gas: params.gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n public async publishCiphertextOutput(\n e3Id: bigint,\n ciphertextOutput: `0x${string}`,\n proof: `0x${string}`,\n gasLimit?: bigint,\n ): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, proof],\n account,\n gas: gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n public async getE3(e3Id: bigint): Promise<E3> {\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3: ${error}`, 'GET_E3_FAILED')\n }\n }\n\n public async getE3Quote(requestParams: E3RequestParams): Promise<bigint> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Quote',\n args: [\n {\n committeeSize: requestParams.committeeSize,\n inputWindow: requestParams.inputWindow,\n e3Program: requestParams.e3Program,\n paramSet: requestParams.paramSet,\n computeProviderParams: requestParams.computeProviderParams,\n customParams: requestParams.customParams || '0x',\n proofAggregationEnabled: requestParams.proofAggregationEnabled ?? true,\n },\n ],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 quote: ${error}`, 'GET_E3_QUOTE_FAILED')\n }\n }\n\n public async getFailureReason(e3Id: bigint): Promise<FailureReason> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getFailureReason',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get failure reason: ${error}`, 'GET_FAILURE_REASON_FAILED')\n }\n }\n\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n functionName: 'committeePublicKey',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3 public key: ${error}`, 'GET_E3_PUBLIC_KEY_FAILED')\n }\n }\n\n public async getE3Stage(e3Id: bigint): Promise<E3Stage> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Stage',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 stage: ${error}`, 'GET_E3_STAGE_FAILED')\n }\n }\n\n public async estimateGas(\n functionName: string,\n args: readonly unknown[],\n contractAddress: `0x${string}`,\n abi: Abi,\n value?: bigint,\n ): Promise<bigint> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for gas estimation', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const estimateParams = {\n address: contractAddress,\n abi,\n functionName,\n args,\n account,\n ...(value !== undefined && { value }),\n }\n\n return await this.publicClient.estimateContractGas(estimateParams)\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n return await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n } catch (error) {\n throw new SDKError(`Failed to wait for transaction: ${error}`, 'TRANSACTION_WAIT_FAILED')\n }\n }\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { type Address, type Hash, type Log, PublicClient, encodeAbiParameters } from 'viem'\nimport type { BfvParams } from './types'\n\nexport class SDKError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n }\n}\n\nexport function isValidAddress(address: string): address is Address {\n return /^0x[a-fA-F0-9]{40}$/.test(address)\n}\n\nexport function isValidHash(hash: string): hash is Hash {\n return /^0x[a-fA-F0-9]{64}$/.test(hash)\n}\n\nexport function formatEventName(contractName: string, eventName: string): string {\n return `${contractName}.${eventName}`\n}\n\nexport function parseEventData<T>(log: Log): T {\n return log.data as unknown as T\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport const sleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport function formatBigInt(value: bigint): string {\n return value.toString()\n}\n\nexport function parseBigInt(value: string): bigint {\n return BigInt(value)\n}\n\nexport function generateEventId(log: Log): string {\n return `${log.blockHash}-${log.logIndex}`\n}\n\n/**\n * Get the current timestamp in seconds\n * from onchain\n * @param publicClient - The public client to use\n */\nexport async function getCurrentTimestamp(publicClient: PublicClient): Promise<bigint> {\n const block = await publicClient.getBlock()\n return block.timestamp\n}\n\n// Compute provider parameters structure\nexport interface ComputeProviderParams {\n name: string\n parallel: boolean\n batch_size: number\n}\n\n// Default compute provider configuration\nexport const DEFAULT_COMPUTE_PROVIDER_PARAMS: ComputeProviderParams = {\n name: 'risc0',\n parallel: false,\n batch_size: 2,\n}\n\n// Default E3 configuration (`committeeSize` is `IInterfold.CommitteeSize`, not circuit N_PARTIES).\nexport const DEFAULT_E3_CONFIG = {\n committeeSize: 0, // CommitteeSize.Micro\n duration: 1800, // 30 minutes in seconds\n payment_amount: '0', // 0 ETH in wei\n} as const\n\n/**\n * Encode BFV parameters for the smart contract\n * BFV (Brakerski-Fan-Vercauteren) is a type of fully homomorphic encryption\n */\nexport function encodeBfvParams(params: BfvParams): `0x${string}` {\n const { degree, plaintextModulus, moduli, error1Variance } = params\n\n if (error1Variance === undefined) {\n throw new SDKError(\n 'error1Variance is required in ProtocolParams. All BFV parameter sets must specify error1_variance.',\n 'MISSING_ERROR1_VARIANCE',\n )\n }\n\n return encodeAbiParameters(\n [\n {\n name: 'bfvParams',\n type: 'tuple',\n components: [\n { name: 'degree', type: 'uint256' },\n { name: 'plaintext_modulus', type: 'uint256' },\n { name: 'moduli', type: 'uint256[]' },\n { name: 'error1_variance', type: 'string' },\n ],\n },\n ],\n [\n {\n degree: BigInt(degree),\n plaintext_modulus: BigInt(plaintextModulus),\n moduli: [...moduli],\n error1_variance: error1Variance,\n },\n ],\n )\n}\n\n/**\n * Encode compute provider parameters for the smart contract'\n * If mock is true, the compute provider parameters will return 32 bytes of 0x00\n */\nexport function encodeComputeProviderParams(params: ComputeProviderParams, mock: boolean = false): `0x${string}` {\n if (mock) {\n return `0x${'00'.repeat(32)}` as `0x${string}`\n }\n\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n/**\n * Encode custom parameters for the smart contract.\n */\nexport function encodeCustomParams(params: Record<string, unknown>): `0x${string}` {\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n// inputWindow[0] is always larger than now and dkg deadline\nexport const inputWindowStartBuffer = 15n\n\n/**\n * Calculate start window for E3 request\n * @dev This function can be used for testing purposes, or for E3s which need to start as soon as possible.\n * @param publicClient - The public client to use\n * @param duration - The duration of the input window in seconds\n * @param startBuffer - Buffer in seconds added to current timestamp for input window start\n */\nexport async function calculateInputWindow(\n publicClient: PublicClient,\n duration: number = DEFAULT_E3_CONFIG.duration,\n startBuffer: bigint = inputWindowStartBuffer,\n): Promise<[bigint, bigint]> {\n const now = await getCurrentTimestamp(publicClient)\n return [BigInt(now) + startBuffer, BigInt(now) + startBuffer + BigInt(duration)]\n}\n\n/**\n * Decode plaintextOutput bytes to get the actual result number\n */\nexport function decodePlaintextOutput(plaintextOutput: string): number | null {\n try {\n // Remove '0x' prefix if present\n const hex = plaintextOutput.startsWith('0x') ? plaintextOutput.slice(2) : plaintextOutput\n\n // Convert hex to bytes\n const bytes = new Uint8Array(hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [])\n\n if (bytes.length < 8) {\n console.warn('Plaintext output too short for u64 decoding')\n return null\n }\n\n // Decode first u64 (8 bytes) as little-endian\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const result = view.getBigUint64(0, true) // true for little-endian\n\n return Number(result)\n } catch (error) {\n console.error('Failed to decode plaintext output:', error)\n return null\n }\n}\n\n// Helper function to convert proof bytes to field elements\nexport function proofToFields(proof: Uint8Array): string[] {\n const fields: string[] = []\n for (let i = 0; i < proof.length; i += 32) {\n const chunk = proof.slice(i, i + 32)\n fields.push('0x' + Buffer.from(chunk).toString('hex'))\n }\n return fields\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nexport interface ContractAddresses {\n interfold: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n}\n\nexport enum CommitteeSize {\n Micro = 0,\n Small = 1,\n Medium = 2,\n Large = 3,\n}\n\nexport enum ParamSet {\n Insecure512 = 0,\n Secure8192 = 1,\n}\n\nexport interface E3 {\n seed: bigint\n committeeSize: number\n requestBlock: bigint\n inputWindow: readonly [bigint, bigint]\n encryptionSchemeId: string\n e3Program: string\n paramSet: number\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n plaintextOutput: string\n}\n\nexport interface RequestParams {\n gasLimit?: bigint\n}\n\nexport interface E3RequestParams extends RequestParams {\n committeeSize: number\n inputWindow: readonly [bigint, bigint]\n e3Program: `0x${string}`\n paramSet: number\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n /** When true, ciphernodes generate wrapper/fold proofs for DKG proof aggregation.\n * When false, proof aggregation is skipped for faster computation. Defaults to true. */\n proofAggregationEnabled?: boolean\n}\n\nexport enum E3Stage {\n None,\n Requested,\n CommitteeFinalized,\n KeyPublished,\n CiphertextReady,\n Complete,\n Failed,\n}\n\nexport enum FailureReason {\n None,\n CommitteeFormationTimeout,\n InsufficientCommitteeMembers,\n DKGTimeout,\n DKGInvalidShares,\n NoInputsReceived,\n ComputeTimeout,\n ComputeProviderExpired,\n ComputeProviderFailed,\n RequesterCancelled,\n DecryptionTimeout,\n DecryptionInvalidShares,\n VerificationFailed,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,IAAAA,eAWO;AACP,sBAAoC;AAEpC,mBAAgG;;;ACdhG,kBAAqF;AAG9E,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,eAAe,SAAqC;AAClE,SAAO,sBAAsB,KAAK,OAAO;AAC3C;;;ADSO,IAAM,iBAAN,MAAM,gBAAe;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAMR,YAAY,QAA8B;AACxC,UAAM,EAAE,cAAc,cAAc,UAAU,IAAI;AAElD,QAAI,CAAC,eAAe,UAAU,SAAS,GAAG;AACxC,YAAM,IAA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AAAA,8BAAA;AAbU,SAAAA;AAAA,GAAA;","names":["import_viem","E3Stage","FailureReason"]}
@@ -0,0 +1,34 @@
1
+ import { PublicClient, WalletClient, Chain, Hash, Abi, TransactionReceipt } from 'viem';
2
+ import { C as ContractAddresses, a as E3RequestParams, E as E3, F as FailureReason, b as E3Stage } from '../types-C9WZ1Khd.js';
3
+
4
+ interface ContractClientConfig {
5
+ publicClient: PublicClient;
6
+ walletClient?: WalletClient;
7
+ contracts: ContractAddresses;
8
+ }
9
+ declare class ContractClient {
10
+ private publicClient;
11
+ private walletClient?;
12
+ private contracts;
13
+ private contractInfo;
14
+ constructor(config: ContractClientConfig);
15
+ static create(options: {
16
+ rpcUrl: string;
17
+ contracts: ContractAddresses;
18
+ privateKey?: `0x${string}`;
19
+ chain: Chain;
20
+ }): ContractClient;
21
+ getPublicClient(): PublicClient;
22
+ approveFeeToken(amount: bigint): Promise<Hash>;
23
+ requestE3(params: E3RequestParams): Promise<Hash>;
24
+ publishCiphertextOutput(e3Id: bigint, ciphertextOutput: `0x${string}`, proof: `0x${string}`, gasLimit?: bigint): Promise<Hash>;
25
+ getE3(e3Id: bigint): Promise<E3>;
26
+ getE3Quote(requestParams: E3RequestParams): Promise<bigint>;
27
+ getFailureReason(e3Id: bigint): Promise<FailureReason>;
28
+ getE3PublicKey(e3Id: bigint): Promise<`0x${string}`>;
29
+ getE3Stage(e3Id: bigint): Promise<E3Stage>;
30
+ estimateGas(functionName: string, args: readonly unknown[], contractAddress: `0x${string}`, abi: Abi, value?: bigint): Promise<bigint>;
31
+ waitForTransaction(hash: Hash): Promise<TransactionReceipt>;
32
+ }
33
+
34
+ export { ContractAddresses, ContractClient, type ContractClientConfig, E3, E3RequestParams, E3Stage, FailureReason };