@enclave-e3/sdk 0.1.7 → 0.1.9

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/enclave-sdk.ts","../src/contract-client.ts","../src/utils.ts","../src/event-listener.ts","../src/types.ts","../src/greco.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\n// Main SDK class\nexport { EnclaveSDK } from './enclave-sdk'\n\n// Core classes\nexport { EventListener } from './event-listener'\nexport { ContractClient } from './contract-client'\n\n// Types and interfaces\nexport type {\n E3,\n SDKConfig,\n EventListenerConfig,\n ContractInstances,\n EventFilter,\n EventCallback,\n SDKEventEmitter,\n AllEventTypes,\n EnclaveEvent,\n // Event data types\n E3RequestedData,\n E3ActivatedData,\n CiphertextOutputPublishedData,\n PlaintextOutputPublishedData,\n CiphernodeAddedData,\n CiphernodeRemovedData,\n CommitteeRequestedData,\n CommitteePublishedData,\n CommitteeFinalizedData,\n EnclaveEventData,\n RegistryEventData,\n ProtocolParams,\n VerifiableEncryptionResult,\n EncryptedValueAndPublicInputs,\n} from './types'\n\n// enums and constants\nexport { EnclaveEventType, RegistryEventType, FheProtocol, BfvProtocolParams } from './types'\n\n// Export utilities\nexport {\n SDKError,\n isValidAddress,\n isValidHash,\n formatEventName,\n parseEventData,\n formatBigInt,\n parseBigInt,\n generateEventId,\n sleep,\n getCurrentTimestamp,\n // BFV and E3 utilities\n BFV_PARAMS_SET,\n DEFAULT_COMPUTE_PROVIDER_PARAMS,\n DEFAULT_E3_CONFIG,\n encodeBfvParams,\n encodeComputeProviderParams,\n encodeCustomParams,\n calculateStartWindow,\n decodePlaintextOutput,\n type ComputeProviderParams,\n} from './utils'\n\nexport { generateProof, type Polynomial, convertToPolynomial, convertToPolynomialArray } from './greco'\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 Abi, type Hash, type Log, PublicClient, WalletClient, createPublicClient, createWalletClient, http, webSocket } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { hardhat, mainnet, monadTestnet, sepolia } from 'viem/chains'\nimport initializeWasm from '@enclave-e3/wasm/init'\n\nimport { CiphernodeRegistryOwnable__factory, Enclave__factory } from '@enclave-e3/contracts/types'\nimport { ContractClient } from './contract-client'\nimport { EventListener } from './event-listener'\nimport { FheProtocol, EnclaveEventType } from './types'\nimport { SDKError, isValidAddress } from './utils'\n\nimport type {\n AllEventTypes,\n E3,\n EventCallback,\n SDKConfig,\n ProtocolParams,\n VerifiableEncryptionResult,\n EncryptedValueAndPublicInputs,\n ProtocolParamsName,\n} from './types'\nimport {\n bfv_encrypt_number,\n bfv_encrypt_vector,\n bfv_verifiable_encrypt_number,\n bfv_verifiable_encrypt_vector,\n get_bfv_params,\n} from '@enclave-e3/wasm'\nimport { generateProof } from './greco'\nimport { CompiledCircuit } from '@noir-lang/noir_js'\n\nexport class EnclaveSDK {\n public static readonly chains = {\n 1: mainnet,\n 11155111: sepolia,\n 41454: monadTestnet,\n 31337: hardhat,\n } as const\n\n private eventListener: EventListener\n private contractClient: ContractClient\n private initialized = false\n private protocol: FheProtocol\n private protocolParams?: ProtocolParams\n private publicClient: PublicClient\n\n // TODO: use zod for config validation\n constructor(private config: SDKConfig) {\n if (!config.publicClient) {\n throw new SDKError('Public client is required', 'MISSING_PUBLIC_CLIENT')\n }\n\n if (!isValidAddress(config.contracts.enclave)) {\n throw new SDKError('Invalid Enclave contract address', 'INVALID_ADDRESS')\n }\n\n if (!isValidAddress(config.contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n\n if (!isValidAddress(config.contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n this.eventListener = new EventListener(config.publicClient)\n this.contractClient = new ContractClient(config.publicClient, config.walletClient, config.contracts)\n\n if (!Object.values(FheProtocol).includes(config.protocol)) {\n throw new SDKError(`Invalid protocol: ${config.protocol}`, 'INVALID_PROTOCOL')\n }\n\n this.protocol = config.protocol\n\n if (config.protocolParams) {\n this.protocolParams = config.protocolParams\n }\n\n this.publicClient = config.publicClient\n }\n\n /**\n * Initialize the SDK\n */\n // TODO: Delete this it is redundant\n public async initialize(): Promise<void> {\n if (this.initialized) return\n\n try {\n await this.contractClient.initialize()\n this.initialized = true\n } catch (error) {\n throw new SDKError(`Failed to initialize SDK: ${error}`, 'SDK_INITIALIZATION_FAILED')\n }\n }\n\n /**\n * Get the public client used by the SDK\n * @returns The public client\n */\n public getPublicClient = (): PublicClient => {\n return this.publicClient\n }\n\n public async getBfvParamsSet(name: ProtocolParamsName): Promise<ProtocolParams> {\n await initializeWasm()\n let params = get_bfv_params(name as string)\n return {\n degree: Number(params.degree), // degree is returned as a bigint from wasm\n plaintextModulus: params.plaintext_modulus as bigint,\n moduli: params.moduli as bigint[],\n error1Variance: params.error1_variance,\n }\n }\n\n public async getProtocolParams(): Promise<ProtocolParams> {\n await initializeWasm()\n if (this.protocolParams) {\n return this.protocolParams\n }\n\n switch (this.protocol) {\n case FheProtocol.BFV:\n return await this.getBfvParamsSet('INSECURE_SET_2048_1032193_1')\n case FheProtocol.TRBFV:\n return await this.getBfvParamsSet('INSECURE_SET_512_10_1')\n }\n }\n\n /**\n * Encrypt a number using the configured protocol\n * @param data - The number to encrypt\n * @param publicKey - The public key to use for encryption\n * @returns The encrypted number\n */\n public async encryptNumber(data: bigint, publicKey: Uint8Array): Promise<Uint8Array> {\n await initializeWasm()\n const protocolParams = await this.getProtocolParams()\n\n return bfv_encrypt_number(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n }\n\n /**\n * Encrypt a vector using the configured protocol\n * @param data - The vector to encrypt\n * @param publicKey - The public key to use for encryption\n * @returns The ciphertext\n */\n public async encryptVector(data: BigUint64Array, publicKey: Uint8Array): Promise<Uint8Array> {\n await initializeWasm()\n const protocolParams = await this.getProtocolParams()\n\n return bfv_encrypt_vector(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n }\n\n /**\n * This function encrypts a number using the configured FHE protocol\n * and generates the necessary public inputs for a zk-SNARK proof.\n * @param data The number to encrypt\n * @param publicKey The public key to use for encryption\n * @returns The encrypted number and the inputs for the zk-SNARK proof\n */\n public async encryptNumberAndGenInputs(data: bigint, publicKey: Uint8Array): Promise<EncryptedValueAndPublicInputs> {\n await initializeWasm()\n const protocolParams = await this.getProtocolParams()\n\n const [encryptedData, circuitInputs] = bfv_verifiable_encrypt_number(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n\n const publicInputs = JSON.parse(circuitInputs)\n return {\n encryptedData,\n publicInputs,\n }\n }\n\n /**\n * Encrypt a number using the configured protocol and generate a zk-SNARK proof using Greco\n * @param data - The number to encrypt\n * @param publicKey - The public key to use for encryption\n * @param circuit - The circuit to use for proof generation\n * @returns The encrypted number and the proof\n */\n public async encryptNumberAndGenProof(\n data: bigint,\n publicKey: Uint8Array,\n circuit: CompiledCircuit,\n ): Promise<VerifiableEncryptionResult> {\n const { publicInputs, encryptedData } = await this.encryptNumberAndGenInputs(data, publicKey)\n const proof = await generateProof(publicInputs, circuit)\n\n return {\n encryptedData,\n proof,\n }\n }\n\n /**\n * Encrypt a vector and generate inputs for an E3 computation\n * @param data - The vector to encrypt\n * @param publicKey - The public key to use for encryption\n * @returns The encrypted vector and the inputs for the E3 computation\n */\n public async encryptVectorAndGenInputs(data: BigUint64Array, publicKey: Uint8Array): Promise<EncryptedValueAndPublicInputs> {\n await initializeWasm()\n const protocolParams = await this.getProtocolParams()\n\n const [encryptedData, circuitInputs] = bfv_verifiable_encrypt_vector(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n\n const publicInputs = JSON.parse(circuitInputs)\n return {\n encryptedData,\n publicInputs,\n }\n }\n\n /**\n * Encrypt a vector using the configured protocol and generate a zk-SNARK proof using Greco\n * @param data - The vector to encrypt\n * @param publicKey - The public key to use for encryption\n * @param circuit - The circuit to use for proof generation\n * @returns The encrypted vector and the proof\n */\n public async encryptVectorAndGenProof(\n data: BigUint64Array,\n publicKey: Uint8Array,\n circuit: CompiledCircuit,\n ): Promise<VerifiableEncryptionResult> {\n const { publicInputs, encryptedData } = await this.encryptVectorAndGenInputs(data, publicKey)\n\n const proof = await generateProof(publicInputs, circuit)\n\n return {\n encryptedData,\n proof,\n }\n }\n\n /**\n * Approve the fee token for the Enclave\n * @param amount - The amount to approve\n * @returns The approval transaction hash\n */\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n console.log('>>> APPROVE FEE TOKEN')\n\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.approveFeeToken(amount)\n }\n\n /**\n * Request a new E3 computation\n */\n public async requestE3(params: {\n threshold: [number, number]\n startWindow: [bigint, bigint]\n duration: bigint\n e3Program: `0x${string}`\n e3ProgramParams: `0x${string}`\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n gasLimit?: bigint\n }): Promise<Hash> {\n console.log('>>> REQUEST')\n\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.requestE3(\n params.threshold,\n params.startWindow,\n params.duration,\n params.e3Program,\n params.e3ProgramParams,\n params.computeProviderParams,\n params.customParams,\n params.gasLimit,\n )\n }\n\n /**\n * Get the public key for an E3 computation\n * @param e3Id - The ID of the E3 computation\n * @returns The public key\n */\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.getE3PublicKey(e3Id)\n }\n\n /**\n * Activate an E3 computation\n */\n public async activateE3(e3Id: bigint, publicKey: `0x${string}`, gasLimit?: bigint): Promise<Hash> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.activateE3(e3Id, publicKey, gasLimit)\n }\n\n /**\n * Publish input for an E3 computation\n */\n public async publishInput(e3Id: bigint, data: `0x${string}`, gasLimit?: bigint): Promise<Hash> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.publishInput(e3Id, data, gasLimit)\n }\n\n /**\n * Publish ciphertext output for an E3 computation\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.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.publishCiphertextOutput(e3Id, ciphertextOutput, proof, gasLimit)\n }\n\n /**\n * Get E3 information\n */\n public async getE3(e3Id: bigint): Promise<E3> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.getE3(e3Id)\n }\n\n /**\n * Unified Event Listening - Listen to any Enclave or Registry event\n */\n public onEnclaveEvent<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n // Determine which contract to listen to based on event type\n const isEnclaveEvent = Object.values(EnclaveEventType).includes(eventType as EnclaveEventType)\n const contractAddress = isEnclaveEvent ? this.config.contracts.enclave : this.config.contracts.ciphernodeRegistry\n const abi = isEnclaveEvent ? Enclave__factory.abi : CiphernodeRegistryOwnable__factory.abi\n\n void this.eventListener.watchContractEvent(contractAddress, eventType, abi, callback)\n }\n\n /**\n * Remove event listener\n */\n public off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n this.eventListener.off(eventType, callback)\n }\n\n /**\n * Handle an event only once\n */\n public once<T extends AllEventTypes>(type: T, callback: EventCallback<T>): void {\n const handler: EventCallback<T> = (event) => {\n this.off(type, handler)\n const prom = callback(event)\n if (prom) {\n prom.catch((e) => console.log(e))\n }\n }\n this.onEnclaveEvent(type, handler)\n }\n\n /**\n * Get historical events\n */\n public async getHistoricalEvents(eventType: AllEventTypes, fromBlock?: bigint, toBlock?: bigint): Promise<Log[]> {\n const isEnclaveEvent = Object.values(EnclaveEventType).includes(eventType as EnclaveEventType)\n const contractAddress = isEnclaveEvent ? this.config.contracts.enclave : this.config.contracts.ciphernodeRegistry\n const abi = isEnclaveEvent ? Enclave__factory.abi : CiphernodeRegistryOwnable__factory.abi\n\n return this.eventListener.getHistoricalEvents(contractAddress, eventType, abi, fromBlock, toBlock)\n }\n\n /**\n * Start polling for events\n */\n public async startEventPolling(): Promise<void> {\n void this.eventListener.startPolling()\n }\n\n /**\n * Stop polling for events\n */\n public stopEventPolling(): void {\n this.eventListener.stopPolling()\n }\n\n /**\n * Utility methods\n */\n\n /**\n * Estimate gas for a transaction\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 return this.contractClient.estimateGas(functionName, args, contractAddress, abi, value)\n }\n\n /**\n * Wait for transaction confirmation\n */\n public async waitForTransaction(hash: Hash): Promise<unknown> {\n return this.contractClient.waitForTransaction(hash)\n }\n\n /**\n * Clean up resources\n */\n public cleanup(): void {\n this.eventListener.cleanup()\n }\n\n /**\n * Update SDK configuration\n */\n // TODO: We should delete this as we don't want a stateful client.\n public updateConfig(newConfig: Partial<SDKConfig>): void {\n if (newConfig.publicClient) {\n this.config.publicClient = newConfig.publicClient\n this.eventListener = new EventListener(newConfig.publicClient)\n }\n\n if (newConfig.walletClient) {\n this.config.walletClient = newConfig.walletClient\n }\n\n if (newConfig.contracts) {\n this.config.contracts = {\n ...this.config.contracts,\n ...newConfig.contracts,\n }\n }\n\n if (newConfig.chainId) {\n this.config.chainId = newConfig.chainId\n }\n\n this.contractClient = new ContractClient(this.config.publicClient, this.config.walletClient, this.config.contracts)\n\n this.initialized = false\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: {\n enclave: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n }\n privateKey?: `0x${string}`\n chainId: keyof typeof EnclaveSDK.chains\n protocol: FheProtocol\n protocolParams?: ProtocolParams\n }): EnclaveSDK {\n const chain = EnclaveSDK.chains[options.chainId]\n\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 const publicClient = createPublicClient({\n chain,\n transport,\n }) as SDKConfig['publicClient']\n let walletClient: WalletClient | undefined = undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain,\n transport,\n })\n }\n\n return new EnclaveSDK({\n publicClient,\n walletClient,\n contracts: options.contracts,\n chainId: options.chainId,\n protocol: options.protocol,\n protocolParams: options.protocolParams,\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 { Abi, Hash, PublicClient, TransactionReceipt, WalletClient } from 'viem'\n\nimport { CiphernodeRegistryOwnable__factory, Enclave__factory, EnclaveToken__factory } from '@enclave-e3/contracts/types'\nimport { type E3 } from './types'\nimport { SDKError, isValidAddress } from './utils'\n\nexport class ContractClient {\n private contractInfo: {\n enclave: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n } | null = null\n\n constructor(\n private publicClient: PublicClient,\n private walletClient?: WalletClient,\n private addresses: {\n enclave: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n } = {\n enclave: '0x0000000000000000000000000000000000000000',\n ciphernodeRegistry: '0x0000000000000000000000000000000000000000',\n feeToken: '0x0000000000000000000000000000000000000000',\n },\n ) {\n if (!isValidAddress(addresses.enclave)) {\n throw new SDKError('Invalid Enclave contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(addresses.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(addresses.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n }\n\n /**\n * Initialize contract instances\n */\n public async initialize(): Promise<void> {\n try {\n this.contractInfo = {\n enclave: {\n address: this.addresses.enclave,\n abi: Enclave__factory.abi,\n },\n ciphernodeRegistry: {\n address: this.addresses.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: this.addresses.feeToken,\n abi: EnclaveToken__factory.abi,\n },\n }\n } catch (error) {\n throw new SDKError(`Failed to initialize contracts: ${error}`, 'INITIALIZATION_FAILED')\n }\n }\n\n /**\n * Approve the fee token for the Enclave\n * approve(address spender, uint256 amount)\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 if (!this.contractInfo) {\n await this.initialize()\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.addresses.feeToken,\n abi: EnclaveToken__factory.abi,\n functionName: 'approve',\n args: [this.addresses.enclave, amount],\n account,\n })\n\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n /**\n * Request a new E3 computation\n * request(address filter, uint32[2] threshold, uint256[2] startWindow, uint256 duration, IE3Program e3Program, bytes e3ProgramParams, bytes computeProviderParams, bytes customParams)\n */\n public async requestE3(\n threshold: [number, number],\n startWindow: [bigint, bigint],\n duration: bigint,\n e3Program: `0x${string}`,\n e3ProgramParams: `0x${string}`,\n computeProviderParams: `0x${string}`,\n customParams?: `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 if (!this.contractInfo) {\n await this.initialize()\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 // Simulate transaction\n const { request } = await this.publicClient.simulateContract({\n address: this.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'request',\n args: [\n {\n threshold,\n startWindow,\n duration,\n e3Program,\n e3ProgramParams,\n computeProviderParams,\n customParams: customParams || '0x',\n },\n ],\n account,\n gas: gasLimit,\n })\n\n // Execute transaction\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n /**\n * Activate an E3 computation\n * activate(uint256 e3Id, bytes memory publicKey)\n */\n public async activateE3(e3Id: bigint, publicKey: `0x${string}`, gasLimit?: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n if (!this.contractInfo) {\n await this.initialize()\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.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'activate',\n args: [e3Id, publicKey],\n account,\n gas: gasLimit,\n })\n\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to activate E3: ${error}`, 'ACTIVATE_E3_FAILED')\n }\n }\n\n /**\n * Publish input for an E3 computation\n * publishInput(uint256 e3Id, bytes memory data)\n */\n public async publishInput(e3Id: bigint, data: `0x${string}`, gasLimit?: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n if (!this.contractInfo) {\n await this.initialize()\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.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'publishInput',\n args: [e3Id, data],\n account,\n gas: gasLimit,\n })\n\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to publish input: ${error}`, 'PUBLISH_INPUT_FAILED')\n }\n }\n\n /**\n * Publish ciphertext output for an E3 computation\n * publishCiphertextOutput(uint256 e3Id, bytes memory ciphertextOutput, bytes memory proof)\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 if (!this.contractInfo) {\n await this.initialize()\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 // Simulate transaction\n const { request } = await this.publicClient.simulateContract({\n address: this.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, proof],\n account,\n gas: gasLimit,\n })\n\n // Execute transaction\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n /**\n * Get E3 information\n * Based on the contract: getE3(uint256 e3Id) returns (E3 memory e3)\n */\n public async getE3(e3Id: bigint): Promise<E3> {\n if (!this.contractInfo) {\n await this.initialize()\n }\n\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.addresses.enclave,\n abi: Enclave__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 /**\n * Get the public key for an E3 computation\n * Based on the contract: committeePublicKey(uint256 e3Id) returns (bytes32 publicKeyHash)\n * @param e3Id\n * @returns The public key\n */\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n if (!this.contractInfo) {\n await this.initialize()\n }\n\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.addresses.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 /**\n * Estimate gas for a transaction\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 const gas = await this.publicClient.estimateContractGas(estimateParams)\n\n return gas\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n /**\n * Wait for transaction confirmation\n */\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n\n return receipt\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, encodeAbiParameters } from 'viem'\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 */\nexport function getCurrentTimestamp(): number {\n return Math.floor(Date.now() / 1000)\n}\n\n// BFV parameter set matching the Rust INSECURE_SET_2048_1032193_1 configuration\nexport const INSECURE_SET_2048_1032193_1 = {\n degree: 2048,\n plaintext_modulus: 1032193,\n moduli: [0x3fffffff000001n], // BigInt for the modulus\n error1_variance: '10',\n} as const\n\n// BFV parameter set matching the Rust SET_8192_1000_4 configuration\nexport const SET_8192_1000_4 = {\n degree: 8192,\n plaintext_modulus: 1000,\n moduli: [0x00800000022a0001n, 0x00800000021a0001n, 0x0080000002120001n, 0x0080000001f60001n],\n error1_variance: '52309181128222339698631578526730685514457152477762943514050560000',\n}\n\n// Set default parameter set\nexport const BFV_PARAMS_SET = INSECURE_SET_2048_1032193_1\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\nexport const DEFAULT_E3_CONFIG = {\n threshold_min: 2,\n threshold_max: 5,\n window_size: 120, // 2 minutes in seconds\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(\n degree: number = BFV_PARAMS_SET.degree,\n plaintext_modulus: number = BFV_PARAMS_SET.plaintext_modulus,\n moduli: readonly bigint[] = BFV_PARAMS_SET.moduli,\n error1_variance: string = BFV_PARAMS_SET.error1_variance,\n): `0x${string}` {\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(plaintext_modulus),\n moduli: [...moduli],\n error1_variance,\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${'0'.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/**\n * Calculate start window for E3 request\n */\nexport function calculateStartWindow(windowSize: number = DEFAULT_E3_CONFIG.window_size): [bigint, bigint] {\n const now = getCurrentTimestamp()\n return [BigInt(now), BigInt(now + windowSize)]\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","// 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 Abi, type Log, type PublicClient } from 'viem'\n\nimport {\n type AllEventTypes,\n type EnclaveEvent,\n type EnclaveEventData,\n type EnclaveEventType,\n type EventCallback,\n type EventListenerConfig,\n type RegistryEventData,\n type RegistryEventType,\n type SDKEventEmitter,\n} from './types'\nimport { SDKError, sleep } from './utils'\n\nexport class EventListener implements SDKEventEmitter {\n private listeners: Map<AllEventTypes, Set<EventCallback>> = new Map()\n private activeWatchers: Map<string, () => void> = new Map()\n private isPolling = false\n private lastBlockNumber: bigint = BigInt(0)\n\n constructor(\n private publicClient: PublicClient,\n private config: EventListenerConfig = {},\n ) {}\n\n /**\n * Listen to specific contract events\n */\n public async watchContractEvent<T extends AllEventTypes>(\n address: `0x${string}`,\n eventType: T,\n abi: Abi,\n callback: EventCallback<T>,\n ): Promise<void> {\n const watcherKey = `${address}:${eventType}`\n console.log(`watchContractEvent: ${watcherKey}`)\n\n if (!this.listeners.has(eventType)) {\n this.listeners.set(eventType, new Set())\n }\n console.log('Added callback')\n this.listeners.get(eventType)!.add(callback as EventCallback)\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const emitter = this\n\n // If we don't have an active watcher for this event, create one\n if (!this.activeWatchers.has(watcherKey)) {\n console.log('Adding active watcher for ' + watcherKey)\n\n try {\n const unwatch = this.publicClient.watchContractEvent({\n address,\n abi,\n eventName: eventType as string,\n fromBlock: this.config.fromBlock,\n onLogs(logs: Log[]) {\n for (let i = 0; i < logs.length; i++) {\n const log = logs[i]\n if (!log) {\n console.log('warning: Log was falsy when a log was expected!')\n break\n }\n const event: EnclaveEvent<T> = {\n type: eventType,\n data: (log as unknown as { args: unknown }).args as T extends EnclaveEventType\n ? EnclaveEventData[T]\n : T extends RegistryEventType\n ? RegistryEventData[T]\n : unknown,\n log,\n timestamp: new Date(),\n blockNumber: log.blockNumber ?? BigInt(0),\n transactionHash: log.transactionHash ?? '0x',\n }\n console.log('Created event, now emitting event...')\n emitter.emit(event)\n console.log('Event emitted')\n }\n },\n })\n\n this.activeWatchers.set(watcherKey, unwatch)\n } catch (error) {\n throw new SDKError(`Failed to watch contract event ${eventType} on ${address}: ${error}`, 'WATCH_EVENT_FAILED')\n }\n }\n }\n\n /**\n * Listen to all logs from a specific address\n */\n public async watchLogs(address: `0x${string}`, callback: (log: Log) => void): Promise<void> {\n const watcherKey = `logs:${address}`\n\n if (!this.activeWatchers.has(watcherKey)) {\n try {\n const unwatch = this.publicClient.watchEvent({\n address,\n onLogs: (logs: Log[]) => {\n logs.forEach((log: Log) => {\n callback(log)\n })\n },\n })\n\n this.activeWatchers.set(watcherKey, unwatch)\n } catch (error) {\n throw new SDKError(`Failed to watch logs for address ${address}: ${error}`, 'WATCH_LOGS_FAILED')\n }\n }\n }\n\n /**\n * Start polling for historical events\n */\n public async startPolling(): Promise<void> {\n if (this.isPolling) return\n\n this.isPolling = true\n\n try {\n this.lastBlockNumber = await this.publicClient.getBlockNumber()\n\n void this.pollForEvents()\n } catch (error) {\n this.isPolling = false\n throw new SDKError(`Failed to start polling: ${error}`, 'POLLING_START_FAILED')\n }\n }\n\n /**\n * Stop polling for events\n */\n public stopPolling(): void {\n this.isPolling = false\n }\n\n /**\n * Get historical events\n */\n public async getHistoricalEvents(\n address: `0x${string}`,\n eventType: AllEventTypes,\n abi: Abi,\n fromBlock?: bigint,\n toBlock?: bigint,\n ): Promise<Log[]> {\n try {\n const logs = await this.publicClient.getContractEvents({\n address,\n abi,\n eventName: eventType as string,\n fromBlock: fromBlock || this.config.fromBlock,\n toBlock: toBlock || this.config.toBlock,\n })\n\n return logs\n } catch (error) {\n throw new SDKError(`Failed to get historical events: ${error}`, 'HISTORICAL_EVENTS_FAILED')\n }\n }\n\n /**\n * SDKEventEmitter implementation\n */\n public on<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n if (!this.listeners.has(eventType)) {\n this.listeners.set(eventType, new Set())\n }\n this.listeners.get(eventType)!.add(callback as EventCallback)\n }\n\n public off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n const callbacks = this.listeners.get(eventType)\n if (callbacks) {\n callbacks.delete(callback as EventCallback)\n if (callbacks.size === 0) {\n this.listeners.delete(eventType)\n // Find and stop corresponding watchers\n const watchersToRemove: string[] = []\n this.activeWatchers.forEach((unwatch, key) => {\n if (key.endsWith(`:${eventType}`)) {\n try {\n unwatch()\n } catch (error) {\n console.error(`Error unwatching event ${eventType}:`, error)\n }\n watchersToRemove.push(key)\n }\n })\n watchersToRemove.forEach((key) => this.activeWatchers.delete(key))\n }\n }\n }\n\n public emit<T extends AllEventTypes>(event: EnclaveEvent<T>): void {\n console.log('emit() called for ' + event.type)\n const callbacks = this.listeners.get(event.type)\n if (callbacks) {\n console.log('Have ' + callbacks.size + ' callbacks')\n callbacks.forEach((callback) => {\n console.log('Running callback...')\n try {\n void (callback as EventCallback<T>)(event)\n } catch (error) {\n console.error(`Error in event callback for ${event.type}:`, error)\n }\n })\n }\n }\n\n /**\n * Clean up all listeners and watchers\n */\n public cleanup(): void {\n this.stopPolling()\n\n // Stop all active watchers\n this.activeWatchers.forEach((unwatch) => {\n try {\n unwatch()\n } catch (error) {\n console.error('Error unwatching during cleanup:', error)\n }\n })\n this.activeWatchers.clear()\n\n // Clear all listeners\n this.listeners.clear()\n }\n\n private async pollForEvents(): Promise<void> {\n while (this.isPolling) {\n try {\n const currentBlock = await this.publicClient.getBlockNumber()\n\n if (currentBlock > this.lastBlockNumber) {\n this.lastBlockNumber = currentBlock\n }\n\n await sleep(this.config.pollingInterval || 5000)\n } catch (error) {\n console.error('Error during polling:', error)\n await sleep(this.config.pollingInterval || 5000)\n }\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 { Log, PublicClient, WalletClient } from 'viem'\nimport type { ProofData } from '@aztec/bb.js'\nimport type { CiphernodeRegistryOwnable, Enclave, MockCiphernodeRegistry, MockUSDC, EnclaveToken } from '@enclave-e3/contracts/types'\n\nimport type { CircuitInputs } from './greco'\n\n/**\n * SDK configuration\n */\nexport interface SDKConfig {\n /**\n * The public client to use to interact with the blockchain\n */\n publicClient: PublicClient\n\n /**\n * The wallet client to use to send/sign transactions\n */\n walletClient?: WalletClient\n\n /**\n * The Enclave contracts\n */\n contracts: {\n /**\n * The Enclave contract address\n */\n enclave: `0x${string}`\n\n /**\n * The CiphernodeRegistry contract address\n */\n ciphernodeRegistry: `0x${string}`\n\n /**\n * The FeeToken contract address\n */\n feeToken: `0x${string}`\n }\n\n /**\n * The chain ID to which the contracts are deployed\n */\n chainId?: number\n\n /**\n * The protocol to use for the Enclave requests\n */\n protocol: FheProtocol\n\n /**\n * The protocol parameters to use for the Enclave requests\n */\n protocolParams?: ProtocolParams\n}\n\nexport interface EventListenerConfig {\n fromBlock?: bigint\n toBlock?: bigint\n polling?: boolean\n pollingInterval?: number\n}\n\nexport interface ContractInstances {\n enclave: Enclave\n ciphernodeRegistry: CiphernodeRegistryOwnable | MockCiphernodeRegistry\n feeToken: EnclaveToken | MockUSDC\n}\n\n// Unified Event System\nexport enum EnclaveEventType {\n // E3 Lifecycle Events\n E3_REQUESTED = 'E3Requested',\n E3_ACTIVATED = 'E3Activated',\n CIPHERTEXT_OUTPUT_PUBLISHED = 'CiphertextOutputPublished',\n PLAINTEXT_OUTPUT_PUBLISHED = 'PlaintextOutputPublished',\n\n // E3 Program Management\n E3_PROGRAM_ENABLED = 'E3ProgramEnabled',\n E3_PROGRAM_DISABLED = 'E3ProgramDisabled',\n\n // Encryption Scheme Management\n ENCRYPTION_SCHEME_ENABLED = 'EncryptionSchemeEnabled',\n ENCRYPTION_SCHEME_DISABLED = 'EncryptionSchemeDisabled',\n\n // Configuration\n CIPHERNODE_REGISTRY_SET = 'CiphernodeRegistrySet',\n MAX_DURATION_SET = 'MaxDurationSet',\n ALLOWED_E3_PROGRAMS_PARAMS_SET = 'AllowedE3ProgramsParamsSet',\n\n // Ownership\n OWNERSHIP_TRANSFERRED = 'OwnershipTransferred',\n INITIALIZED = 'Initialized',\n}\n\nexport enum RegistryEventType {\n // Committee Management\n COMMITTEE_REQUESTED = 'CommitteeRequested',\n COMMITTEE_PUBLISHED = 'CommitteePublished',\n COMMITTEE_FINALIZED = 'CommitteeFinalized',\n\n // Configuration\n ENCLAVE_SET = 'EnclaveSet',\n\n // Ownership\n OWNERSHIP_TRANSFERRED = 'OwnershipTransferred',\n INITIALIZED = 'Initialized',\n}\n\n// Union type for all events\nexport type AllEventTypes = EnclaveEventType | RegistryEventType\n\n// Event data interfaces based on TypeChain types\nexport interface E3 {\n seed: bigint\n threshold: readonly [number, number]\n requestBlock: bigint\n startWindow: readonly [bigint, bigint]\n duration: bigint\n expiration: bigint\n encryptionSchemeId: string\n e3Program: string\n e3ProgramParams: string\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n plaintextOutput: string\n}\n\nexport interface E3RequestedData {\n e3Id: bigint\n e3: E3\n filter: string\n e3Program: string\n}\n\nexport interface E3ActivatedData {\n e3Id: bigint\n expiration: bigint\n committeePublicKey: string\n}\n\nexport interface CiphertextOutputPublishedData {\n e3Id: bigint\n ciphertextOutput: string\n}\n\nexport interface PlaintextOutputPublishedData {\n e3Id: bigint\n plaintextOutput: string\n}\n\nexport interface CiphernodeAddedData {\n node: string\n index: bigint\n numNodes: bigint\n size: bigint\n}\n\nexport interface CiphernodeRemovedData {\n node: string\n index: bigint\n numNodes: bigint\n size: bigint\n}\n\nexport interface CommitteeRequestedData {\n e3Id: bigint\n seed: bigint\n threshold: [bigint, bigint]\n requestBlock: bigint\n submissionDeadline: bigint\n}\n\nexport interface CommitteePublishedData {\n e3Id: bigint\n publicKey: string\n}\n\nexport interface CommitteeFinalizedData {\n e3Id: bigint\n nodes: string[]\n}\n\n// Event data mapping\nexport interface EnclaveEventData {\n [EnclaveEventType.E3_REQUESTED]: E3RequestedData\n [EnclaveEventType.E3_ACTIVATED]: E3ActivatedData\n [EnclaveEventType.CIPHERTEXT_OUTPUT_PUBLISHED]: CiphertextOutputPublishedData\n [EnclaveEventType.PLAINTEXT_OUTPUT_PUBLISHED]: PlaintextOutputPublishedData\n [EnclaveEventType.E3_PROGRAM_ENABLED]: { e3Program: string }\n [EnclaveEventType.E3_PROGRAM_DISABLED]: { e3Program: string }\n [EnclaveEventType.ENCRYPTION_SCHEME_ENABLED]: { encryptionSchemeId: string }\n [EnclaveEventType.ENCRYPTION_SCHEME_DISABLED]: { encryptionSchemeId: string }\n [EnclaveEventType.CIPHERNODE_REGISTRY_SET]: { ciphernodeRegistry: string }\n [EnclaveEventType.MAX_DURATION_SET]: { maxDuration: bigint }\n [EnclaveEventType.ALLOWED_E3_PROGRAMS_PARAMS_SET]: {\n e3ProgramParams: string[]\n }\n [EnclaveEventType.OWNERSHIP_TRANSFERRED]: {\n previousOwner: string\n newOwner: string\n }\n [EnclaveEventType.INITIALIZED]: { version: bigint }\n}\n\nexport interface RegistryEventData {\n [RegistryEventType.COMMITTEE_REQUESTED]: CommitteeRequestedData\n [RegistryEventType.COMMITTEE_PUBLISHED]: CommitteePublishedData\n [RegistryEventType.COMMITTEE_FINALIZED]: CommitteeFinalizedData\n [RegistryEventType.ENCLAVE_SET]: { enclave: string }\n [RegistryEventType.OWNERSHIP_TRANSFERRED]: {\n previousOwner: string\n newOwner: string\n }\n [RegistryEventType.INITIALIZED]: { version: bigint }\n}\n\n// Generic event structure\nexport interface EnclaveEvent<T extends AllEventTypes> {\n type: T\n data: T extends EnclaveEventType ? EnclaveEventData[T] : T extends RegistryEventType ? RegistryEventData[T] : unknown\n log: Log\n timestamp: Date\n blockNumber: bigint\n transactionHash: string\n}\n\nexport type EventCallback<T extends AllEventTypes = AllEventTypes> = (event: EnclaveEvent<T>) => void | Promise<void>\n\nexport interface EventFilter<T = unknown> {\n address?: `0x${string}`\n fromBlock?: bigint\n toBlock?: bigint\n args?: Partial<T>\n}\n\nexport interface SDKEventEmitter {\n on<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void\n off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void\n emit<T extends AllEventTypes>(event: EnclaveEvent<T>): void\n}\n\n/**\n * Result of verifiable encryption using BFV\n */\nexport interface VerifiableEncryptionResult {\n /**\n * The encrypted data\n */\n encryptedData: Uint8Array\n /**\n * The proof generated by Greco\n */\n proof: ProofData\n}\n\n/**\n * The protocol to use for the Enclave requests\n */\nexport enum FheProtocol {\n /**\n * The BFV protocol\n */\n BFV = 'BFV',\n /**\n * The TrBFV protocol\n */\n TRBFV = 'TRBFV',\n}\n\n/**\n * Protocol parameters for an Enclave program request\n * Example for BFV\n * 2048, // degree\n * 1032193, // plaintext_modulus\n * 0x3FFFFFFF000001, // moduli\n */\nexport interface ProtocolParams {\n /**\n * The degree of the polynomial\n */\n degree: number\n /**\n * The plaintext modulus\n */\n plaintextModulus: bigint\n /**\n * The moduli\n */\n moduli: bigint[]\n /**\n * error1\n */\n error1Variance: string | undefined\n}\n\nexport type ProtocolParamsName =\n | 'INSECURE_SET_2048_1032193_1'\n | 'INSECURE_SET_512_10_1'\n | 'INSECURE_SET_512_0XFFFFEE001_1'\n | 'SET_8192_1000_4'\n | 'SET_8192_144115188075855872_2'\n\n/**\n * Parameters for the BFV protocol\n */\nexport const BfvProtocolParams = {\n /**\n * Recommended parameters for BFV protocol\n * - Degree: 2048\n * - Plaintext modulus: 1032193\n * - Moduli:0x3FFFFFFF000001\n */\n BFV_NORMAL: {\n degree: 2048,\n plaintextModulus: 1032193n,\n moduli: [0x3fffffff000001n],\n error1Variance: '10',\n } as const satisfies ProtocolParams,\n\n /**\n * Recommended parameters for TrBFV protocol\n * - Degree: 8192\n * - Plaintext modulus: 1000\n * - Moduli: [0x00800000022a0001, 0x00800000021a0001, 0x0080000002120001, 0x0080000001f60001]\n */\n BFV_THRESHOLD: {\n degree: 8192,\n plaintextModulus: 1000n,\n moduli: [0x00800000022a0001n, 0x00800000021a0001n, 0x0080000002120001n, 0x0080000001f60001n],\n error1Variance: '10',\n } as const satisfies ProtocolParams,\n}\n\n/**\n * The result of encrypting a value and generating a proof\n */\nexport interface EncryptedValueAndPublicInputs {\n /**\n * The encrypted data\n */\n encryptedData: Uint8Array\n\n /**\n * The public inputs for the proof\n */\n publicInputs: CircuitInputs\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 { UltraHonkBackend, type ProofData } from '@aztec/bb.js'\nimport { type CompiledCircuit, Noir } from '@noir-lang/noir_js'\n\n// Conversion to Noir types\nexport type Field = string\n\n/**\n * Describes a polynomial to be used in a Noir circuit (Greco)\n */\nexport type Polynomial = {\n coefficients: Field[]\n}\n\n/**\n * Describes the inputs to Greco circuit\n */\nexport interface CircuitInputs {\n pk0is: string[][]\n pk1is: string[][]\n ct0is: string[][]\n ct1is: string[][]\n u: string[]\n e0: string[]\n e1: string[]\n e0is: string[][]\n k1: string[]\n r1is: string[][]\n r2is: string[][]\n p1is: string[][]\n p2is: string[][]\n}\n\n/**\n * BfvPkEncryption params for Greco\npub struct Params<let N: u32, let L: u32> {\n crypto: CryptographicParams<L>,\n bounds: BoundParams<L>,\n}\n */\nexport interface BoundParams {\n pk_bounds: Field[]\n e0_bound: Field\n e1_bound: Field\n u_bound: Field\n r1_low_bounds: Field[]\n r1_up_bounds: Field[]\n r2_bounds: Field[]\n p1_bounds: Field[]\n p2_bounds: Field[]\n k1_low_bound: Field\n k1_up_bound: Field\n}\n\nexport interface CryptographicParams {\n q_mod_t: Field\n qis: Field[]\n k0is: Field[]\n}\n\nexport interface Params {\n bounds: BoundParams\n crypto: CryptographicParams\n}\n\n/**\n * Default greco params for BFV pk encryption.\n */\nexport const defaultParams: Params = {\n bounds: {\n pk_bounds: ['34359701504', '34359615488'],\n e0_bound: '20',\n e1_bound: '20',\n u_bound: '1',\n r1_low_bounds: ['261', '258'],\n r1_up_bounds: ['260', '258'],\n r2_bounds: ['34359701504', '34359615488'],\n p1_bounds: ['256', '256'],\n p2_bounds: ['34359701504', '34359615488'],\n k1_low_bound: '5',\n k1_up_bound: '4',\n },\n crypto: {\n q_mod_t: '3',\n qis: ['68719403009', '68719230977'],\n k0is: ['61847462708', '20615769293'],\n },\n}\n\n/**\n * Convert a string array to a polynomial\n * @param stringArray - The string array\n * @returns The polynomial\n */\nexport const convertToPolynomial = (stringArray: string[]): Polynomial => {\n return {\n coefficients: stringArray,\n }\n}\n\n/**\n * Convert an array of string arrays to an array of polynomials\n * @param stringArrays - The array of string arrays\n * @returns The array of polynomials\n */\nexport const convertToPolynomialArray = (stringArrays: string[][]): Polynomial[] => {\n return stringArrays.map(convertToPolynomial)\n}\n\n/**\n * Generate a proof for a given circuit and circuit inputs\n * @dev Defaults to the UltraHonkBackend\n * @param circuitInputs - The circuit inputs\n * @param circuit - The circuit\n * @returns The proof\n */\nexport const generateProof = async (circuitInputs: CircuitInputs, circuit: CompiledCircuit): Promise<ProofData> => {\n const noir = new Noir(circuit)\n\n const backend = new UltraHonkBackend(circuit.bytecode, { threads: 4 })\n\n const pk0is_poly = convertToPolynomialArray(circuitInputs.pk0is)\n const pk1is_poly = convertToPolynomialArray(circuitInputs.pk1is)\n const ct0is_poly = convertToPolynomialArray(circuitInputs.ct0is)\n const ct1is_poly = convertToPolynomialArray(circuitInputs.ct1is)\n const u_poly = convertToPolynomial(circuitInputs.u)\n const e0_poly = convertToPolynomial(circuitInputs.e0)\n const e1_poly = convertToPolynomial(circuitInputs.e1)\n const e0is_poly = convertToPolynomialArray(circuitInputs.e0is)\n const k1_poly = convertToPolynomial(circuitInputs.k1)\n const r1is_poly = convertToPolynomialArray(circuitInputs.r1is)\n const r2is_poly = convertToPolynomialArray(circuitInputs.r2is)\n const p1is_poly = convertToPolynomialArray(circuitInputs.p1is)\n const p2is_poly = convertToPolynomialArray(circuitInputs.p2is)\n\n const { witness } = await noir.execute({\n params: defaultParams as any,\n pk0is: pk0is_poly,\n pk1is: pk1is_poly,\n ct0is: ct0is_poly,\n ct1is: ct1is_poly,\n u: u_poly,\n e0: e0_poly,\n e1: e1_poly,\n e0is: e0is_poly,\n k1: k1_poly,\n r1is: r1is_poly,\n r2is: r2is_poly,\n p1is: p1is_poly,\n p2is: p2is_poly,\n })\n\n return await backend.generateProof(witness, { keccakZK: true })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,IAAAA,eAAmI;AACnI,sBAAoC;AACpC,oBAAwD;AACxD,kBA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AI,UAAU,WAAW;AACvB,WAAK,OAAO,YAAY;AAAA,QACtB,GAAG,KAAK,OAAO;AAAA,QACf,GAAG,UAAU;AAAA,MACf;AAAA,IACF;AAEA,QAAI,UAAU,SAAS;AACrB,WAAK,OAAO,UAAU,UAAU;AAAA,IAClC;AAEA,SAAK,iBAAiB,IAAI,eAAe,KAAK,OAAO,cAAc,KAAK,OAAO,cAAc,KAAK,OAAO,SAAS;AAElH,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,OAAc,OAAO,SAWN;AACb,UAAM,QAAQ,YAAW,OAAO,QAAQ,OAAO;AAE/C,UAAM,cAAc,QAAQ,OAAO,WAAW,OAAO,KAAK,QAAQ,OAAO,WAAW,QAAQ;AAC5F,UAAM,YAAY,kBACd,wBAAU,QAAQ,QAAQ;AAAA,MACxB,WAAW,EAAE,UAAU,IAAO;AAAA,MAC9B,WAAW,EAAE,UAAU,GAAG,OAAO,IAAM;AAAA,IACzC,CAAC,QACD,mBAAK,QAAQ,MAAM;AACvB,UAAM,mBAAe,iCAAmB;AAAA,MACtC;AAAA,MACA;AAAA,IACF,CAAC;AACD,QAAI,eAAyC;AAC7C,QAAI,QAAQ,YAAY;AACtB,YAAM,cAAU,qCAAoB,QAAQ,UAAU;AACtD,yBAAe,iCAAmB;AAAA,QAChC;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAEA,WAAO,IAAI,YAAW;AAAA,MACpB;AAAA,MACA;AAAA,MACA,WAAW,QAAQ;AAAA,MACnB,SAAS,QAAQ;AAAA,MACjB,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;","names":["import_viem","import_types","EnclaveEventType","RegistryEventType","FheProtocol","initializeWasm"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/enclave-sdk.ts","../src/contract-client.ts","../src/utils.ts","../src/event-listener.ts","../src/types.ts","../src/greco.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\n// Main SDK class\nexport { EnclaveSDK } from './enclave-sdk'\n\n// Core classes\nexport { EventListener } from './event-listener'\nexport { ContractClient } from './contract-client'\n\n// Types and interfaces\nexport type {\n E3,\n SDKConfig,\n EventListenerConfig,\n ContractInstances,\n EventFilter,\n EventCallback,\n SDKEventEmitter,\n AllEventTypes,\n EnclaveEvent,\n // Event data types\n E3RequestedData,\n E3ActivatedData,\n CiphertextOutputPublishedData,\n PlaintextOutputPublishedData,\n CiphernodeAddedData,\n CiphernodeRemovedData,\n CommitteeRequestedData,\n CommitteePublishedData,\n CommitteeFinalizedData,\n EnclaveEventData,\n RegistryEventData,\n BfvParams,\n VerifiableEncryptionResult,\n EncryptedValueAndPublicInputs,\n} from './types'\n\n// enums and constants\nexport { EnclaveEventType, RegistryEventType, ThresholdBfvParamsPresetName, ThresholdBfvParamsPresetNames } from './types'\n\n// Export utilities\nexport {\n SDKError,\n isValidAddress,\n isValidHash,\n formatEventName,\n parseEventData,\n formatBigInt,\n parseBigInt,\n generateEventId,\n sleep,\n getCurrentTimestamp,\n // BFV and E3 utilities\n DEFAULT_COMPUTE_PROVIDER_PARAMS,\n DEFAULT_E3_CONFIG,\n encodeBfvParams,\n encodeComputeProviderParams,\n encodeCustomParams,\n calculateStartWindow,\n decodePlaintextOutput,\n type ComputeProviderParams,\n} from './utils'\n\nexport { generateProof, type Polynomial } from './greco'\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 Abi, type Hash, type Log, PublicClient, WalletClient, createPublicClient, createWalletClient, http, webSocket } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { hardhat, mainnet, monadTestnet, sepolia } from 'viem/chains'\nimport initializeWasm from '@enclave-e3/wasm/init'\n\nimport { CiphernodeRegistryOwnable__factory, Enclave__factory } from '@enclave-e3/contracts/types'\nimport { ContractClient } from './contract-client'\nimport { EventListener } from './event-listener'\nimport { EnclaveEventType, ThresholdBfvParamsPresetNames } from './types'\nimport { SDKError, isValidAddress } from './utils'\n\nimport type {\n AllEventTypes,\n E3,\n EventCallback,\n SDKConfig,\n BfvParams,\n VerifiableEncryptionResult,\n EncryptedValueAndPublicInputs,\n ThresholdBfvParamsPresetName,\n} from './types'\nimport {\n bfv_encrypt_number,\n bfv_encrypt_vector,\n generate_public_key,\n bfv_verifiable_encrypt_number,\n bfv_verifiable_encrypt_vector,\n compute_pk_commitment,\n get_bfv_params,\n} from '@enclave-e3/wasm'\nimport { generateProof } from './greco'\nimport { CompiledCircuit } from '@noir-lang/noir_js'\n\nexport class EnclaveSDK {\n public static readonly chains = {\n 1: mainnet,\n 11155111: sepolia,\n 41454: monadTestnet,\n 31337: hardhat,\n } as const\n\n private eventListener: EventListener\n private contractClient: ContractClient\n private initialized = false\n private thresholdBfvParamsPresetName?: ThresholdBfvParamsPresetName\n private publicClient: PublicClient\n\n // TODO: use zod for config validation\n constructor(private config: SDKConfig) {\n if (!config.publicClient) {\n throw new SDKError('Public client is required', 'MISSING_PUBLIC_CLIENT')\n }\n\n if (!isValidAddress(config.contracts.enclave)) {\n throw new SDKError('Invalid Enclave contract address', 'INVALID_ADDRESS')\n }\n\n if (!isValidAddress(config.contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n\n if (!isValidAddress(config.contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n if (!config.thresholdBfvParamsPresetName) {\n throw new SDKError('Threshold BFV parameters preset name is required', 'MISSING_THRESHOLD_BFV_PARAMS_PRESET_NAME')\n }\n\n if (!Object.values(ThresholdBfvParamsPresetNames).includes(config.thresholdBfvParamsPresetName)) {\n throw new SDKError(\n `Invalid threshold BFV parameters preset name: ${config.thresholdBfvParamsPresetName}`,\n 'INVALID_THRESHOLD_BFV_PARAMS_PRESET_NAME',\n )\n }\n\n this.thresholdBfvParamsPresetName = config.thresholdBfvParamsPresetName\n this.eventListener = new EventListener(config.publicClient)\n this.contractClient = new ContractClient(config.publicClient, config.walletClient, config.contracts)\n this.publicClient = config.publicClient\n }\n\n /**\n * Initialize the SDK\n */\n // TODO: Delete this it is redundant\n public async initialize(): Promise<void> {\n if (this.initialized) return\n\n try {\n await this.contractClient.initialize()\n this.initialized = true\n } catch (error) {\n throw new SDKError(`Failed to initialize SDK: ${error}`, 'SDK_INITIALIZATION_FAILED')\n }\n }\n\n /**\n * Get the public client used by the SDK\n * @returns The public client\n */\n public getPublicClient = (): PublicClient => {\n return this.publicClient\n }\n\n public async getThresholdBfvParamsSet(): Promise<BfvParams> {\n await initializeWasm()\n let params = get_bfv_params(this.thresholdBfvParamsPresetName as ThresholdBfvParamsPresetName)\n return {\n degree: Number(params.degree), // degree is returned as a bigint from wasm\n plaintextModulus: params.plaintext_modulus as bigint,\n moduli: params.moduli as bigint[],\n error1Variance: params.error1_variance,\n }\n }\n\n public async generatePublicKey(): Promise<Uint8Array> {\n await initializeWasm()\n const protocolParams = await this.getThresholdBfvParamsSet()\n return generate_public_key(protocolParams.degree, protocolParams.plaintextModulus, BigUint64Array.from(protocolParams.moduli))\n }\n\n public async computePublicKeyCommitment(publicKey: Uint8Array): Promise<Uint8Array> {\n await initializeWasm()\n const protocolParams = await this.getThresholdBfvParamsSet()\n\n return compute_pk_commitment(\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n }\n\n /**\n * Encrypt a number using the configured protocol\n * @param data - The number to encrypt\n * @param publicKey - The public key to use for encryption\n * @returns The encrypted number\n */\n public async encryptNumber(data: bigint, publicKey: Uint8Array): Promise<Uint8Array> {\n await initializeWasm()\n const protocolParams = await this.getThresholdBfvParamsSet()\n\n return bfv_encrypt_number(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n }\n\n /**\n * Encrypt a vector using the configured protocol\n * @param data - The vector to encrypt\n * @param publicKey - The public key to use for encryption\n * @returns The ciphertext\n */\n public async encryptVector(data: BigUint64Array, publicKey: Uint8Array): Promise<Uint8Array> {\n await initializeWasm()\n const protocolParams = await this.getThresholdBfvParamsSet()\n\n return bfv_encrypt_vector(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n }\n\n /**\n * This function encrypts a number using the configured FHE protocol\n * and generates the necessary public inputs for a zk-SNARK proof.\n * @param data The number to encrypt\n * @param publicKey The public key to use for encryption\n * @returns The encrypted number and the inputs for the zk-SNARK proof\n */\n public async encryptNumberAndGenInputs(data: bigint, publicKey: Uint8Array): Promise<EncryptedValueAndPublicInputs> {\n await initializeWasm()\n const protocolParams = await this.getThresholdBfvParamsSet()\n\n const [encryptedData, circuitInputs] = bfv_verifiable_encrypt_number(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n\n return {\n encryptedData,\n circuitInputs: JSON.parse(circuitInputs),\n }\n }\n\n /**\n * Encrypt a number using the configured protocol and generate a zk-SNARK proof using Greco\n * @param data - The number to encrypt\n * @param publicKey - The public key to use for encryption\n * @param circuit - The circuit to use for proof generation\n * @returns The encrypted number and the proof\n */\n public async encryptNumberAndGenProof(\n data: bigint,\n publicKey: Uint8Array,\n circuit: CompiledCircuit,\n ): Promise<VerifiableEncryptionResult> {\n const { circuitInputs: publicInputs, encryptedData } = await this.encryptNumberAndGenInputs(data, publicKey)\n const proof = await generateProof(publicInputs, circuit)\n\n return {\n encryptedData,\n proof,\n }\n }\n\n /**\n * Encrypt a vector and generate inputs for an E3 computation\n * @param data - The vector to encrypt\n * @param publicKey - The public key to use for encryption\n * @returns The encrypted vector and the inputs for the E3 computation\n */\n public async encryptVectorAndGenInputs(data: BigUint64Array, publicKey: Uint8Array): Promise<EncryptedValueAndPublicInputs> {\n await initializeWasm()\n const protocolParams = await this.getThresholdBfvParamsSet()\n\n const [encryptedData, circuitInputs] = bfv_verifiable_encrypt_vector(\n data,\n publicKey,\n protocolParams.degree,\n protocolParams.plaintextModulus,\n BigUint64Array.from(protocolParams.moduli),\n )\n\n return {\n encryptedData,\n circuitInputs: JSON.parse(circuitInputs),\n }\n }\n\n /**\n * Encrypt a vector using the configured protocol and generate a zk-SNARK proof using Greco\n * @param data - The vector to encrypt\n * @param publicKey - The public key to use for encryption\n * @param circuit - The circuit to use for proof generation\n * @returns The encrypted vector and the proof\n */\n public async encryptVectorAndGenProof(\n data: BigUint64Array,\n publicKey: Uint8Array,\n circuit: CompiledCircuit,\n ): Promise<VerifiableEncryptionResult> {\n const { circuitInputs: publicInputs, encryptedData } = await this.encryptVectorAndGenInputs(data, publicKey)\n\n const proof = await generateProof(publicInputs, circuit)\n\n return {\n encryptedData,\n proof,\n }\n }\n\n /**\n * Approve the fee token for the Enclave\n * @param amount - The amount to approve\n * @returns The approval transaction hash\n */\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n console.log('>>> APPROVE FEE TOKEN')\n\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.approveFeeToken(amount)\n }\n\n /**\n * Request a new E3 computation\n */\n public async requestE3(params: {\n threshold: [number, number]\n startWindow: [bigint, bigint]\n duration: bigint\n e3Program: `0x${string}`\n e3ProgramParams: `0x${string}`\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n gasLimit?: bigint\n }): Promise<Hash> {\n console.log('>>> REQUEST')\n\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.requestE3(\n params.threshold,\n params.startWindow,\n params.duration,\n params.e3Program,\n params.e3ProgramParams,\n params.computeProviderParams,\n params.customParams,\n params.gasLimit,\n )\n }\n\n /**\n * Get the public key for an E3 computation\n * @param e3Id - The ID of the E3 computation\n * @returns The public key\n */\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.getE3PublicKey(e3Id)\n }\n\n /**\n * Activate an E3 computation\n */\n public async activateE3(e3Id: bigint, gasLimit?: bigint): Promise<Hash> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.activateE3(e3Id, gasLimit)\n }\n\n /**\n * Publish input for an E3 computation\n */\n public async publishInput(e3Id: bigint, data: `0x${string}`, gasLimit?: bigint): Promise<Hash> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.publishInput(e3Id, data, gasLimit)\n }\n\n /**\n * Publish ciphertext output for an E3 computation\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.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.publishCiphertextOutput(e3Id, ciphertextOutput, proof, gasLimit)\n }\n\n /**\n * Get E3 information\n */\n public async getE3(e3Id: bigint): Promise<E3> {\n if (!this.initialized) {\n await this.initialize()\n }\n\n return this.contractClient.getE3(e3Id)\n }\n\n /**\n * Unified Event Listening - Listen to any Enclave or Registry event\n */\n public onEnclaveEvent<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n // Determine which contract to listen to based on event type\n const isEnclaveEvent = Object.values(EnclaveEventType).includes(eventType as EnclaveEventType)\n const contractAddress = isEnclaveEvent ? this.config.contracts.enclave : this.config.contracts.ciphernodeRegistry\n const abi = isEnclaveEvent ? Enclave__factory.abi : CiphernodeRegistryOwnable__factory.abi\n\n void this.eventListener.watchContractEvent(contractAddress, eventType, abi, callback)\n }\n\n /**\n * Remove event listener\n */\n public off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n this.eventListener.off(eventType, callback)\n }\n\n /**\n * Handle an event only once\n */\n public once<T extends AllEventTypes>(type: T, callback: EventCallback<T>): void {\n const handler: EventCallback<T> = (event) => {\n this.off(type, handler)\n const prom = callback(event)\n if (prom) {\n prom.catch((e) => console.log(e))\n }\n }\n this.onEnclaveEvent(type, handler)\n }\n\n /**\n * Get historical events\n */\n public async getHistoricalEvents(eventType: AllEventTypes, fromBlock?: bigint, toBlock?: bigint): Promise<Log[]> {\n const isEnclaveEvent = Object.values(EnclaveEventType).includes(eventType as EnclaveEventType)\n const contractAddress = isEnclaveEvent ? this.config.contracts.enclave : this.config.contracts.ciphernodeRegistry\n const abi = isEnclaveEvent ? Enclave__factory.abi : CiphernodeRegistryOwnable__factory.abi\n\n return this.eventListener.getHistoricalEvents(contractAddress, eventType, abi, fromBlock, toBlock)\n }\n\n /**\n * Start polling for events\n */\n public async startEventPolling(): Promise<void> {\n void this.eventListener.startPolling()\n }\n\n /**\n * Stop polling for events\n */\n public stopEventPolling(): void {\n this.eventListener.stopPolling()\n }\n\n /**\n * Utility methods\n */\n\n /**\n * Estimate gas for a transaction\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 return this.contractClient.estimateGas(functionName, args, contractAddress, abi, value)\n }\n\n /**\n * Wait for transaction confirmation\n */\n public async waitForTransaction(hash: Hash): Promise<unknown> {\n return this.contractClient.waitForTransaction(hash)\n }\n\n /**\n * Clean up resources\n */\n public cleanup(): void {\n this.eventListener.cleanup()\n }\n\n /**\n * Update SDK configuration\n */\n // TODO: We should delete this as we don't want a stateful client.\n public updateConfig(newConfig: Partial<SDKConfig>): void {\n if (newConfig.publicClient) {\n this.config.publicClient = newConfig.publicClient\n this.eventListener = new EventListener(newConfig.publicClient)\n }\n\n if (newConfig.walletClient) {\n this.config.walletClient = newConfig.walletClient\n }\n\n if (newConfig.contracts) {\n this.config.contracts = {\n ...this.config.contracts,\n ...newConfig.contracts,\n }\n }\n\n if (newConfig.chainId) {\n this.config.chainId = newConfig.chainId\n }\n\n this.contractClient = new ContractClient(this.config.publicClient, this.config.walletClient, this.config.contracts)\n\n this.initialized = false\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: {\n enclave: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n }\n privateKey?: `0x${string}`\n chainId: keyof typeof EnclaveSDK.chains\n thresholdBfvParamsPresetName: ThresholdBfvParamsPresetName\n }): EnclaveSDK {\n const chain = EnclaveSDK.chains[options.chainId]\n\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 const publicClient = createPublicClient({\n chain,\n transport,\n }) as SDKConfig['publicClient']\n let walletClient: WalletClient | undefined = undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain,\n transport,\n })\n }\n\n return new EnclaveSDK({\n publicClient,\n walletClient,\n contracts: options.contracts,\n chainId: options.chainId,\n thresholdBfvParamsPresetName: options.thresholdBfvParamsPresetName,\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 { Abi, Hash, PublicClient, TransactionReceipt, WalletClient } from 'viem'\n\nimport { CiphernodeRegistryOwnable__factory, Enclave__factory, EnclaveToken__factory } from '@enclave-e3/contracts/types'\nimport { type E3 } from './types'\nimport { SDKError, isValidAddress } from './utils'\n\nexport class ContractClient {\n private contractInfo: {\n enclave: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n } | null = null\n\n constructor(\n private publicClient: PublicClient,\n private walletClient?: WalletClient,\n private addresses: {\n enclave: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n } = {\n enclave: '0x0000000000000000000000000000000000000000',\n ciphernodeRegistry: '0x0000000000000000000000000000000000000000',\n feeToken: '0x0000000000000000000000000000000000000000',\n },\n ) {\n if (!isValidAddress(addresses.enclave)) {\n throw new SDKError('Invalid Enclave contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(addresses.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(addresses.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n }\n\n /**\n * Initialize contract instances\n */\n public async initialize(): Promise<void> {\n try {\n this.contractInfo = {\n enclave: {\n address: this.addresses.enclave,\n abi: Enclave__factory.abi,\n },\n ciphernodeRegistry: {\n address: this.addresses.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: this.addresses.feeToken,\n abi: EnclaveToken__factory.abi,\n },\n }\n } catch (error) {\n throw new SDKError(`Failed to initialize contracts: ${error}`, 'INITIALIZATION_FAILED')\n }\n }\n\n /**\n * Approve the fee token for the Enclave\n * approve(address spender, uint256 amount)\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 if (!this.contractInfo) {\n await this.initialize()\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.addresses.feeToken,\n abi: EnclaveToken__factory.abi,\n functionName: 'approve',\n args: [this.addresses.enclave, amount],\n account,\n })\n\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n /**\n * Request a new E3 computation\n * request(address filter, uint32[2] threshold, uint256[2] startWindow, uint256 duration, IE3Program e3Program, bytes e3ProgramParams, bytes computeProviderParams, bytes customParams)\n */\n public async requestE3(\n threshold: [number, number],\n startWindow: [bigint, bigint],\n duration: bigint,\n e3Program: `0x${string}`,\n e3ProgramParams: `0x${string}`,\n computeProviderParams: `0x${string}`,\n customParams?: `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 if (!this.contractInfo) {\n await this.initialize()\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 // Simulate transaction\n const { request } = await this.publicClient.simulateContract({\n address: this.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'request',\n args: [\n {\n threshold,\n startWindow,\n duration,\n e3Program,\n e3ProgramParams,\n computeProviderParams,\n customParams: customParams || '0x',\n },\n ],\n account,\n gas: gasLimit,\n })\n\n // Execute transaction\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n /**\n * Activate an E3 computation\n * activate(uint256 e3Id)\n */\n public async activateE3(e3Id: bigint, gasLimit?: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n if (!this.contractInfo) {\n await this.initialize()\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.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'activate',\n args: [e3Id],\n account,\n gas: gasLimit,\n })\n\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to activate E3: ${error}`, 'ACTIVATE_E3_FAILED')\n }\n }\n\n /**\n * Publish input for an E3 computation\n * publishInput(uint256 e3Id, bytes memory data)\n */\n public async publishInput(e3Id: bigint, data: `0x${string}`, gasLimit?: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n if (!this.contractInfo) {\n await this.initialize()\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.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'publishInput',\n args: [e3Id, data],\n account,\n gas: gasLimit,\n })\n\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to publish input: ${error}`, 'PUBLISH_INPUT_FAILED')\n }\n }\n\n /**\n * Publish ciphertext output for an E3 computation\n * publishCiphertextOutput(uint256 e3Id, bytes memory ciphertextOutput, bytes memory proof)\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 if (!this.contractInfo) {\n await this.initialize()\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 // Simulate transaction\n const { request } = await this.publicClient.simulateContract({\n address: this.addresses.enclave,\n abi: Enclave__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, proof],\n account,\n gas: gasLimit,\n })\n\n // Execute transaction\n const hash = await this.walletClient.writeContract(request)\n\n return hash\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n /**\n * Get E3 information\n * Based on the contract: getE3(uint256 e3Id) returns (E3 memory e3)\n */\n public async getE3(e3Id: bigint): Promise<E3> {\n if (!this.contractInfo) {\n await this.initialize()\n }\n\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.addresses.enclave,\n abi: Enclave__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 /**\n * Get the public key for an E3 computation\n * Based on the contract: committeePublicKey(uint256 e3Id) returns (bytes32 publicKeyHash)\n * @param e3Id\n * @returns The public key\n */\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n if (!this.contractInfo) {\n await this.initialize()\n }\n\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.addresses.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 /**\n * Estimate gas for a transaction\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 const gas = await this.publicClient.estimateContractGas(estimateParams)\n\n return gas\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n /**\n * Wait for transaction confirmation\n */\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n\n return receipt\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, 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 */\nexport function getCurrentTimestamp(): number {\n return Math.floor(Date.now() / 1000)\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\nexport const DEFAULT_E3_CONFIG = {\n threshold_min: 2,\n threshold_max: 5,\n window_size: 120, // 2 minutes in seconds\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${'0'.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/**\n * Calculate start window for E3 request\n */\nexport function calculateStartWindow(windowSize: number = DEFAULT_E3_CONFIG.window_size): [bigint, bigint] {\n const now = getCurrentTimestamp()\n return [BigInt(now), BigInt(now + windowSize)]\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","// 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 Abi, type Log, type PublicClient } from 'viem'\n\nimport {\n type AllEventTypes,\n type EnclaveEvent,\n type EnclaveEventData,\n type EnclaveEventType,\n type EventCallback,\n type EventListenerConfig,\n type RegistryEventData,\n type RegistryEventType,\n type SDKEventEmitter,\n} from './types'\nimport { SDKError, sleep } from './utils'\n\nexport class EventListener implements SDKEventEmitter {\n private listeners: Map<AllEventTypes, Set<EventCallback>> = new Map()\n private activeWatchers: Map<string, () => void> = new Map()\n private isPolling = false\n private lastBlockNumber: bigint = BigInt(0)\n\n constructor(\n private publicClient: PublicClient,\n private config: EventListenerConfig = {},\n ) {}\n\n /**\n * Listen to specific contract events\n */\n public async watchContractEvent<T extends AllEventTypes>(\n address: `0x${string}`,\n eventType: T,\n abi: Abi,\n callback: EventCallback<T>,\n ): Promise<void> {\n const watcherKey = `${address}:${eventType}`\n console.log(`watchContractEvent: ${watcherKey}`)\n\n if (!this.listeners.has(eventType)) {\n this.listeners.set(eventType, new Set())\n }\n console.log('Added callback')\n this.listeners.get(eventType)!.add(callback as EventCallback)\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const emitter = this\n\n // If we don't have an active watcher for this event, create one\n if (!this.activeWatchers.has(watcherKey)) {\n console.log('Adding active watcher for ' + watcherKey)\n\n try {\n const unwatch = this.publicClient.watchContractEvent({\n address,\n abi,\n eventName: eventType as string,\n fromBlock: this.config.fromBlock,\n onLogs(logs: Log[]) {\n for (let i = 0; i < logs.length; i++) {\n const log = logs[i]\n if (!log) {\n console.log('warning: Log was falsy when a log was expected!')\n break\n }\n const event: EnclaveEvent<T> = {\n type: eventType,\n data: (log as unknown as { args: unknown }).args as T extends EnclaveEventType\n ? EnclaveEventData[T]\n : T extends RegistryEventType\n ? RegistryEventData[T]\n : unknown,\n log,\n timestamp: new Date(),\n blockNumber: log.blockNumber ?? BigInt(0),\n transactionHash: log.transactionHash ?? '0x',\n }\n console.log('Created event, now emitting event...')\n emitter.emit(event)\n console.log('Event emitted')\n }\n },\n })\n\n this.activeWatchers.set(watcherKey, unwatch)\n } catch (error) {\n throw new SDKError(`Failed to watch contract event ${eventType} on ${address}: ${error}`, 'WATCH_EVENT_FAILED')\n }\n }\n }\n\n /**\n * Listen to all logs from a specific address\n */\n public async watchLogs(address: `0x${string}`, callback: (log: Log) => void): Promise<void> {\n const watcherKey = `logs:${address}`\n\n if (!this.activeWatchers.has(watcherKey)) {\n try {\n const unwatch = this.publicClient.watchEvent({\n address,\n onLogs: (logs: Log[]) => {\n logs.forEach((log: Log) => {\n callback(log)\n })\n },\n })\n\n this.activeWatchers.set(watcherKey, unwatch)\n } catch (error) {\n throw new SDKError(`Failed to watch logs for address ${address}: ${error}`, 'WATCH_LOGS_FAILED')\n }\n }\n }\n\n /**\n * Start polling for historical events\n */\n public async startPolling(): Promise<void> {\n if (this.isPolling) return\n\n this.isPolling = true\n\n try {\n this.lastBlockNumber = await this.publicClient.getBlockNumber()\n\n void this.pollForEvents()\n } catch (error) {\n this.isPolling = false\n throw new SDKError(`Failed to start polling: ${error}`, 'POLLING_START_FAILED')\n }\n }\n\n /**\n * Stop polling for events\n */\n public stopPolling(): void {\n this.isPolling = false\n }\n\n /**\n * Get historical events\n */\n public async getHistoricalEvents(\n address: `0x${string}`,\n eventType: AllEventTypes,\n abi: Abi,\n fromBlock?: bigint,\n toBlock?: bigint,\n ): Promise<Log[]> {\n try {\n const logs = await this.publicClient.getContractEvents({\n address,\n abi,\n eventName: eventType as string,\n fromBlock: fromBlock || this.config.fromBlock,\n toBlock: toBlock || this.config.toBlock,\n })\n\n return logs\n } catch (error) {\n throw new SDKError(`Failed to get historical events: ${error}`, 'HISTORICAL_EVENTS_FAILED')\n }\n }\n\n /**\n * SDKEventEmitter implementation\n */\n public on<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n if (!this.listeners.has(eventType)) {\n this.listeners.set(eventType, new Set())\n }\n this.listeners.get(eventType)!.add(callback as EventCallback)\n }\n\n public off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void {\n const callbacks = this.listeners.get(eventType)\n if (callbacks) {\n callbacks.delete(callback as EventCallback)\n if (callbacks.size === 0) {\n this.listeners.delete(eventType)\n // Find and stop corresponding watchers\n const watchersToRemove: string[] = []\n this.activeWatchers.forEach((unwatch, key) => {\n if (key.endsWith(`:${eventType}`)) {\n try {\n unwatch()\n } catch (error) {\n console.error(`Error unwatching event ${eventType}:`, error)\n }\n watchersToRemove.push(key)\n }\n })\n watchersToRemove.forEach((key) => this.activeWatchers.delete(key))\n }\n }\n }\n\n public emit<T extends AllEventTypes>(event: EnclaveEvent<T>): void {\n console.log('emit() called for ' + event.type)\n const callbacks = this.listeners.get(event.type)\n if (callbacks) {\n console.log('Have ' + callbacks.size + ' callbacks')\n callbacks.forEach((callback) => {\n console.log('Running callback...')\n try {\n void (callback as EventCallback<T>)(event)\n } catch (error) {\n console.error(`Error in event callback for ${event.type}:`, error)\n }\n })\n }\n }\n\n /**\n * Clean up all listeners and watchers\n */\n public cleanup(): void {\n this.stopPolling()\n\n // Stop all active watchers\n this.activeWatchers.forEach((unwatch) => {\n try {\n unwatch()\n } catch (error) {\n console.error('Error unwatching during cleanup:', error)\n }\n })\n this.activeWatchers.clear()\n\n // Clear all listeners\n this.listeners.clear()\n }\n\n private async pollForEvents(): Promise<void> {\n while (this.isPolling) {\n try {\n const currentBlock = await this.publicClient.getBlockNumber()\n\n if (currentBlock > this.lastBlockNumber) {\n this.lastBlockNumber = currentBlock\n }\n\n await sleep(this.config.pollingInterval || 5000)\n } catch (error) {\n console.error('Error during polling:', error)\n await sleep(this.config.pollingInterval || 5000)\n }\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 { Log, PublicClient, WalletClient } from 'viem'\nimport type { ProofData } from '@aztec/bb.js'\nimport type { CiphernodeRegistryOwnable, Enclave, MockCiphernodeRegistry, MockUSDC, EnclaveToken } from '@enclave-e3/contracts/types'\n\nimport type { CircuitInputs } from './greco'\n\n/**\n * SDK configuration\n */\nexport interface SDKConfig {\n /**\n * The public client to use to interact with the blockchain\n */\n publicClient: PublicClient\n\n /**\n * The wallet client to use to send/sign transactions\n */\n walletClient?: WalletClient\n\n /**\n * The Enclave contracts\n */\n contracts: {\n /**\n * The Enclave contract address\n */\n enclave: `0x${string}`\n\n /**\n * The CiphernodeRegistry contract address\n */\n ciphernodeRegistry: `0x${string}`\n\n /**\n * The FeeToken contract address\n */\n feeToken: `0x${string}`\n }\n\n /**\n * The chain ID to which the contracts are deployed\n */\n chainId?: number\n\n /**\n * The threshold BFV parameters preset name to use for the Enclave requests\n */\n thresholdBfvParamsPresetName: ThresholdBfvParamsPresetName\n}\n\nexport interface EventListenerConfig {\n fromBlock?: bigint\n toBlock?: bigint\n polling?: boolean\n pollingInterval?: number\n}\n\nexport interface ContractInstances {\n enclave: Enclave\n ciphernodeRegistry: CiphernodeRegistryOwnable | MockCiphernodeRegistry\n feeToken: EnclaveToken | MockUSDC\n}\n\n// Unified Event System\nexport enum EnclaveEventType {\n // E3 Lifecycle Events\n E3_REQUESTED = 'E3Requested',\n E3_ACTIVATED = 'E3Activated',\n CIPHERTEXT_OUTPUT_PUBLISHED = 'CiphertextOutputPublished',\n PLAINTEXT_OUTPUT_PUBLISHED = 'PlaintextOutputPublished',\n\n // E3 Program Management\n E3_PROGRAM_ENABLED = 'E3ProgramEnabled',\n E3_PROGRAM_DISABLED = 'E3ProgramDisabled',\n\n // Encryption Scheme Management\n ENCRYPTION_SCHEME_ENABLED = 'EncryptionSchemeEnabled',\n ENCRYPTION_SCHEME_DISABLED = 'EncryptionSchemeDisabled',\n\n // Configuration\n CIPHERNODE_REGISTRY_SET = 'CiphernodeRegistrySet',\n MAX_DURATION_SET = 'MaxDurationSet',\n ALLOWED_E3_PROGRAMS_PARAMS_SET = 'AllowedE3ProgramsParamsSet',\n\n // Ownership\n OWNERSHIP_TRANSFERRED = 'OwnershipTransferred',\n INITIALIZED = 'Initialized',\n}\n\nexport enum RegistryEventType {\n // Committee Management\n COMMITTEE_REQUESTED = 'CommitteeRequested',\n COMMITTEE_PUBLISHED = 'CommitteePublished',\n COMMITTEE_FINALIZED = 'CommitteeFinalized',\n\n // Configuration\n ENCLAVE_SET = 'EnclaveSet',\n\n // Ownership\n OWNERSHIP_TRANSFERRED = 'OwnershipTransferred',\n INITIALIZED = 'Initialized',\n}\n\n// Union type for all events\nexport type AllEventTypes = EnclaveEventType | RegistryEventType\n\n// Event data interfaces based on TypeChain types\nexport interface E3 {\n seed: bigint\n threshold: readonly [number, number]\n requestBlock: bigint\n startWindow: readonly [bigint, bigint]\n duration: bigint\n expiration: bigint\n encryptionSchemeId: string\n e3Program: string\n e3ProgramParams: string\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n plaintextOutput: string\n}\n\nexport interface E3RequestedData {\n e3Id: bigint\n e3: E3\n filter: string\n e3Program: string\n}\n\nexport interface E3ActivatedData {\n e3Id: bigint\n expiration: bigint\n committeePublicKey: string\n}\n\nexport interface CiphertextOutputPublishedData {\n e3Id: bigint\n ciphertextOutput: string\n}\n\nexport interface PlaintextOutputPublishedData {\n e3Id: bigint\n plaintextOutput: string\n}\n\nexport interface CiphernodeAddedData {\n node: string\n index: bigint\n numNodes: bigint\n size: bigint\n}\n\nexport interface CiphernodeRemovedData {\n node: string\n index: bigint\n numNodes: bigint\n size: bigint\n}\n\nexport interface CommitteeRequestedData {\n e3Id: bigint\n seed: bigint\n threshold: [bigint, bigint]\n requestBlock: bigint\n submissionDeadline: bigint\n}\n\nexport interface CommitteePublishedData {\n e3Id: bigint\n publicKey: string\n}\n\nexport interface CommitteeFinalizedData {\n e3Id: bigint\n nodes: string[]\n}\n\n// Event data mapping\nexport interface EnclaveEventData {\n [EnclaveEventType.E3_REQUESTED]: E3RequestedData\n [EnclaveEventType.E3_ACTIVATED]: E3ActivatedData\n [EnclaveEventType.CIPHERTEXT_OUTPUT_PUBLISHED]: CiphertextOutputPublishedData\n [EnclaveEventType.PLAINTEXT_OUTPUT_PUBLISHED]: PlaintextOutputPublishedData\n [EnclaveEventType.E3_PROGRAM_ENABLED]: { e3Program: string }\n [EnclaveEventType.E3_PROGRAM_DISABLED]: { e3Program: string }\n [EnclaveEventType.ENCRYPTION_SCHEME_ENABLED]: { encryptionSchemeId: string }\n [EnclaveEventType.ENCRYPTION_SCHEME_DISABLED]: { encryptionSchemeId: string }\n [EnclaveEventType.CIPHERNODE_REGISTRY_SET]: { ciphernodeRegistry: string }\n [EnclaveEventType.MAX_DURATION_SET]: { maxDuration: bigint }\n [EnclaveEventType.ALLOWED_E3_PROGRAMS_PARAMS_SET]: {\n e3ProgramParams: string[]\n }\n [EnclaveEventType.OWNERSHIP_TRANSFERRED]: {\n previousOwner: string\n newOwner: string\n }\n [EnclaveEventType.INITIALIZED]: { version: bigint }\n}\n\nexport interface RegistryEventData {\n [RegistryEventType.COMMITTEE_REQUESTED]: CommitteeRequestedData\n [RegistryEventType.COMMITTEE_PUBLISHED]: CommitteePublishedData\n [RegistryEventType.COMMITTEE_FINALIZED]: CommitteeFinalizedData\n [RegistryEventType.ENCLAVE_SET]: { enclave: string }\n [RegistryEventType.OWNERSHIP_TRANSFERRED]: {\n previousOwner: string\n newOwner: string\n }\n [RegistryEventType.INITIALIZED]: { version: bigint }\n}\n\n// Generic event structure\nexport interface EnclaveEvent<T extends AllEventTypes> {\n type: T\n data: T extends EnclaveEventType ? EnclaveEventData[T] : T extends RegistryEventType ? RegistryEventData[T] : unknown\n log: Log\n timestamp: Date\n blockNumber: bigint\n transactionHash: string\n}\n\nexport type EventCallback<T extends AllEventTypes = AllEventTypes> = (event: EnclaveEvent<T>) => void | Promise<void>\n\nexport interface EventFilter<T = unknown> {\n address?: `0x${string}`\n fromBlock?: bigint\n toBlock?: bigint\n args?: Partial<T>\n}\n\nexport interface SDKEventEmitter {\n on<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void\n off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void\n emit<T extends AllEventTypes>(event: EnclaveEvent<T>): void\n}\n\n/**\n * Result of verifiable encryption using BFV\n */\nexport interface VerifiableEncryptionResult {\n /**\n * The encrypted data\n */\n encryptedData: Uint8Array\n /**\n * The proof generated by Greco\n */\n proof: ProofData\n}\n\n/**\n * BFV parameters for an Enclave program request\n * Example for BFV\n * 512, // degree\n * 10, // plaintext_modulus\n * 0xffffee001, // moduli\n * 0xffffc4001, // moduli\n */\nexport interface BfvParams {\n /**\n * The degree of the polynomial\n */\n degree: number\n /**\n * The plaintext modulus\n */\n plaintextModulus: bigint\n /**\n * The moduli\n */\n moduli: bigint[]\n /**\n * error1\n */\n error1Variance: string | undefined\n}\n\nexport type ThresholdBfvParamsPresetName = 'INSECURE_THRESHOLD_512' | 'SECURE_THRESHOLD_8192'\n\nexport const ThresholdBfvParamsPresetNames = [\n 'INSECURE_THRESHOLD_512',\n 'SECURE_THRESHOLD_8192',\n] as const satisfies ReadonlyArray<ThresholdBfvParamsPresetName>\n\n/**\n * The result of encrypting a value and generating a proof\n */\nexport interface EncryptedValueAndPublicInputs {\n /**\n * The encrypted data\n */\n encryptedData: Uint8Array\n\n /**\n * The public inputs for the proof\n */\n circuitInputs: CircuitInputs\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 { UltraHonkBackend, type ProofData } from '@aztec/bb.js'\nimport { type CompiledCircuit, Noir } from '@noir-lang/noir_js'\n\n// Conversion to Noir types\nexport type Field = string\n\n/**\n * Describes a polynomial to be used in a Noir circuit (Greco)\n */\nexport type Polynomial = {\n coefficients: Field[]\n}\n\n/**\n * Describes the inputs to Greco circuit\n */\nexport interface CircuitInputs {\n pk0is: string[][]\n pk1is: string[][]\n ct0is: string[][]\n ct1is: string[][]\n u: string[]\n e0: string[]\n e1: string[]\n e0is: string[][]\n e0_quotients: string[][]\n k1: string[]\n r1is: string[][]\n r2is: string[][]\n p1is: string[][]\n p2is: string[][]\n pk_commitment: string\n}\n\n/**\n * Generate a proof for a given circuit and circuit inputs\n * @dev Defaults to the UltraHonkBackend\n * @param circuitInputs - The circuit inputs\n * @param circuit - The circuit\n * @returns The proof\n */\nexport const generateProof = async (circuitInputs: CircuitInputs, circuit: CompiledCircuit): Promise<ProofData> => {\n const noir = new Noir(circuit)\n\n const backend = new UltraHonkBackend(circuit.bytecode, { threads: 4 })\n\n const { witness } = await noir.execute(circuitInputs as any)\n\n return await backend.generateProof(witness, { keccakZK: true })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,IAAAA,eAAmI;AACnI,sBAAoC;AACpC,oBAAwD;AACxD,kBAA2B;AAE3B,IAAAC,gBAAqE;;;ACHrE,mBAA4F;;;ACF5F,kBAAuE;AAGhE,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAC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C,QAAI,QAAQ,YAAY;AACtB,YAAM,cAAU,qCAAoB,QAAQ,UAAU;AACtD,yBAAe,iCAAmB;AAAA,QAChC;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAEA,WAAO,IAAI,YAAW;AAAA,MACpB;AAAA,MACA;AAAA,MACA,WAAW,QAAQ;AAAA,MACnB,SAAS,QAAQ;AAAA,MACjB,8BAA8B,QAAQ;AAAA,IACxC,CAAC;AAAA,EACH;AACF;","names":["import_viem","import_types","EnclaveEventType","RegistryEventType","initializeWasm"]}
package/dist/index.d.cts CHANGED
@@ -23,24 +23,14 @@ interface CircuitInputs {
23
23
  e0: string[];
24
24
  e1: string[];
25
25
  e0is: string[][];
26
+ e0_quotients: string[][];
26
27
  k1: string[];
27
28
  r1is: string[][];
28
29
  r2is: string[][];
29
30
  p1is: string[][];
30
31
  p2is: string[][];
32
+ pk_commitment: string;
31
33
  }
