@enclave-e3/sdk 0.0.7-test

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1103 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ BFV_PARAMS_SET: () => BFV_PARAMS_SET,
34
+ BfvProtocolParams: () => BfvProtocolParams,
35
+ ContractClient: () => ContractClient,
36
+ DEFAULT_COMPUTE_PROVIDER_PARAMS: () => DEFAULT_COMPUTE_PROVIDER_PARAMS,
37
+ DEFAULT_E3_CONFIG: () => DEFAULT_E3_CONFIG,
38
+ EnclaveEventType: () => EnclaveEventType,
39
+ EnclaveSDK: () => EnclaveSDK,
40
+ EventListener: () => EventListener,
41
+ FheProtocol: () => FheProtocol,
42
+ RegistryEventType: () => RegistryEventType,
43
+ SDKError: () => SDKError,
44
+ calculateStartWindow: () => calculateStartWindow,
45
+ decodePlaintextOutput: () => decodePlaintextOutput,
46
+ encodeBfvParams: () => encodeBfvParams,
47
+ encodeComputeProviderParams: () => encodeComputeProviderParams,
48
+ formatBigInt: () => formatBigInt,
49
+ formatEventName: () => formatEventName,
50
+ generateEventId: () => generateEventId,
51
+ generateProof: () => generateProof,
52
+ getCurrentTimestamp: () => getCurrentTimestamp,
53
+ isValidAddress: () => isValidAddress,
54
+ isValidHash: () => isValidHash,
55
+ parseBigInt: () => parseBigInt,
56
+ parseEventData: () => parseEventData,
57
+ sleep: () => sleep
58
+ });
59
+ module.exports = __toCommonJS(index_exports);
60
+
61
+ // src/enclave-sdk.ts
62
+ var import_viem2 = require("viem");
63
+ var import_accounts = require("viem/accounts");
64
+ var import_chains = require("viem/chains");
65
+ var import_init = __toESM(require("@enclave-e3/wasm/init"), 1);
66
+ var import_types2 = require("@enclave-e3/contracts/types");
67
+
68
+ // src/contract-client.ts
69
+ var import_types = require("@enclave-e3/contracts/types");
70
+
71
+ // src/utils.ts
72
+ var import_viem = require("viem");
73
+ var SDKError = class extends Error {
74
+ constructor(message, code) {
75
+ super(message);
76
+ this.code = code;
77
+ this.name = "SDKError";
78
+ }
79
+ };
80
+ function isValidAddress(address) {
81
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
82
+ }
83
+ function isValidHash(hash) {
84
+ return /^0x[a-fA-F0-9]{64}$/.test(hash);
85
+ }
86
+ function formatEventName(contractName, eventName) {
87
+ return `${contractName}.${eventName}`;
88
+ }
89
+ function parseEventData(log) {
90
+ return log.data;
91
+ }
92
+ var sleep = (ms) => {
93
+ return new Promise((resolve) => setTimeout(resolve, ms));
94
+ };
95
+ function formatBigInt(value) {
96
+ return value.toString();
97
+ }
98
+ function parseBigInt(value) {
99
+ return BigInt(value);
100
+ }
101
+ function generateEventId(log) {
102
+ return `${log.blockHash}-${log.logIndex}`;
103
+ }
104
+ function getCurrentTimestamp() {
105
+ return Math.floor(Date.now() / 1e3);
106
+ }
107
+ var BFV_PARAMS_SET = {
108
+ degree: 2048,
109
+ plaintext_modulus: 1032193,
110
+ moduli: [0x3fffffff000001n]
111
+ // BigInt for the modulus
112
+ };
113
+ var DEFAULT_COMPUTE_PROVIDER_PARAMS = {
114
+ name: "risc0",
115
+ parallel: false,
116
+ batch_size: 2
117
+ };
118
+ var DEFAULT_E3_CONFIG = {
119
+ threshold_min: 2,
120
+ threshold_max: 3,
121
+ window_size: 120,
122
+ // 2 minutes in seconds
123
+ duration: 1800,
124
+ // 30 minutes in seconds
125
+ payment_amount: "0"
126
+ // 0 ETH in wei
127
+ };
128
+ function encodeBfvParams(degree = BFV_PARAMS_SET.degree, plaintext_modulus = BFV_PARAMS_SET.plaintext_modulus, moduli = BFV_PARAMS_SET.moduli) {
129
+ return (0, import_viem.encodeAbiParameters)(
130
+ [
131
+ {
132
+ name: "bfvParams",
133
+ type: "tuple",
134
+ components: [
135
+ { name: "degree", type: "uint256" },
136
+ { name: "plaintext_modulus", type: "uint256" },
137
+ { name: "moduli", type: "uint256[]" }
138
+ ]
139
+ }
140
+ ],
141
+ [
142
+ {
143
+ degree: BigInt(degree),
144
+ plaintext_modulus: BigInt(plaintext_modulus),
145
+ moduli: [...moduli]
146
+ }
147
+ ]
148
+ );
149
+ }
150
+ function encodeComputeProviderParams(params) {
151
+ const jsonString = JSON.stringify(params);
152
+ const encoder = new TextEncoder();
153
+ const bytes = encoder.encode(jsonString);
154
+ return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
155
+ }
156
+ function calculateStartWindow(windowSize = DEFAULT_E3_CONFIG.window_size) {
157
+ const now = getCurrentTimestamp();
158
+ return [BigInt(now), BigInt(now + windowSize)];
159
+ }
160
+ function decodePlaintextOutput(plaintextOutput) {
161
+ try {
162
+ const hex = plaintextOutput.startsWith("0x") ? plaintextOutput.slice(2) : plaintextOutput;
163
+ const bytes = new Uint8Array(
164
+ hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || []
165
+ );
166
+ if (bytes.length < 8) {
167
+ console.warn("Plaintext output too short for u64 decoding");
168
+ return null;
169
+ }
170
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
171
+ const result = view.getBigUint64(0, true);
172
+ return Number(result);
173
+ } catch (error) {
174
+ console.error("Failed to decode plaintext output:", error);
175
+ return null;
176
+ }
177
+ }
178
+
179
+ // src/contract-client.ts
180
+ var ContractClient = class {
181
+ constructor(publicClient, walletClient, addresses = {
182
+ enclave: "0x0000000000000000000000000000000000000000",
183
+ ciphernodeRegistry: "0x0000000000000000000000000000000000000000"
184
+ }) {
185
+ this.publicClient = publicClient;
186
+ this.walletClient = walletClient;
187
+ this.addresses = addresses;
188
+ if (!isValidAddress(addresses.enclave)) {
189
+ throw new SDKError("Invalid Enclave contract address", "INVALID_ADDRESS");
190
+ }
191
+ if (!isValidAddress(addresses.ciphernodeRegistry)) {
192
+ throw new SDKError(
193
+ "Invalid CiphernodeRegistry contract address",
194
+ "INVALID_ADDRESS"
195
+ );
196
+ }
197
+ }
198
+ contractInfo = null;
199
+ /**
200
+ * Initialize contract instances
201
+ */
202
+ async initialize() {
203
+ try {
204
+ this.contractInfo = {
205
+ enclave: {
206
+ address: this.addresses.enclave,
207
+ abi: import_types.Enclave__factory.abi
208
+ },
209
+ ciphernodeRegistry: {
210
+ address: this.addresses.ciphernodeRegistry,
211
+ abi: import_types.CiphernodeRegistryOwnable__factory.abi
212
+ }
213
+ };
214
+ } catch (error) {
215
+ throw new SDKError(
216
+ `Failed to initialize contracts: ${error}`,
217
+ "INITIALIZATION_FAILED"
218
+ );
219
+ }
220
+ }
221
+ /**
222
+ * Request a new E3 computation
223
+ * request(address filter, uint32[2] threshold, uint256[2] startWindow, uint256 duration, IE3Program e3Program, bytes e3ProgramParams, bytes computeProviderParams)
224
+ */
225
+ async requestE3(filter, threshold, startWindow, duration, e3Program, e3ProgramParams, computeProviderParams, value, gasLimit) {
226
+ if (!this.walletClient) {
227
+ throw new SDKError(
228
+ "Wallet client required for write operations",
229
+ "NO_WALLET"
230
+ );
231
+ }
232
+ if (!this.contractInfo) {
233
+ await this.initialize();
234
+ }
235
+ try {
236
+ const account = this.walletClient.account;
237
+ if (!account) {
238
+ throw new SDKError("No account connected", "NO_ACCOUNT");
239
+ }
240
+ const { request } = await this.publicClient.simulateContract({
241
+ address: this.addresses.enclave,
242
+ abi: import_types.Enclave__factory.abi,
243
+ functionName: "request",
244
+ args: [
245
+ {
246
+ filter,
247
+ threshold,
248
+ startWindow,
249
+ duration,
250
+ e3Program,
251
+ e3ProgramParams,
252
+ computeProviderParams
253
+ }
254
+ ],
255
+ account,
256
+ value: value || BigInt(0),
257
+ gas: gasLimit
258
+ });
259
+ const hash = await this.walletClient.writeContract(request);
260
+ return hash;
261
+ } catch (error) {
262
+ throw new SDKError(`Failed to request E3: ${error}`, "REQUEST_E3_FAILED");
263
+ }
264
+ }
265
+ /**
266
+ * Activate an E3 computation
267
+ * activate(uint256 e3Id, bytes memory publicKey)
268
+ */
269
+ async activateE3(e3Id, publicKey, gasLimit) {
270
+ if (!this.walletClient) {
271
+ throw new SDKError(
272
+ "Wallet client required for write operations",
273
+ "NO_WALLET"
274
+ );
275
+ }
276
+ if (!this.contractInfo) {
277
+ await this.initialize();
278
+ }
279
+ try {
280
+ const account = this.walletClient.account;
281
+ if (!account) {
282
+ throw new SDKError("No account connected", "NO_ACCOUNT");
283
+ }
284
+ const { request } = await this.publicClient.simulateContract({
285
+ address: this.addresses.enclave,
286
+ abi: import_types.Enclave__factory.abi,
287
+ functionName: "activate",
288
+ args: [e3Id, publicKey],
289
+ account,
290
+ gas: gasLimit
291
+ });
292
+ const hash = await this.walletClient.writeContract(request);
293
+ return hash;
294
+ } catch (error) {
295
+ throw new SDKError(
296
+ `Failed to activate E3: ${error}`,
297
+ "ACTIVATE_E3_FAILED"
298
+ );
299
+ }
300
+ }
301
+ /**
302
+ * Publish input for an E3 computation
303
+ * publishInput(uint256 e3Id, bytes memory data)
304
+ */
305
+ async publishInput(e3Id, data, gasLimit) {
306
+ if (!this.walletClient) {
307
+ throw new SDKError(
308
+ "Wallet client required for write operations",
309
+ "NO_WALLET"
310
+ );
311
+ }
312
+ if (!this.contractInfo) {
313
+ await this.initialize();
314
+ }
315
+ try {
316
+ const account = this.walletClient.account;
317
+ if (!account) {
318
+ throw new SDKError("No account connected", "NO_ACCOUNT");
319
+ }
320
+ const { request } = await this.publicClient.simulateContract({
321
+ address: this.addresses.enclave,
322
+ abi: import_types.Enclave__factory.abi,
323
+ functionName: "publishInput",
324
+ args: [e3Id, data],
325
+ account,
326
+ gas: gasLimit
327
+ });
328
+ const hash = await this.walletClient.writeContract(request);
329
+ return hash;
330
+ } catch (error) {
331
+ throw new SDKError(
332
+ `Failed to publish input: ${error}`,
333
+ "PUBLISH_INPUT_FAILED"
334
+ );
335
+ }
336
+ }
337
+ /**
338
+ * Publish ciphertext output for an E3 computation
339
+ * publishCiphertextOutput(uint256 e3Id, bytes memory ciphertextOutput, bytes memory proof)
340
+ */
341
+ async publishCiphertextOutput(e3Id, ciphertextOutput, proof, gasLimit) {
342
+ if (!this.walletClient) {
343
+ throw new SDKError(
344
+ "Wallet client required for write operations",
345
+ "NO_WALLET"
346
+ );
347
+ }
348
+ if (!this.contractInfo) {
349
+ await this.initialize();
350
+ }
351
+ try {
352
+ const account = this.walletClient.account;
353
+ if (!account) {
354
+ throw new SDKError("No account connected", "NO_ACCOUNT");
355
+ }
356
+ const { request } = await this.publicClient.simulateContract({
357
+ address: this.addresses.enclave,
358
+ abi: import_types.Enclave__factory.abi,
359
+ functionName: "publishCiphertextOutput",
360
+ args: [e3Id, ciphertextOutput, proof],
361
+ account,
362
+ gas: gasLimit
363
+ });
364
+ const hash = await this.walletClient.writeContract(request);
365
+ return hash;
366
+ } catch (error) {
367
+ throw new SDKError(
368
+ `Failed to publish ciphertext output: ${error}`,
369
+ "PUBLISH_CIPHERTEXT_OUTPUT_FAILED"
370
+ );
371
+ }
372
+ }
373
+ /**
374
+ * Get E3 information
375
+ * Based on the contract: getE3(uint256 e3Id) returns (E3 memory e3)
376
+ */
377
+ async getE3(e3Id) {
378
+ if (!this.contractInfo) {
379
+ await this.initialize();
380
+ }
381
+ try {
382
+ const result = await this.publicClient.readContract({
383
+ address: this.addresses.enclave,
384
+ abi: import_types.Enclave__factory.abi,
385
+ functionName: "getE3",
386
+ args: [e3Id]
387
+ });
388
+ return result;
389
+ } catch (error) {
390
+ throw new SDKError(`Failed to get E3: ${error}`, "GET_E3_FAILED");
391
+ }
392
+ }
393
+ /**
394
+ * Estimate gas for a transaction
395
+ */
396
+ async estimateGas(functionName, args, contractAddress, abi, value) {
397
+ if (!this.walletClient) {
398
+ throw new SDKError(
399
+ "Wallet client required for gas estimation",
400
+ "NO_WALLET"
401
+ );
402
+ }
403
+ try {
404
+ const account = this.walletClient.account;
405
+ if (!account) {
406
+ throw new SDKError("No account connected", "NO_ACCOUNT");
407
+ }
408
+ const estimateParams = {
409
+ address: contractAddress,
410
+ abi,
411
+ functionName,
412
+ args,
413
+ account,
414
+ ...value !== void 0 && { value }
415
+ };
416
+ const gas = await this.publicClient.estimateContractGas(estimateParams);
417
+ return gas;
418
+ } catch (error) {
419
+ throw new SDKError(
420
+ `Failed to estimate gas: ${error}`,
421
+ "GAS_ESTIMATION_FAILED"
422
+ );
423
+ }
424
+ }
425
+ /**
426
+ * Wait for transaction confirmation
427
+ */
428
+ async waitForTransaction(hash) {
429
+ try {
430
+ const receipt = await this.publicClient.waitForTransactionReceipt({
431
+ hash,
432
+ confirmations: 1
433
+ });
434
+ return receipt;
435
+ } catch (error) {
436
+ throw new SDKError(
437
+ `Failed to wait for transaction: ${error}`,
438
+ "TRANSACTION_WAIT_FAILED"
439
+ );
440
+ }
441
+ }
442
+ };
443
+
444
+ // src/event-listener.ts
445
+ var EventListener = class {
446
+ constructor(publicClient, config = {}) {
447
+ this.publicClient = publicClient;
448
+ this.config = config;
449
+ }
450
+ listeners = /* @__PURE__ */ new Map();
451
+ activeWatchers = /* @__PURE__ */ new Map();
452
+ isPolling = false;
453
+ lastBlockNumber = BigInt(0);
454
+ /**
455
+ * Listen to specific contract events
456
+ */
457
+ async watchContractEvent(address, eventType, abi, callback) {
458
+ const watcherKey = `${address}:${eventType}`;
459
+ console.log(`watchContractEvent: ${watcherKey}`);
460
+ if (!this.listeners.has(eventType)) {
461
+ this.listeners.set(eventType, /* @__PURE__ */ new Set());
462
+ }
463
+ console.log("Added callback");
464
+ this.listeners.get(eventType).add(callback);
465
+ const emitter = this;
466
+ if (!this.activeWatchers.has(watcherKey)) {
467
+ console.log("Adding active watcher for " + watcherKey);
468
+ try {
469
+ const unwatch = this.publicClient.watchContractEvent({
470
+ address,
471
+ abi,
472
+ eventName: eventType,
473
+ fromBlock: this.config.fromBlock,
474
+ onLogs(logs) {
475
+ for (let i = 0; i < logs.length; i++) {
476
+ const log = logs[i];
477
+ if (!log) {
478
+ console.log("warning: Log was falsy when a log was expected!");
479
+ break;
480
+ }
481
+ const event = {
482
+ type: eventType,
483
+ data: log.args,
484
+ log,
485
+ timestamp: /* @__PURE__ */ new Date(),
486
+ blockNumber: log.blockNumber ?? BigInt(0),
487
+ transactionHash: log.transactionHash ?? "0x"
488
+ };
489
+ console.log("Created event, now emitting event...");
490
+ emitter.emit(event);
491
+ console.log("Event emitted");
492
+ }
493
+ }
494
+ });
495
+ this.activeWatchers.set(watcherKey, unwatch);
496
+ } catch (error) {
497
+ throw new SDKError(
498
+ `Failed to watch contract event ${eventType} on ${address}: ${error}`,
499
+ "WATCH_EVENT_FAILED"
500
+ );
501
+ }
502
+ }
503
+ }
504
+ /**
505
+ * Listen to all logs from a specific address
506
+ */
507
+ async watchLogs(address, callback) {
508
+ const watcherKey = `logs:${address}`;
509
+ if (!this.activeWatchers.has(watcherKey)) {
510
+ try {
511
+ const unwatch = this.publicClient.watchEvent({
512
+ address,
513
+ onLogs: (logs) => {
514
+ logs.forEach((log) => {
515
+ callback(log);
516
+ });
517
+ }
518
+ });
519
+ this.activeWatchers.set(watcherKey, unwatch);
520
+ } catch (error) {
521
+ throw new SDKError(
522
+ `Failed to watch logs for address ${address}: ${error}`,
523
+ "WATCH_LOGS_FAILED"
524
+ );
525
+ }
526
+ }
527
+ }
528
+ /**
529
+ * Start polling for historical events
530
+ */
531
+ async startPolling() {
532
+ if (this.isPolling) return;
533
+ this.isPolling = true;
534
+ try {
535
+ this.lastBlockNumber = await this.publicClient.getBlockNumber();
536
+ void this.pollForEvents();
537
+ } catch (error) {
538
+ this.isPolling = false;
539
+ throw new SDKError(
540
+ `Failed to start polling: ${error}`,
541
+ "POLLING_START_FAILED"
542
+ );
543
+ }
544
+ }
545
+ /**
546
+ * Stop polling for events
547
+ */
548
+ stopPolling() {
549
+ this.isPolling = false;
550
+ }
551
+ /**
552
+ * Get historical events
553
+ */
554
+ async getHistoricalEvents(address, eventType, abi, fromBlock, toBlock) {
555
+ try {
556
+ const logs = await this.publicClient.getContractEvents({
557
+ address,
558
+ abi,
559
+ eventName: eventType,
560
+ fromBlock: fromBlock || this.config.fromBlock,
561
+ toBlock: toBlock || this.config.toBlock
562
+ });
563
+ return logs;
564
+ } catch (error) {
565
+ throw new SDKError(
566
+ `Failed to get historical events: ${error}`,
567
+ "HISTORICAL_EVENTS_FAILED"
568
+ );
569
+ }
570
+ }
571
+ /**
572
+ * SDKEventEmitter implementation
573
+ */
574
+ on(eventType, callback) {
575
+ if (!this.listeners.has(eventType)) {
576
+ this.listeners.set(eventType, /* @__PURE__ */ new Set());
577
+ }
578
+ this.listeners.get(eventType).add(callback);
579
+ }
580
+ off(eventType, callback) {
581
+ const callbacks = this.listeners.get(eventType);
582
+ if (callbacks) {
583
+ callbacks.delete(callback);
584
+ if (callbacks.size === 0) {
585
+ this.listeners.delete(eventType);
586
+ const watchersToRemove = [];
587
+ this.activeWatchers.forEach((unwatch, key) => {
588
+ if (key.endsWith(`:${eventType}`)) {
589
+ try {
590
+ unwatch();
591
+ } catch (error) {
592
+ console.error(`Error unwatching event ${eventType}:`, error);
593
+ }
594
+ watchersToRemove.push(key);
595
+ }
596
+ });
597
+ watchersToRemove.forEach((key) => this.activeWatchers.delete(key));
598
+ }
599
+ }
600
+ }
601
+ emit(event) {
602
+ console.log("emit() called for " + event.type);
603
+ const callbacks = this.listeners.get(event.type);
604
+ if (callbacks) {
605
+ console.log("Have " + callbacks.size + " callbacks");
606
+ callbacks.forEach((callback) => {
607
+ console.log("Running callback...");
608
+ try {
609
+ void callback(event);
610
+ } catch (error) {
611
+ console.error(`Error in event callback for ${event.type}:`, error);
612
+ }
613
+ });
614
+ }
615
+ }
616
+ /**
617
+ * Clean up all listeners and watchers
618
+ */
619
+ cleanup() {
620
+ this.stopPolling();
621
+ this.activeWatchers.forEach((unwatch) => {
622
+ try {
623
+ unwatch();
624
+ } catch (error) {
625
+ console.error("Error unwatching during cleanup:", error);
626
+ }
627
+ });
628
+ this.activeWatchers.clear();
629
+ this.listeners.clear();
630
+ }
631
+ async pollForEvents() {
632
+ while (this.isPolling) {
633
+ try {
634
+ const currentBlock = await this.publicClient.getBlockNumber();
635
+ if (currentBlock > this.lastBlockNumber) {
636
+ this.lastBlockNumber = currentBlock;
637
+ }
638
+ await sleep(this.config.pollingInterval || 5e3);
639
+ } catch (error) {
640
+ console.error("Error during polling:", error);
641
+ await sleep(this.config.pollingInterval || 5e3);
642
+ }
643
+ }
644
+ }
645
+ };
646
+
647
+ // src/types.ts
648
+ var EnclaveEventType = /* @__PURE__ */ ((EnclaveEventType2) => {
649
+ EnclaveEventType2["E3_REQUESTED"] = "E3Requested";
650
+ EnclaveEventType2["E3_ACTIVATED"] = "E3Activated";
651
+ EnclaveEventType2["INPUT_PUBLISHED"] = "InputPublished";
652
+ EnclaveEventType2["CIPHERTEXT_OUTPUT_PUBLISHED"] = "CiphertextOutputPublished";
653
+ EnclaveEventType2["PLAINTEXT_OUTPUT_PUBLISHED"] = "PlaintextOutputPublished";
654
+ EnclaveEventType2["E3_PROGRAM_ENABLED"] = "E3ProgramEnabled";
655
+ EnclaveEventType2["E3_PROGRAM_DISABLED"] = "E3ProgramDisabled";
656
+ EnclaveEventType2["ENCRYPTION_SCHEME_ENABLED"] = "EncryptionSchemeEnabled";
657
+ EnclaveEventType2["ENCRYPTION_SCHEME_DISABLED"] = "EncryptionSchemeDisabled";
658
+ EnclaveEventType2["CIPHERNODE_REGISTRY_SET"] = "CiphernodeRegistrySet";
659
+ EnclaveEventType2["MAX_DURATION_SET"] = "MaxDurationSet";
660
+ EnclaveEventType2["ALLOWED_E3_PROGRAMS_PARAMS_SET"] = "AllowedE3ProgramsParamsSet";
661
+ EnclaveEventType2["OWNERSHIP_TRANSFERRED"] = "OwnershipTransferred";
662
+ EnclaveEventType2["INITIALIZED"] = "Initialized";
663
+ return EnclaveEventType2;
664
+ })(EnclaveEventType || {});
665
+ var RegistryEventType = /* @__PURE__ */ ((RegistryEventType2) => {
666
+ RegistryEventType2["COMMITTEE_REQUESTED"] = "CommitteeRequested";
667
+ RegistryEventType2["COMMITTEE_PUBLISHED"] = "CommitteePublished";
668
+ RegistryEventType2["ENCLAVE_SET"] = "EnclaveSet";
669
+ RegistryEventType2["OWNERSHIP_TRANSFERRED"] = "OwnershipTransferred";
670
+ RegistryEventType2["INITIALIZED"] = "Initialized";
671
+ return RegistryEventType2;
672
+ })(RegistryEventType || {});
673
+ var FheProtocol = /* @__PURE__ */ ((FheProtocol2) => {
674
+ FheProtocol2["BFV"] = "BFV";
675
+ return FheProtocol2;
676
+ })(FheProtocol || {});
677
+ var BfvProtocolParams = {
678
+ /**
679
+ * Recommended parameters for BFV protocol
680
+ * - Degree: 2048
681
+ * - Plaintext modulus: 1032193
682
+ * - Moduli:0x3FFFFFFF000001
683
+ */
684
+ BFV_NORMAL: {
685
+ degree: 2048,
686
+ plaintextModulus: 1032193n,
687
+ moduli: 0x3FFFFFFF000001n
688
+ }
689
+ };
690
+
691
+ // src/enclave-sdk.ts
692
+ var import_wasm = require("@enclave-e3/wasm");
693
+
694
+ // src/greco.ts
695
+ var import_bb = require("@aztec/bb.js");
696
+ var import_noir_js = require("@noir-lang/noir_js");
697
+ var convertToPolynomial = (stringArray) => {
698
+ return {
699
+ coefficients: stringArray
700
+ };
701
+ };
702
+ var convertToPolynomialArray = (stringArrays) => {
703
+ return stringArrays.map(convertToPolynomial);
704
+ };
705
+ var generateProof = async (circuitInputs, circuit) => {
706
+ const noir = new import_noir_js.Noir(circuit);
707
+ const backend = new import_bb.UltraHonkBackend(circuit.bytecode, { threads: 4 });
708
+ const pk0is_poly = convertToPolynomialArray(circuitInputs.pk0is);
709
+ const pk1is_poly = convertToPolynomialArray(circuitInputs.pk1is);
710
+ const ct0is_poly = convertToPolynomialArray(circuitInputs.ct0is);
711
+ const ct1is_poly = convertToPolynomialArray(circuitInputs.ct1is);
712
+ const u_poly = convertToPolynomial(circuitInputs.u);
713
+ const e0_poly = convertToPolynomial(circuitInputs.e0);
714
+ const e1_poly = convertToPolynomial(circuitInputs.e1);
715
+ const k1_poly = convertToPolynomial(circuitInputs.k1);
716
+ const r1is_poly = convertToPolynomialArray(circuitInputs.r1is);
717
+ const r2is_poly = convertToPolynomialArray(circuitInputs.r2is);
718
+ const p1is_poly = convertToPolynomialArray(circuitInputs.p1is);
719
+ const p2is_poly = convertToPolynomialArray(circuitInputs.p2is);
720
+ const { witness } = await noir.execute({
721
+ // params: {
722
+ // q_mod_t: circuitInputs.params.q_mod_t,
723
+ // pk_bounds: circuitInputs.params.pk_bounds,
724
+ // e_bound: circuitInputs.params.e_bound,
725
+ // u_bound: circuitInputs.params.u_bound,
726
+ // r1_low_bounds: circuitInputs.params.r1_low_bounds,
727
+ // r1_up_bounds: circuitInputs.params.r1_up_bounds,
728
+ // r2_bounds: circuitInputs.params.r2_bounds,
729
+ // p1_bounds: circuitInputs.params.p1_bounds,
730
+ // p2_bounds: circuitInputs.params.p2_bounds,
731
+ // k1_low_bound: circuitInputs.params.k1_low_bound,
732
+ // k1_up_bound: circuitInputs.params.k1_up_bound,
733
+ // qis: circuitInputs.params.qis,
734
+ // k0is: circuitInputs.params.k0is,
735
+ // size: circuitInputs.params.size,
736
+ // tag: circuitInputs.params.tag,
737
+ // },
738
+ pk0is: pk0is_poly,
739
+ pk1is: pk1is_poly,
740
+ ct0is: ct0is_poly,
741
+ ct1is: ct1is_poly,
742
+ u: u_poly,
743
+ e0: e0_poly,
744
+ e1: e1_poly,
745
+ k1: k1_poly,
746
+ r1is: r1is_poly,
747
+ r2is: r2is_poly,
748
+ p1is: p1is_poly,
749
+ p2is: p2is_poly
750
+ });
751
+ return await backend.generateProof(witness, { keccak: true });
752
+ };
753
+
754
+ // src/enclave-sdk.ts
755
+ var EnclaveSDK = class _EnclaveSDK {
756
+ constructor(config) {
757
+ this.config = config;
758
+ if (!config.publicClient) {
759
+ throw new SDKError("Public client is required", "MISSING_PUBLIC_CLIENT");
760
+ }
761
+ if (!isValidAddress(config.contracts.enclave)) {
762
+ throw new SDKError("Invalid Enclave contract address", "INVALID_ADDRESS");
763
+ }
764
+ if (!isValidAddress(config.contracts.ciphernodeRegistry)) {
765
+ throw new SDKError(
766
+ "Invalid CiphernodeRegistry contract address",
767
+ "INVALID_ADDRESS"
768
+ );
769
+ }
770
+ this.eventListener = new EventListener(config.publicClient);
771
+ this.contractClient = new ContractClient(
772
+ config.publicClient,
773
+ config.walletClient,
774
+ config.contracts
775
+ );
776
+ this.protocol = config.protocol;
777
+ if (config.protocolParams) {
778
+ this.protocolParams = config.protocolParams;
779
+ } else {
780
+ switch (this.protocol) {
781
+ case "BFV" /* BFV */:
782
+ this.protocolParams = BfvProtocolParams.BFV_NORMAL;
783
+ break;
784
+ default:
785
+ throw new Error("Protocol not supported");
786
+ }
787
+ }
788
+ }
789
+ static chains = {
790
+ 1: import_chains.mainnet,
791
+ 11155111: import_chains.sepolia,
792
+ 41454: import_chains.monadTestnet,
793
+ 31337: import_chains.hardhat
794
+ };
795
+ eventListener;
796
+ contractClient;
797
+ initialized = false;
798
+ protocol;
799
+ protocolParams;
800
+ /**
801
+ * Initialize the SDK
802
+ */
803
+ // TODO: Delete this it is redundant
804
+ async initialize() {
805
+ if (this.initialized) return;
806
+ try {
807
+ await this.contractClient.initialize();
808
+ this.initialized = true;
809
+ } catch (error) {
810
+ throw new SDKError(
811
+ `Failed to initialize SDK: ${error}`,
812
+ "SDK_INITIALIZATION_FAILED"
813
+ );
814
+ }
815
+ }
816
+ /**
817
+ * Encrypt a number using the configured protocol
818
+ * @param data - The number to encrypt
819
+ * @param publicKey - The public key to use for encryption
820
+ * @returns The encrypted number
821
+ */
822
+ async encryptNumber(data, publicKey) {
823
+ await (0, import_init.default)();
824
+ switch (this.protocol) {
825
+ case "BFV" /* BFV */:
826
+ return (0, import_wasm.bfv_encrypt_number)(
827
+ data,
828
+ publicKey,
829
+ this.protocolParams.degree,
830
+ this.protocolParams.plaintextModulus,
831
+ this.protocolParams.moduli
832
+ );
833
+ default:
834
+ throw new Error("Protocol not supported");
835
+ }
836
+ }
837
+ /**
838
+ * Encrypt a number using the configured protocol and generate a zk-SNARK proof using Greco
839
+ * @param data - The number to encrypt
840
+ * @param publicKey - The public key to use for encryption
841
+ * @param circuit - The circuit to use for proof generation
842
+ * @returns The encrypted number and the proof
843
+ */
844
+ async encryptNumberAndGenProof(data, publicKey, circuit) {
845
+ await (0, import_init.default)();
846
+ switch (this.protocol) {
847
+ case "BFV" /* BFV */:
848
+ const [encryptedVote, circuitInputs] = (0, import_wasm.bfv_verifiable_encrypt_number)(
849
+ data,
850
+ publicKey,
851
+ this.protocolParams.degree,
852
+ this.protocolParams.plaintextModulus,
853
+ this.protocolParams.moduli
854
+ );
855
+ const inputs = JSON.parse(circuitInputs);
856
+ const proof = await generateProof(inputs, circuit);
857
+ return {
858
+ encryptedVote,
859
+ proof
860
+ };
861
+ default:
862
+ throw new Error("Protocol not supported");
863
+ }
864
+ }
865
+ /**
866
+ * Request a new E3 computation
867
+ */
868
+ async requestE3(params) {
869
+ console.log(">>> REQUEST");
870
+ if (!this.initialized) {
871
+ await this.initialize();
872
+ }
873
+ return this.contractClient.requestE3(
874
+ params.filter,
875
+ params.threshold,
876
+ params.startWindow,
877
+ params.duration,
878
+ params.e3Program,
879
+ params.e3ProgramParams,
880
+ params.computeProviderParams,
881
+ params.value,
882
+ params.gasLimit
883
+ );
884
+ }
885
+ /**
886
+ * Activate an E3 computation
887
+ */
888
+ async activateE3(e3Id, publicKey, gasLimit) {
889
+ if (!this.initialized) {
890
+ await this.initialize();
891
+ }
892
+ return this.contractClient.activateE3(e3Id, publicKey, gasLimit);
893
+ }
894
+ /**
895
+ * Publish input for an E3 computation
896
+ */
897
+ async publishInput(e3Id, data, gasLimit) {
898
+ if (!this.initialized) {
899
+ await this.initialize();
900
+ }
901
+ return this.contractClient.publishInput(e3Id, data, gasLimit);
902
+ }
903
+ /**
904
+ * Publish ciphertext output for an E3 computation
905
+ */
906
+ async publishCiphertextOutput(e3Id, ciphertextOutput, proof, gasLimit) {
907
+ if (!this.initialized) {
908
+ await this.initialize();
909
+ }
910
+ return this.contractClient.publishCiphertextOutput(
911
+ e3Id,
912
+ ciphertextOutput,
913
+ proof,
914
+ gasLimit
915
+ );
916
+ }
917
+ /**
918
+ * Get E3 information
919
+ */
920
+ async getE3(e3Id) {
921
+ if (!this.initialized) {
922
+ await this.initialize();
923
+ }
924
+ return this.contractClient.getE3(e3Id);
925
+ }
926
+ /**
927
+ * Unified Event Listening - Listen to any Enclave or Registry event
928
+ */
929
+ onEnclaveEvent(eventType, callback) {
930
+ const isEnclaveEvent = Object.values(EnclaveEventType).includes(
931
+ eventType
932
+ );
933
+ const contractAddress = isEnclaveEvent ? this.config.contracts.enclave : this.config.contracts.ciphernodeRegistry;
934
+ const abi = isEnclaveEvent ? import_types2.Enclave__factory.abi : import_types2.CiphernodeRegistryOwnable__factory.abi;
935
+ void this.eventListener.watchContractEvent(
936
+ contractAddress,
937
+ eventType,
938
+ abi,
939
+ callback
940
+ );
941
+ }
942
+ /**
943
+ * Remove event listener
944
+ */
945
+ off(eventType, callback) {
946
+ this.eventListener.off(eventType, callback);
947
+ }
948
+ /**
949
+ * Handle an event only once
950
+ */
951
+ once(type, callback) {
952
+ const handler = (event) => {
953
+ this.off(type, handler);
954
+ const prom = callback(event);
955
+ if (prom) {
956
+ prom.catch((e) => console.log(e));
957
+ }
958
+ };
959
+ this.onEnclaveEvent(type, handler);
960
+ }
961
+ /**
962
+ * Get historical events
963
+ */
964
+ async getHistoricalEvents(eventType, fromBlock, toBlock) {
965
+ const isEnclaveEvent = Object.values(EnclaveEventType).includes(
966
+ eventType
967
+ );
968
+ const contractAddress = isEnclaveEvent ? this.config.contracts.enclave : this.config.contracts.ciphernodeRegistry;
969
+ const abi = isEnclaveEvent ? import_types2.Enclave__factory.abi : import_types2.CiphernodeRegistryOwnable__factory.abi;
970
+ return this.eventListener.getHistoricalEvents(
971
+ contractAddress,
972
+ eventType,
973
+ abi,
974
+ fromBlock,
975
+ toBlock
976
+ );
977
+ }
978
+ /**
979
+ * Start polling for events
980
+ */
981
+ async startEventPolling() {
982
+ void this.eventListener.startPolling();
983
+ }
984
+ /**
985
+ * Stop polling for events
986
+ */
987
+ stopEventPolling() {
988
+ this.eventListener.stopPolling();
989
+ }
990
+ /**
991
+ * Utility methods
992
+ */
993
+ /**
994
+ * Estimate gas for a transaction
995
+ */
996
+ async estimateGas(functionName, args, contractAddress, abi, value) {
997
+ return this.contractClient.estimateGas(
998
+ functionName,
999
+ args,
1000
+ contractAddress,
1001
+ abi,
1002
+ value
1003
+ );
1004
+ }
1005
+ /**
1006
+ * Wait for transaction confirmation
1007
+ */
1008
+ async waitForTransaction(hash) {
1009
+ return this.contractClient.waitForTransaction(hash);
1010
+ }
1011
+ /**
1012
+ * Clean up resources
1013
+ */
1014
+ cleanup() {
1015
+ this.eventListener.cleanup();
1016
+ }
1017
+ /**
1018
+ * Update SDK configuration
1019
+ */
1020
+ // TODO: We should delete this as we don't want a stateful client.
1021
+ updateConfig(newConfig) {
1022
+ if (newConfig.publicClient) {
1023
+ this.config.publicClient = newConfig.publicClient;
1024
+ this.eventListener = new EventListener(newConfig.publicClient);
1025
+ }
1026
+ if (newConfig.walletClient) {
1027
+ this.config.walletClient = newConfig.walletClient;
1028
+ }
1029
+ if (newConfig.contracts) {
1030
+ this.config.contracts = {
1031
+ ...this.config.contracts,
1032
+ ...newConfig.contracts
1033
+ };
1034
+ }
1035
+ if (newConfig.chainId) {
1036
+ this.config.chainId = newConfig.chainId;
1037
+ }
1038
+ this.contractClient = new ContractClient(
1039
+ this.config.publicClient,
1040
+ this.config.walletClient,
1041
+ this.config.contracts
1042
+ );
1043
+ this.initialized = false;
1044
+ }
1045
+ static create(options) {
1046
+ const chain = _EnclaveSDK.chains[options.chainId];
1047
+ const isWebSocket = options.rpcUrl.startsWith("ws://") || options.rpcUrl.startsWith("wss://");
1048
+ const transport = isWebSocket ? (0, import_viem2.webSocket)(options.rpcUrl, {
1049
+ keepAlive: { interval: 3e4 },
1050
+ reconnect: { attempts: 5, delay: 2e3 }
1051
+ }) : (0, import_viem2.http)(options.rpcUrl);
1052
+ const publicClient = (0, import_viem2.createPublicClient)({
1053
+ chain,
1054
+ transport
1055
+ });
1056
+ let walletClient = void 0;
1057
+ if (options.privateKey) {
1058
+ const account = (0, import_accounts.privateKeyToAccount)(options.privateKey);
1059
+ walletClient = (0, import_viem2.createWalletClient)({
1060
+ account,
1061
+ chain,
1062
+ transport
1063
+ });
1064
+ }
1065
+ return new _EnclaveSDK({
1066
+ publicClient,
1067
+ walletClient,
1068
+ contracts: options.contracts,
1069
+ chainId: options.chainId,
1070
+ protocol: options.protocol,
1071
+ protocolParams: options.protocolParams
1072
+ });
1073
+ }
1074
+ };
1075
+ // Annotate the CommonJS export names for ESM import in node:
1076
+ 0 && (module.exports = {
1077
+ BFV_PARAMS_SET,
1078
+ BfvProtocolParams,
1079
+ ContractClient,
1080
+ DEFAULT_COMPUTE_PROVIDER_PARAMS,
1081
+ DEFAULT_E3_CONFIG,
1082
+ EnclaveEventType,
1083
+ EnclaveSDK,
1084
+ EventListener,
1085
+ FheProtocol,
1086
+ RegistryEventType,
1087
+ SDKError,
1088
+ calculateStartWindow,
1089
+ decodePlaintextOutput,
1090
+ encodeBfvParams,
1091
+ encodeComputeProviderParams,
1092
+ formatBigInt,
1093
+ formatEventName,
1094
+ generateEventId,
1095
+ generateProof,
1096
+ getCurrentTimestamp,
1097
+ isValidAddress,
1098
+ isValidHash,
1099
+ parseBigInt,
1100
+ parseEventData,
1101
+ sleep
1102
+ });
1103
+ //# sourceMappingURL=index.cjs.map