32
- /**
33
- * Convert a string array to a polynomial
34
- * @param stringArray - The string array
35
- * @returns The polynomial
36
- */
37
- declare const convertToPolynomial: (stringArray: string[]) => Polynomial;
38
- /**
39
- * Convert an array of string arrays to an array of polynomials
40
- * @param stringArrays - The array of string arrays
41
- * @returns The array of polynomials
42
- */
43
- declare const convertToPolynomialArray: (stringArrays: string[][]) => Polynomial[];
44
34
  /**
45
35
  * Generate a proof for a given circuit and circuit inputs
46
36
  * @dev Defaults to the UltraHonkBackend
@@ -84,13 +74,9 @@ interface SDKConfig {
84
74
  */
85
75
  chainId?: number;
86
76
  /**
87
- * The protocol to use for the Enclave requests
88
- */
89
- protocol: FheProtocol;
90
- /**
91
- * The protocol parameters to use for the Enclave requests
77
+ * The threshold BFV parameters preset name to use for the Enclave requests
92
78
  */
93
- protocolParams?: ProtocolParams;
79
+ thresholdBfvParamsPresetName: ThresholdBfvParamsPresetName;
94
80
  }
95
81
  interface EventListenerConfig {
96
82
  fromBlock?: bigint;
@@ -271,26 +257,14 @@ interface VerifiableEncryptionResult {
271
257
  proof: ProofData;
272
258
  }
273
259
  /**
274
- * The protocol to use for the Enclave requests
275
- */
276
- declare enum FheProtocol {
277
- /**
278
- * The BFV protocol
279
- */
280
- BFV = "BFV",
281
- /**
282
- * The TrBFV protocol
283
- */
284
- TRBFV = "TRBFV"
285
- }
286
- /**
287
- * Protocol parameters for an Enclave program request
260
+ * BFV parameters for an Enclave program request
288
261
  * Example for BFV
289
- * 2048, // degree
290
- * 1032193, // plaintext_modulus
291
- * 0x3FFFFFFF000001, // moduli
262
+ * 512, // degree
263
+ * 10, // plaintext_modulus
264
+ * 0xffffee001, // moduli
265
+ * 0xffffc4001, // moduli
292
266
  */
293
- interface ProtocolParams {
267
+ interface BfvParams {
294
268
  /**
295
269
  * The degree of the polynomial
296
270
  */
@@ -308,36 +282,8 @@ interface ProtocolParams {
308
282
  */
309
283
  error1Variance: string | undefined;
310
284
  }
311
- type ProtocolParamsName = 'INSECURE_SET_2048_1032193_1' | 'INSECURE_SET_512_10_1' | 'INSECURE_SET_512_0XFFFFEE001_1' | 'SET_8192_1000_4' | 'SET_8192_144115188075855872_2';
312
- /**
313
- * Parameters for the BFV protocol
314
- */
315
- declare const BfvProtocolParams: {
316
- /**
317
- * Recommended parameters for BFV protocol
318
- * - Degree: 2048
319
- * - Plaintext modulus: 1032193
320
- * - Moduli:0x3FFFFFFF000001
321
- */
322
- BFV_NORMAL: {
323
- readonly degree: 2048;
324
- readonly plaintextModulus: 1032193n;
325
- readonly moduli: [18014398492704769n];
326
- readonly error1Variance: "10";
327
- };
328
- /**
329
- * Recommended parameters for TrBFV protocol
330
- * - Degree: 8192
331
- * - Plaintext modulus: 1000
332
- * - Moduli: [0x00800000022a0001, 0x00800000021a0001, 0x0080000002120001, 0x0080000001f60001]
333
- */
334
- BFV_THRESHOLD: {
335
- readonly degree: 8192;
336
- readonly plaintextModulus: 1000n;
337
- readonly moduli: [36028797055270913n, 36028797054222337n, 36028797053698049n, 36028797051863041n];
338
- readonly error1Variance: "10";
339
- };
340
- };
285
+ type ThresholdBfvParamsPresetName = 'INSECURE_THRESHOLD_512' | 'SECURE_THRESHOLD_8192';
286
+ declare const ThresholdBfvParamsPresetNames: readonly ["INSECURE_THRESHOLD_512", "SECURE_THRESHOLD_8192"];
341
287
  /**
342
288
  * The result of encrypting a value and generating a proof
343
289
  */
@@ -349,7 +295,7 @@ interface EncryptedValueAndPublicInputs {
349
295
  /**
350
296
  * The public inputs for the proof
351
297
  */
352
- publicInputs: CircuitInputs;
298
+ circuitInputs: CircuitInputs;
353
299
  }
354
300
 
355
301
  declare class EnclaveSDK {
@@ -518,8 +464,7 @@ declare class EnclaveSDK {
518
464
  private eventListener;
519
465
  private contractClient;
520
466
  private initialized;
521
- private protocol;
522
- private protocolParams?;
467
+ private thresholdBfvParamsPresetName?;
523
468
  private publicClient;
524
469
  constructor(config: SDKConfig);
525
470
  /**
@@ -531,8 +476,9 @@ declare class EnclaveSDK {
531
476
  * @returns The public client
532
477
  */
533
478
  getPublicClient: () => PublicClient;
534
- getBfvParamsSet(name: ProtocolParamsName): Promise<ProtocolParams>;
535
- getProtocolParams(): Promise<ProtocolParams>;
479
+ getThresholdBfvParamsSet(): Promise<BfvParams>;
480
+ generatePublicKey(): Promise<Uint8Array>;
481
+ computePublicKeyCommitment(publicKey: Uint8Array): Promise<Uint8Array>;
536
482
  /**
537
483
  * Encrypt a number using the configured protocol
538
484
  * @param data - The number to encrypt
@@ -606,7 +552,7 @@ declare class EnclaveSDK {
606
552
  /**
607
553
  * Activate an E3 computation
608
554
  */
609
- activateE3(e3Id: bigint, publicKey: `0x${string}`, gasLimit?: bigint): Promise<Hash>;
555
+ activateE3(e3Id: bigint, gasLimit?: bigint): Promise<Hash>;
610
556
  /**
611
557
  * Publish input for an E3 computation
612
558
  */
@@ -671,8 +617,7 @@ declare class EnclaveSDK {
671
617
  };
672
618
  privateKey?: `0x${string}`;
673
619
  chainId: keyof typeof EnclaveSDK.chains;
674
- protocol: FheProtocol;
675
- protocolParams?: ProtocolParams;
620
+ thresholdBfvParamsPresetName: ThresholdBfvParamsPresetName;
676
621
  }): EnclaveSDK;
677
622
  }
678
623
 
@@ -743,9 +688,9 @@ declare class ContractClient {
743
688
  requestE3(threshold: [number, number], startWindow: [bigint, bigint], duration: bigint, e3Program: `0x${string}`, e3ProgramParams: `0x${string}`, computeProviderParams: `0x${string}`, customParams?: `0x${string}`, gasLimit?: bigint): Promise<Hash>;
744
689
  /**
745
690
  * Activate an E3 computation
746
- * activate(uint256 e3Id, bytes memory publicKey)
691
+ * activate(uint256 e3Id)
747
692
  */
748
- activateE3(e3Id: bigint, publicKey: `0x${string}`, gasLimit?: bigint): Promise<Hash>;
693
+ activateE3(e3Id: bigint, gasLimit?: bigint): Promise<Hash>;
749
694
  /**
750
695
  * Publish input for an E3 computation
751
696
  * publishInput(uint256 e3Id, bytes memory data)
@@ -797,12 +742,6 @@ declare function generateEventId(log: Log): string;
797
742
  * Get the current timestamp in seconds
798
743
  */
799
744
  declare function getCurrentTimestamp(): number;
800
- declare const BFV_PARAMS_SET: {
801
- readonly degree: 2048;
802
- readonly plaintext_modulus: 1032193;
803
- readonly moduli: readonly [18014398492704769n];
804
- readonly error1_variance: "10";
805
- };
806
745
  interface ComputeProviderParams {
807
746
  name: string;
808
747
  parallel: boolean;
@@ -820,7 +759,7 @@ declare const DEFAULT_E3_CONFIG: {
820
759
  * Encode BFV parameters for the smart contract
821
760
  * BFV (Brakerski-Fan-Vercauteren) is a type of fully homomorphic encryption
822
761
  */
823
- declare function encodeBfvParams(degree?: number, plaintext_modulus?: number, moduli?: readonly bigint[], error1_variance?: string): `0x${string}`;
762
+ declare function encodeBfvParams(params: BfvParams): `0x${string}`;
824
763
  /**
825
764
  * Encode compute provider parameters for the smart contract'
826
765
  * If mock is true, the compute provider parameters will return 32 bytes of 0x00
@@ -839,4 +778,4 @@ declare function calculateStartWindow(windowSize?: number): [bigint, bigint];
839
778
  */
840
779
  declare function decodePlaintextOutput(plaintextOutput: string): number | null;
841
780
 
842
- export { type AllEventTypes, BFV_PARAMS_SET, BfvProtocolParams, type CiphernodeAddedData, type CiphernodeRemovedData, type CiphertextOutputPublishedData, type CommitteeFinalizedData, type CommitteePublishedData, type CommitteeRequestedData, type ComputeProviderParams, ContractClient, type ContractInstances, DEFAULT_COMPUTE_PROVIDER_PARAMS, DEFAULT_E3_CONFIG, type E3, type E3ActivatedData, type E3RequestedData, type EnclaveEvent, type EnclaveEventData, EnclaveEventType, EnclaveSDK, type EncryptedValueAndPublicInputs, type EventCallback, type EventFilter, EventListener, type EventListenerConfig, FheProtocol, type PlaintextOutputPublishedData, type Polynomial, type ProtocolParams, type RegistryEventData, RegistryEventType, type SDKConfig, SDKError, type SDKEventEmitter, type VerifiableEncryptionResult, calculateStartWindow, convertToPolynomial, convertToPolynomialArray, decodePlaintextOutput, encodeBfvParams, encodeComputeProviderParams, encodeCustomParams, formatBigInt, formatEventName, generateEventId, generateProof, getCurrentTimestamp, isValidAddress, isValidHash, parseBigInt, parseEventData, sleep };
781
+ export { type AllEventTypes, type BfvParams, type CiphernodeAddedData, type CiphernodeRemovedData, type CiphertextOutputPublishedData, type CommitteeFinalizedData, type CommitteePublishedData, type CommitteeRequestedData, type ComputeProviderParams, ContractClient, type ContractInstances, DEFAULT_COMPUTE_PROVIDER_PARAMS, DEFAULT_E3_CONFIG, type E3, type E3ActivatedData, type E3RequestedData, type EnclaveEvent, type EnclaveEventData, EnclaveEventType, EnclaveSDK, type EncryptedValueAndPublicInputs, type EventCallback, type EventFilter, EventListener, type EventListenerConfig, type PlaintextOutputPublishedData, type Polynomial, type RegistryEventData, RegistryEventType, type SDKConfig, SDKError, type SDKEventEmitter, type ThresholdBfvParamsPresetName, ThresholdBfvParamsPresetNames, type VerifiableEncryptionResult, calculateStartWindow, decodePlaintextOutput, encodeBfvParams, encodeComputeProviderParams, encodeCustomParams, formatBigInt, formatEventName, generateEventId, generateProof, getCurrentTimestamp, isValidAddress, isValidHash, parseBigInt, parseEventData, sleep };