@interfold/sdk 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contracts/index.cjs +6 -1
- package/dist/contracts/index.cjs.map +1 -1
- package/dist/contracts/index.js +6 -2
- package/dist/contracts/index.js.map +1 -1
- package/dist/index.cjs +6 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/contracts/index.cjs
CHANGED
|
@@ -261,6 +261,11 @@ var ContractClient = class _ContractClient {
|
|
|
261
261
|
async getE3Quote(requestParams) {
|
|
262
262
|
try {
|
|
263
263
|
const committeeSize = validateCommitteeSize(requestParams.committeeSize);
|
|
264
|
+
const expectedCryptoConfigId = await this.publicClient.readContract({
|
|
265
|
+
address: this.contracts.interfold,
|
|
266
|
+
abi: import_types.Interfold__factory.abi,
|
|
267
|
+
functionName: "activeCryptoConfigId"
|
|
268
|
+
});
|
|
264
269
|
return this.publicClient.readContract({
|
|
265
270
|
address: this.contracts.interfold,
|
|
266
271
|
abi: import_types.Interfold__factory.abi,
|
|
@@ -274,7 +279,7 @@ var ContractClient = class _ContractClient {
|
|
|
274
279
|
computeProviderParams: requestParams.computeProviderParams,
|
|
275
280
|
customParams: requestParams.customParams || "0x",
|
|
276
281
|
expectedFeeToken: this.contracts.feeToken,
|
|
277
|
-
expectedCryptoConfigId
|
|
282
|
+
expectedCryptoConfigId,
|
|
278
283
|
maxFee: requestParams.maxFee ?? 0n
|
|
279
284
|
}
|
|
280
285
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/index.ts","../../src/contracts/contract-client.ts","../../src/utils.ts","../../src/contracts/types.ts"],"sourcesContent":["// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nexport { ContractClient } from './contract-client'\nexport type { ContractClientConfig } from './contract-client'\nexport type { ContractAddresses, E3, E3RequestParams } from './types'\nexport { E3Stage, FailureReason } from './types'\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport {\n type Abi,\n type Chain,\n type Hash,\n type PublicClient,\n type TransactionReceipt,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n zeroHash,\n webSocket,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\n\nimport { CiphernodeRegistryOwnable__factory, Interfold__factory, InterfoldToken__factory } from '@interfold/contracts/types'\nimport type { ContractAddresses, E3, E3RequestParams, E3Stage, FailureReason } from './types'\nimport { validateCommitteeSize } from './types'\nimport { SDKError, isValidAddress } from '../utils'\n\nexport interface ContractClientConfig {\n publicClient: PublicClient\n walletClient?: WalletClient\n contracts: ContractAddresses\n}\n\nexport class ContractClient {\n private publicClient: PublicClient\n private walletClient?: WalletClient\n private contracts: ContractAddresses\n private contractInfo: {\n interfold: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n }\n\n constructor(config: ContractClientConfig) {\n const { publicClient, walletClient, contracts } = config\n\n if (!isValidAddress(contracts.interfold)) {\n throw new SDKError('Invalid Interfold contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n this.publicClient = publicClient\n this.walletClient = walletClient\n this.contracts = contracts\n\n this.contractInfo = {\n interfold: {\n address: contracts.interfold,\n abi: Interfold__factory.abi,\n },\n ciphernodeRegistry: {\n address: contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n },\n }\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: ContractAddresses\n privateKey?: `0x${string}`\n chain: Chain\n }): ContractClient {\n const isWebSocket = options.rpcUrl.startsWith('ws://') || options.rpcUrl.startsWith('wss://')\n const transport = isWebSocket\n ? webSocket(options.rpcUrl, {\n keepAlive: { interval: 30_000 },\n reconnect: { attempts: 5, delay: 2_000 },\n })\n : http(options.rpcUrl)\n\n const publicClient = createPublicClient({\n chain: options.chain,\n transport,\n }) as PublicClient\n\n let walletClient: WalletClient | undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain: options.chain,\n transport,\n })\n }\n\n return new ContractClient({ publicClient, walletClient, contracts: options.contracts })\n }\n\n public getPublicClient(): PublicClient {\n return this.publicClient\n }\n\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n functionName: 'approve',\n args: [this.contracts.interfold, amount],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n public async requestE3(params: E3RequestParams): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const committeeSize = validateCommitteeSize(params.committeeSize)\n const maxFee = params.maxFee ?? (await this.getE3Quote(params))\n const expectedCryptoConfigId = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'activeCryptoConfigId',\n })\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'request',\n args: [\n {\n committeeSize,\n inputWindow: params.inputWindow,\n e3Program: params.e3Program,\n paramSet: params.paramSet,\n computeProviderParams: params.computeProviderParams,\n customParams: params.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId,\n maxFee,\n },\n ],\n account,\n gas: params.gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n public async cancelE3(e3Id: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n try {\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'cancelE3',\n args: [e3Id],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to cancel E3: ${error}`, 'CANCEL_E3_FAILED')\n }\n }\n\n public async publishCiphertextOutput(\n e3Id: bigint,\n ciphertextOutput: `0x${string}`,\n ciphertextCommitment: `0x${string}`,\n proof: `0x${string}`,\n gasLimit?: bigint,\n ): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, ciphertextCommitment, proof],\n account,\n gas: gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n public async getE3(e3Id: bigint): Promise<E3> {\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3: ${error}`, 'GET_E3_FAILED')\n }\n }\n\n public async getE3Quote(requestParams: E3RequestParams): Promise<bigint> {\n try {\n const committeeSize = validateCommitteeSize(requestParams.committeeSize)\n\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Quote',\n args: [\n {\n committeeSize,\n inputWindow: requestParams.inputWindow,\n e3Program: requestParams.e3Program,\n paramSet: requestParams.paramSet,\n computeProviderParams: requestParams.computeProviderParams,\n customParams: requestParams.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId: zeroHash,\n maxFee: requestParams.maxFee ?? 0n,\n },\n ],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 quote: ${error}`, 'GET_E3_QUOTE_FAILED')\n }\n }\n\n public async getFailureReason(e3Id: bigint): Promise<FailureReason> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getFailureReason',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get failure reason: ${error}`, 'GET_FAILURE_REASON_FAILED')\n }\n }\n\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n functionName: 'committeePublicKey',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3 public key: ${error}`, 'GET_E3_PUBLIC_KEY_FAILED')\n }\n }\n\n public async getE3Stage(e3Id: bigint): Promise<E3Stage> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Stage',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 stage: ${error}`, 'GET_E3_STAGE_FAILED')\n }\n }\n\n public async estimateGas(\n functionName: string,\n args: readonly unknown[],\n contractAddress: `0x${string}`,\n abi: Abi,\n value?: bigint,\n ): Promise<bigint> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for gas estimation', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const estimateParams = {\n address: contractAddress,\n abi,\n functionName,\n args,\n account,\n ...(value !== undefined && { value }),\n }\n\n return await this.publicClient.estimateContractGas(estimateParams)\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n return await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n } catch (error) {\n throw new SDKError(`Failed to wait for transaction: ${error}`, 'TRANSACTION_WAIT_FAILED')\n }\n }\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { type Address, type Hash, type Log, PublicClient, encodeAbiParameters } from 'viem'\nimport type { BfvParams } from './types'\n\nexport class SDKError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n }\n}\n\nexport function isValidAddress(address: string): address is Address {\n return /^0x[a-fA-F0-9]{40}$/.test(address)\n}\n\nexport function isValidHash(hash: string): hash is Hash {\n return /^0x[a-fA-F0-9]{64}$/.test(hash)\n}\n\nexport function formatEventName(contractName: string, eventName: string): string {\n return `${contractName}.${eventName}`\n}\n\nexport function parseEventData<T>(log: Log): T {\n return log.data as unknown as T\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport const sleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport function formatBigInt(value: bigint): string {\n return value.toString()\n}\n\nexport function parseBigInt(value: string): bigint {\n return BigInt(value)\n}\n\nexport function generateEventId(log: Log): string {\n return `${log.blockHash}-${log.logIndex}`\n}\n\n/**\n * Get the current timestamp in seconds\n * from onchain\n * @param publicClient - The public client to use\n */\nexport async function getCurrentTimestamp(publicClient: PublicClient): Promise<bigint> {\n const block = await publicClient.getBlock()\n return block.timestamp\n}\n\n// Compute provider parameters structure\nexport interface ComputeProviderParams {\n name: string\n parallel: boolean\n batch_size: number\n}\n\n// Default compute provider configuration\nexport const DEFAULT_COMPUTE_PROVIDER_PARAMS: ComputeProviderParams = {\n name: 'risc0',\n parallel: false,\n batch_size: 2,\n}\n\n// Default E3 configuration (`committeeSize` is `IInterfold.CommitteeSize`, not circuit N_PARTIES).\nexport const DEFAULT_E3_CONFIG = {\n committeeSize: 0, // CommitteeSize.Minimum\n duration: 1800, // 30 minutes in seconds\n payment_amount: '0', // 0 ETH in wei\n} as const\n\n/**\n * Encode BFV parameters for the smart contract\n * BFV (Brakerski-Fan-Vercauteren) is a type of fully homomorphic encryption\n */\nexport function encodeBfvParams(params: BfvParams): `0x${string}` {\n const { degree, plaintextModulus, moduli, error1Variance } = params\n\n if (error1Variance === undefined) {\n throw new SDKError(\n 'error1Variance is required in ProtocolParams. All BFV parameter sets must specify error1_variance.',\n 'MISSING_ERROR1_VARIANCE',\n )\n }\n\n return encodeAbiParameters(\n [\n {\n name: 'bfvParams',\n type: 'tuple',\n components: [\n { name: 'degree', type: 'uint256' },\n { name: 'plaintext_modulus', type: 'uint256' },\n { name: 'moduli', type: 'uint256[]' },\n { name: 'error1_variance', type: 'string' },\n ],\n },\n ],\n [\n {\n degree: BigInt(degree),\n plaintext_modulus: BigInt(plaintextModulus),\n moduli: [...moduli],\n error1_variance: error1Variance,\n },\n ],\n )\n}\n\n/**\n * Encode compute provider parameters for the smart contract'\n * If mock is true, the compute provider parameters will return 32 bytes of 0x00\n */\nexport function encodeComputeProviderParams(params: ComputeProviderParams, mock: boolean = false): `0x${string}` {\n if (mock) {\n return `0x${'00'.repeat(32)}` as `0x${string}`\n }\n\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n/**\n * Encode custom parameters for the smart contract.\n */\nexport function encodeCustomParams(params: Record<string, unknown>): `0x${string}` {\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n// inputWindow[0] is always larger than now and dkg deadline\nexport const inputWindowStartBuffer = 15n\n\n/**\n * Calculate start window for E3 request\n * @dev This function can be used for testing purposes, or for E3s which need to start as soon as possible.\n * @param publicClient - The public client to use\n * @param duration - The duration of the input window in seconds\n * @param startBuffer - Buffer in seconds added to current timestamp for input window start\n */\nexport async function calculateInputWindow(\n publicClient: PublicClient,\n duration: number = DEFAULT_E3_CONFIG.duration,\n startBuffer: bigint = inputWindowStartBuffer,\n): Promise<[bigint, bigint]> {\n const now = await getCurrentTimestamp(publicClient)\n return [BigInt(now) + startBuffer, BigInt(now) + startBuffer + BigInt(duration)]\n}\n\n/**\n * Decode plaintextOutput bytes to get the actual result number\n */\nexport function decodePlaintextOutput(plaintextOutput: string): number | null {\n try {\n // Remove '0x' prefix if present\n const hex = plaintextOutput.startsWith('0x') ? plaintextOutput.slice(2) : plaintextOutput\n\n // Convert hex to bytes\n const bytes = new Uint8Array(hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [])\n\n if (bytes.length < 8) {\n console.warn('Plaintext output too short for u64 decoding')\n return null\n }\n\n // Decode first u64 (8 bytes) as little-endian\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const result = view.getBigUint64(0, true) // true for little-endian\n\n return Number(result)\n } catch (error) {\n console.error('Failed to decode plaintext output:', error)\n return null\n }\n}\n\n// Helper function to convert proof bytes to field elements\nexport function proofToFields(proof: Uint8Array): string[] {\n const fields: string[] = []\n for (let i = 0; i < proof.length; i += 32) {\n const chunk = proof.slice(i, i + 32)\n fields.push('0x' + Buffer.from(chunk).toString('hex'))\n }\n return fields\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { SDKError } from '../utils'\n\nexport interface ContractAddresses {\n interfold: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n}\n\n/** On-chain `IInterfold.CommitteeSize`: Minimum (N=3), Micro (N=9), Small (N=19). */\nexport enum CommitteeSize {\n Minimum = 0,\n Micro = 1,\n Small = 2,\n}\n\n/** Fail fast on out-of-range committee sizes before they hit the contract. */\nexport function validateCommitteeSize(value: number | CommitteeSize): CommitteeSize {\n if (!Number.isInteger(value) || value < CommitteeSize.Minimum || value > CommitteeSize.Small) {\n throw new SDKError(\n `Invalid committeeSize ${value}. Use CommitteeSize.Minimum (0), CommitteeSize.Micro (1), or CommitteeSize.Small (2).`,\n 'INVALID_COMMITTEE_SIZE',\n )\n }\n return value\n}\n\nexport enum ParamSet {\n Insecure512 = 0,\n Secure8192 = 1,\n}\n\nexport interface E3 {\n seed: bigint\n committeeSize: number\n requestBlock: bigint\n inputWindow: readonly [bigint, bigint]\n encryptionSchemeId: string\n e3Program: string\n paramSet: number\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n ciphertextCommitment: string\n plaintextOutput: string\n}\n\nexport interface RequestParams {\n gasLimit?: bigint\n}\n\nexport interface E3RequestParams extends RequestParams {\n committeeSize: number\n inputWindow: readonly [bigint, bigint]\n e3Program: `0x${string}`\n paramSet: number\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n /** Maximum fee token amount accepted. Defaults to a fresh quote. */\n maxFee?: bigint\n}\n\nexport enum E3Stage {\n None,\n Requested,\n CommitteeFinalized,\n KeyPublished,\n CiphertextReady,\n Complete,\n Failed,\n}\n\nexport enum FailureReason {\n None,\n CommitteeFormationTimeout,\n InsufficientCommitteeMembers,\n DKGTimeout,\n DKGInvalidShares,\n NoInputsReceived,\n ComputeTimeout,\n ComputeProviderExpired,\n ComputeProviderFailed,\n RequesterCancelled,\n DecryptionTimeout,\n DecryptionInvalidShares,\n VerificationFailed,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,IAAAA,eAYO;AACP,sBAAoC;AAEpC,mBAAgG;;;ACfhG,kBAAqF;AAG9E,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,eAAe,SAAqC;AAClE,SAAO,sBAAsB,KAAK,OAAO;AAC3C;;;ACCO,SAAS,sBAAsB,OAA8C;AAClF,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,mBAAyB,QAAQ,eAAqB;AAC5F,UAAM,IAAI;AAAA,MACR,yBAAyB,KAAK;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAqCO,IAAK,UAAL,kBAAKC,aAAL;AACL,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AAPU,SAAAA;AAAA,GAAA;AAUL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;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IAAI,SAAS,2BAA2B,KAAK,IAAI,qBAAqB;AAAA,IAC9E;AAAA,EACF;AAAA,EAEA,MAAa,YACX,cACA,MACA,iBACA,KACA,OACiB;AACjB,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,SAAS,6CAA6C,WAAW;AAAA,IAC7E;AAEA,QAAI;AACF,YAAM,UAAU,KAAK,aAAa;AAClC,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,SAAS,wBAAwB,YAAY;AAAA,MACzD;AAEA,YAAM,iBAAiB;AAAA,QACrB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAI,UAAU,UAAa,EAAE,MAAM;AAAA,MACrC;AAEA,aAAO,MAAM,KAAK,aAAa,oBAAoB,cAAc;AAAA,IACnE,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,2BAA2B,KAAK,IAAI,uBAAuB;AAAA,IAChF;AAAA,EACF;AAAA,EAEA,MAAa,mBAAmB,MAAyC;AACvE,QAAI;AACF,aAAO,MAAM,KAAK,aAAa,0BAA0B;AAAA,QACvD;AAAA,QACA,eAAe;AAAA,MACjB,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,mCAAmC,KAAK,IAAI,yBAAyB;AAAA,IAC1F;AAAA,EACF;AACF;","names":["import_viem","E3Stage","FailureReason"]}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/index.ts","../../src/contracts/contract-client.ts","../../src/utils.ts","../../src/contracts/types.ts"],"sourcesContent":["// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nexport { ContractClient } from './contract-client'\nexport type { ContractClientConfig } from './contract-client'\nexport type { ContractAddresses, E3, E3RequestParams } from './types'\nexport { E3Stage, FailureReason } from './types'\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport {\n type Abi,\n type Chain,\n type Hash,\n type PublicClient,\n type TransactionReceipt,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n webSocket,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\n\nimport { CiphernodeRegistryOwnable__factory, Interfold__factory, InterfoldToken__factory } from '@interfold/contracts/types'\nimport type { ContractAddresses, E3, E3RequestParams, E3Stage, FailureReason } from './types'\nimport { validateCommitteeSize } from './types'\nimport { SDKError, isValidAddress } from '../utils'\n\nexport interface ContractClientConfig {\n publicClient: PublicClient\n walletClient?: WalletClient\n contracts: ContractAddresses\n}\n\nexport class ContractClient {\n private publicClient: PublicClient\n private walletClient?: WalletClient\n private contracts: ContractAddresses\n private contractInfo: {\n interfold: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n }\n\n constructor(config: ContractClientConfig) {\n const { publicClient, walletClient, contracts } = config\n\n if (!isValidAddress(contracts.interfold)) {\n throw new SDKError('Invalid Interfold contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n this.publicClient = publicClient\n this.walletClient = walletClient\n this.contracts = contracts\n\n this.contractInfo = {\n interfold: {\n address: contracts.interfold,\n abi: Interfold__factory.abi,\n },\n ciphernodeRegistry: {\n address: contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n },\n }\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: ContractAddresses\n privateKey?: `0x${string}`\n chain: Chain\n }): ContractClient {\n const isWebSocket = options.rpcUrl.startsWith('ws://') || options.rpcUrl.startsWith('wss://')\n const transport = isWebSocket\n ? webSocket(options.rpcUrl, {\n keepAlive: { interval: 30_000 },\n reconnect: { attempts: 5, delay: 2_000 },\n })\n : http(options.rpcUrl)\n\n const publicClient = createPublicClient({\n chain: options.chain,\n transport,\n }) as PublicClient\n\n let walletClient: WalletClient | undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain: options.chain,\n transport,\n })\n }\n\n return new ContractClient({ publicClient, walletClient, contracts: options.contracts })\n }\n\n public getPublicClient(): PublicClient {\n return this.publicClient\n }\n\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n functionName: 'approve',\n args: [this.contracts.interfold, amount],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n public async requestE3(params: E3RequestParams): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const committeeSize = validateCommitteeSize(params.committeeSize)\n const maxFee = params.maxFee ?? (await this.getE3Quote(params))\n const expectedCryptoConfigId = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'activeCryptoConfigId',\n })\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'request',\n args: [\n {\n committeeSize,\n inputWindow: params.inputWindow,\n e3Program: params.e3Program,\n paramSet: params.paramSet,\n computeProviderParams: params.computeProviderParams,\n customParams: params.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId,\n maxFee,\n },\n ],\n account,\n gas: params.gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n public async cancelE3(e3Id: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n try {\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'cancelE3',\n args: [e3Id],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to cancel E3: ${error}`, 'CANCEL_E3_FAILED')\n }\n }\n\n public async publishCiphertextOutput(\n e3Id: bigint,\n ciphertextOutput: `0x${string}`,\n ciphertextCommitment: `0x${string}`,\n proof: `0x${string}`,\n gasLimit?: bigint,\n ): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, ciphertextCommitment, proof],\n account,\n gas: gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n public async getE3(e3Id: bigint): Promise<E3> {\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3: ${error}`, 'GET_E3_FAILED')\n }\n }\n\n public async getE3Quote(requestParams: E3RequestParams): Promise<bigint> {\n try {\n const committeeSize = validateCommitteeSize(requestParams.committeeSize)\n const expectedCryptoConfigId = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'activeCryptoConfigId',\n })\n\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Quote',\n args: [\n {\n committeeSize,\n inputWindow: requestParams.inputWindow,\n e3Program: requestParams.e3Program,\n paramSet: requestParams.paramSet,\n computeProviderParams: requestParams.computeProviderParams,\n customParams: requestParams.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId,\n maxFee: requestParams.maxFee ?? 0n,\n },\n ],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 quote: ${error}`, 'GET_E3_QUOTE_FAILED')\n }\n }\n\n public async getFailureReason(e3Id: bigint): Promise<FailureReason> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getFailureReason',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get failure reason: ${error}`, 'GET_FAILURE_REASON_FAILED')\n }\n }\n\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n functionName: 'committeePublicKey',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3 public key: ${error}`, 'GET_E3_PUBLIC_KEY_FAILED')\n }\n }\n\n public async getE3Stage(e3Id: bigint): Promise<E3Stage> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Stage',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 stage: ${error}`, 'GET_E3_STAGE_FAILED')\n }\n }\n\n public async estimateGas(\n functionName: string,\n args: readonly unknown[],\n contractAddress: `0x${string}`,\n abi: Abi,\n value?: bigint,\n ): Promise<bigint> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for gas estimation', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const estimateParams = {\n address: contractAddress,\n abi,\n functionName,\n args,\n account,\n ...(value !== undefined && { value }),\n }\n\n return await this.publicClient.estimateContractGas(estimateParams)\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n return await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n } catch (error) {\n throw new SDKError(`Failed to wait for transaction: ${error}`, 'TRANSACTION_WAIT_FAILED')\n }\n }\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { type Address, type Hash, type Log, PublicClient, encodeAbiParameters } from 'viem'\nimport type { BfvParams } from './types'\n\nexport class SDKError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n }\n}\n\nexport function isValidAddress(address: string): address is Address {\n return /^0x[a-fA-F0-9]{40}$/.test(address)\n}\n\nexport function isValidHash(hash: string): hash is Hash {\n return /^0x[a-fA-F0-9]{64}$/.test(hash)\n}\n\nexport function formatEventName(contractName: string, eventName: string): string {\n return `${contractName}.${eventName}`\n}\n\nexport function parseEventData<T>(log: Log): T {\n return log.data as unknown as T\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport const sleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport function formatBigInt(value: bigint): string {\n return value.toString()\n}\n\nexport function parseBigInt(value: string): bigint {\n return BigInt(value)\n}\n\nexport function generateEventId(log: Log): string {\n return `${log.blockHash}-${log.logIndex}`\n}\n\n/**\n * Get the current timestamp in seconds\n * from onchain\n * @param publicClient - The public client to use\n */\nexport async function getCurrentTimestamp(publicClient: PublicClient): Promise<bigint> {\n const block = await publicClient.getBlock()\n return block.timestamp\n}\n\n// Compute provider parameters structure\nexport interface ComputeProviderParams {\n name: string\n parallel: boolean\n batch_size: number\n}\n\n// Default compute provider configuration\nexport const DEFAULT_COMPUTE_PROVIDER_PARAMS: ComputeProviderParams = {\n name: 'risc0',\n parallel: false,\n batch_size: 2,\n}\n\n// Default E3 configuration (`committeeSize` is `IInterfold.CommitteeSize`, not circuit N_PARTIES).\nexport const DEFAULT_E3_CONFIG = {\n committeeSize: 0, // CommitteeSize.Minimum\n duration: 1800, // 30 minutes in seconds\n payment_amount: '0', // 0 ETH in wei\n} as const\n\n/**\n * Encode BFV parameters for the smart contract\n * BFV (Brakerski-Fan-Vercauteren) is a type of fully homomorphic encryption\n */\nexport function encodeBfvParams(params: BfvParams): `0x${string}` {\n const { degree, plaintextModulus, moduli, error1Variance } = params\n\n if (error1Variance === undefined) {\n throw new SDKError(\n 'error1Variance is required in ProtocolParams. All BFV parameter sets must specify error1_variance.',\n 'MISSING_ERROR1_VARIANCE',\n )\n }\n\n return encodeAbiParameters(\n [\n {\n name: 'bfvParams',\n type: 'tuple',\n components: [\n { name: 'degree', type: 'uint256' },\n { name: 'plaintext_modulus', type: 'uint256' },\n { name: 'moduli', type: 'uint256[]' },\n { name: 'error1_variance', type: 'string' },\n ],\n },\n ],\n [\n {\n degree: BigInt(degree),\n plaintext_modulus: BigInt(plaintextModulus),\n moduli: [...moduli],\n error1_variance: error1Variance,\n },\n ],\n )\n}\n\n/**\n * Encode compute provider parameters for the smart contract'\n * If mock is true, the compute provider parameters will return 32 bytes of 0x00\n */\nexport function encodeComputeProviderParams(params: ComputeProviderParams, mock: boolean = false): `0x${string}` {\n if (mock) {\n return `0x${'00'.repeat(32)}` as `0x${string}`\n }\n\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n/**\n * Encode custom parameters for the smart contract.\n */\nexport function encodeCustomParams(params: Record<string, unknown>): `0x${string}` {\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n// inputWindow[0] is always larger than now and dkg deadline\nexport const inputWindowStartBuffer = 15n\n\n/**\n * Calculate start window for E3 request\n * @dev This function can be used for testing purposes, or for E3s which need to start as soon as possible.\n * @param publicClient - The public client to use\n * @param duration - The duration of the input window in seconds\n * @param startBuffer - Buffer in seconds added to current timestamp for input window start\n */\nexport async function calculateInputWindow(\n publicClient: PublicClient,\n duration: number = DEFAULT_E3_CONFIG.duration,\n startBuffer: bigint = inputWindowStartBuffer,\n): Promise<[bigint, bigint]> {\n const now = await getCurrentTimestamp(publicClient)\n return [BigInt(now) + startBuffer, BigInt(now) + startBuffer + BigInt(duration)]\n}\n\n/**\n * Decode plaintextOutput bytes to get the actual result number\n */\nexport function decodePlaintextOutput(plaintextOutput: string): number | null {\n try {\n // Remove '0x' prefix if present\n const hex = plaintextOutput.startsWith('0x') ? plaintextOutput.slice(2) : plaintextOutput\n\n // Convert hex to bytes\n const bytes = new Uint8Array(hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [])\n\n if (bytes.length < 8) {\n console.warn('Plaintext output too short for u64 decoding')\n return null\n }\n\n // Decode first u64 (8 bytes) as little-endian\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const result = view.getBigUint64(0, true) // true for little-endian\n\n return Number(result)\n } catch (error) {\n console.error('Failed to decode plaintext output:', error)\n return null\n }\n}\n\n// Helper function to convert proof bytes to field elements\nexport function proofToFields(proof: Uint8Array): string[] {\n const fields: string[] = []\n for (let i = 0; i < proof.length; i += 32) {\n const chunk = proof.slice(i, i + 32)\n fields.push('0x' + Buffer.from(chunk).toString('hex'))\n }\n return fields\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { SDKError } from '../utils'\n\nexport interface ContractAddresses {\n interfold: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n}\n\n/** On-chain `IInterfold.CommitteeSize`: Minimum (N=3), Micro (N=9), Small (N=19). */\nexport enum CommitteeSize {\n Minimum = 0,\n Micro = 1,\n Small = 2,\n}\n\n/** Fail fast on out-of-range committee sizes before they hit the contract. */\nexport function validateCommitteeSize(value: number | CommitteeSize): CommitteeSize {\n if (!Number.isInteger(value) || value < CommitteeSize.Minimum || value > CommitteeSize.Small) {\n throw new SDKError(\n `Invalid committeeSize ${value}. Use CommitteeSize.Minimum (0), CommitteeSize.Micro (1), or CommitteeSize.Small (2).`,\n 'INVALID_COMMITTEE_SIZE',\n )\n }\n return value\n}\n\nexport enum ParamSet {\n Insecure512 = 0,\n Secure8192 = 1,\n}\n\nexport interface E3 {\n seed: bigint\n committeeSize: number\n requestBlock: bigint\n inputWindow: readonly [bigint, bigint]\n encryptionSchemeId: string\n e3Program: string\n paramSet: number\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n ciphertextCommitment: string\n plaintextOutput: string\n}\n\nexport interface RequestParams {\n gasLimit?: bigint\n}\n\nexport interface E3RequestParams extends RequestParams {\n committeeSize: number\n inputWindow: readonly [bigint, bigint]\n e3Program: `0x${string}`\n paramSet: number\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n /** Maximum fee token amount accepted. Defaults to a fresh quote. */\n maxFee?: bigint\n}\n\nexport enum E3Stage {\n None,\n Requested,\n CommitteeFinalized,\n KeyPublished,\n CiphertextReady,\n Complete,\n Failed,\n}\n\nexport enum FailureReason {\n None,\n CommitteeFormationTimeout,\n InsufficientCommitteeMembers,\n DKGTimeout,\n DKGInvalidShares,\n NoInputsReceived,\n ComputeTimeout,\n ComputeProviderExpired,\n ComputeProviderFailed,\n RequesterCancelled,\n DecryptionTimeout,\n DecryptionInvalidShares,\n VerificationFailed,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,IAAAA,eAWO;AACP,sBAAoC;AAEpC,mBAAgG;;;ACdhG,kBAAqF;AAG9E,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,eAAe,SAAqC;AAClE,SAAO,sBAAsB,KAAK,OAAO;AAC3C;;;ACCO,SAAS,sBAAsB,OAA8C;AAClF,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,mBAAyB,QAAQ,eAAqB;AAC5F,UAAM,IAAI;AAAA,MACR,yBAAyB,KAAK;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAqCO,IAAK,UAAL,kBAAKC,aAAL;AACL,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AAPU,SAAAA;AAAA,GAAA;AAUL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AACA,EAAAA,8BAAA;AAC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,MACb,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,2BAA2B,KAAK,IAAI,qBAAqB;AAAA,IAC9E;AAAA,EACF;AAAA,EAEA,MAAa,YACX,cACA,MACA,iBACA,KACA,OACiB;AACjB,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,SAAS,6CAA6C,WAAW;AAAA,IAC7E;AAEA,QAAI;AACF,YAAM,UAAU,KAAK,aAAa;AAClC,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,SAAS,wBAAwB,YAAY;AAAA,MACzD;AAEA,YAAM,iBAAiB;AAAA,QACrB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAI,UAAU,UAAa,EAAE,MAAM;AAAA,MACrC;AAEA,aAAO,MAAM,KAAK,aAAa,oBAAoB,cAAc;AAAA,IACnE,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,2BAA2B,KAAK,IAAI,uBAAuB;AAAA,IAChF;AAAA,EACF;AAAA,EAEA,MAAa,mBAAmB,MAAyC;AACvE,QAAI;AACF,aAAO,MAAM,KAAK,aAAa,0BAA0B;AAAA,QACvD;AAAA,QACA,eAAe;AAAA,MACjB,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,mCAAmC,KAAK,IAAI,yBAAyB;AAAA,IAC1F;AAAA,EACF;AACF;","names":["import_viem","E3Stage","FailureReason"]}
|
package/dist/contracts/index.js
CHANGED
|
@@ -3,7 +3,6 @@ import {
|
|
|
3
3
|
createPublicClient,
|
|
4
4
|
createWalletClient,
|
|
5
5
|
http,
|
|
6
|
-
zeroHash,
|
|
7
6
|
webSocket
|
|
8
7
|
} from "viem";
|
|
9
8
|
import { privateKeyToAccount } from "viem/accounts";
|
|
@@ -239,6 +238,11 @@ var ContractClient = class _ContractClient {
|
|
|
239
238
|
async getE3Quote(requestParams) {
|
|
240
239
|
try {
|
|
241
240
|
const committeeSize = validateCommitteeSize(requestParams.committeeSize);
|
|
241
|
+
const expectedCryptoConfigId = await this.publicClient.readContract({
|
|
242
|
+
address: this.contracts.interfold,
|
|
243
|
+
abi: Interfold__factory.abi,
|
|
244
|
+
functionName: "activeCryptoConfigId"
|
|
245
|
+
});
|
|
242
246
|
return this.publicClient.readContract({
|
|
243
247
|
address: this.contracts.interfold,
|
|
244
248
|
abi: Interfold__factory.abi,
|
|
@@ -252,7 +256,7 @@ var ContractClient = class _ContractClient {
|
|
|
252
256
|
computeProviderParams: requestParams.computeProviderParams,
|
|
253
257
|
customParams: requestParams.customParams || "0x",
|
|
254
258
|
expectedFeeToken: this.contracts.feeToken,
|
|
255
|
-
expectedCryptoConfigId
|
|
259
|
+
expectedCryptoConfigId,
|
|
256
260
|
maxFee: requestParams.maxFee ?? 0n
|
|
257
261
|
}
|
|
258
262
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/contract-client.ts","../../src/utils.ts","../../src/contracts/types.ts"],"sourcesContent":["// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport {\n type Abi,\n type Chain,\n type Hash,\n type PublicClient,\n type TransactionReceipt,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n zeroHash,\n webSocket,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\n\nimport { CiphernodeRegistryOwnable__factory, Interfold__factory, InterfoldToken__factory } from '@interfold/contracts/types'\nimport type { ContractAddresses, E3, E3RequestParams, E3Stage, FailureReason } from './types'\nimport { validateCommitteeSize } from './types'\nimport { SDKError, isValidAddress } from '../utils'\n\nexport interface ContractClientConfig {\n publicClient: PublicClient\n walletClient?: WalletClient\n contracts: ContractAddresses\n}\n\nexport class ContractClient {\n private publicClient: PublicClient\n private walletClient?: WalletClient\n private contracts: ContractAddresses\n private contractInfo: {\n interfold: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n }\n\n constructor(config: ContractClientConfig) {\n const { publicClient, walletClient, contracts } = config\n\n if (!isValidAddress(contracts.interfold)) {\n throw new SDKError('Invalid Interfold contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n this.publicClient = publicClient\n this.walletClient = walletClient\n this.contracts = contracts\n\n this.contractInfo = {\n interfold: {\n address: contracts.interfold,\n abi: Interfold__factory.abi,\n },\n ciphernodeRegistry: {\n address: contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n },\n }\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: ContractAddresses\n privateKey?: `0x${string}`\n chain: Chain\n }): ContractClient {\n const isWebSocket = options.rpcUrl.startsWith('ws://') || options.rpcUrl.startsWith('wss://')\n const transport = isWebSocket\n ? webSocket(options.rpcUrl, {\n keepAlive: { interval: 30_000 },\n reconnect: { attempts: 5, delay: 2_000 },\n })\n : http(options.rpcUrl)\n\n const publicClient = createPublicClient({\n chain: options.chain,\n transport,\n }) as PublicClient\n\n let walletClient: WalletClient | undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain: options.chain,\n transport,\n })\n }\n\n return new ContractClient({ publicClient, walletClient, contracts: options.contracts })\n }\n\n public getPublicClient(): PublicClient {\n return this.publicClient\n }\n\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n functionName: 'approve',\n args: [this.contracts.interfold, amount],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n public async requestE3(params: E3RequestParams): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const committeeSize = validateCommitteeSize(params.committeeSize)\n const maxFee = params.maxFee ?? (await this.getE3Quote(params))\n const expectedCryptoConfigId = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'activeCryptoConfigId',\n })\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'request',\n args: [\n {\n committeeSize,\n inputWindow: params.inputWindow,\n e3Program: params.e3Program,\n paramSet: params.paramSet,\n computeProviderParams: params.computeProviderParams,\n customParams: params.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId,\n maxFee,\n },\n ],\n account,\n gas: params.gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n public async cancelE3(e3Id: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n try {\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'cancelE3',\n args: [e3Id],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to cancel E3: ${error}`, 'CANCEL_E3_FAILED')\n }\n }\n\n public async publishCiphertextOutput(\n e3Id: bigint,\n ciphertextOutput: `0x${string}`,\n ciphertextCommitment: `0x${string}`,\n proof: `0x${string}`,\n gasLimit?: bigint,\n ): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, ciphertextCommitment, proof],\n account,\n gas: gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n public async getE3(e3Id: bigint): Promise<E3> {\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3: ${error}`, 'GET_E3_FAILED')\n }\n }\n\n public async getE3Quote(requestParams: E3RequestParams): Promise<bigint> {\n try {\n const committeeSize = validateCommitteeSize(requestParams.committeeSize)\n\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Quote',\n args: [\n {\n committeeSize,\n inputWindow: requestParams.inputWindow,\n e3Program: requestParams.e3Program,\n paramSet: requestParams.paramSet,\n computeProviderParams: requestParams.computeProviderParams,\n customParams: requestParams.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId: zeroHash,\n maxFee: requestParams.maxFee ?? 0n,\n },\n ],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 quote: ${error}`, 'GET_E3_QUOTE_FAILED')\n }\n }\n\n public async getFailureReason(e3Id: bigint): Promise<FailureReason> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getFailureReason',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get failure reason: ${error}`, 'GET_FAILURE_REASON_FAILED')\n }\n }\n\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n functionName: 'committeePublicKey',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3 public key: ${error}`, 'GET_E3_PUBLIC_KEY_FAILED')\n }\n }\n\n public async getE3Stage(e3Id: bigint): Promise<E3Stage> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Stage',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 stage: ${error}`, 'GET_E3_STAGE_FAILED')\n }\n }\n\n public async estimateGas(\n functionName: string,\n args: readonly unknown[],\n contractAddress: `0x${string}`,\n abi: Abi,\n value?: bigint,\n ): Promise<bigint> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for gas estimation', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const estimateParams = {\n address: contractAddress,\n abi,\n functionName,\n args,\n account,\n ...(value !== undefined && { value }),\n }\n\n return await this.publicClient.estimateContractGas(estimateParams)\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n return await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n } catch (error) {\n throw new SDKError(`Failed to wait for transaction: ${error}`, 'TRANSACTION_WAIT_FAILED')\n }\n }\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { type Address, type Hash, type Log, PublicClient, encodeAbiParameters } from 'viem'\nimport type { BfvParams } from './types'\n\nexport class SDKError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n }\n}\n\nexport function isValidAddress(address: string): address is Address {\n return /^0x[a-fA-F0-9]{40}$/.test(address)\n}\n\nexport function isValidHash(hash: string): hash is Hash {\n return /^0x[a-fA-F0-9]{64}$/.test(hash)\n}\n\nexport function formatEventName(contractName: string, eventName: string): string {\n return `${contractName}.${eventName}`\n}\n\nexport function parseEventData<T>(log: Log): T {\n return log.data as unknown as T\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport const sleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport function formatBigInt(value: bigint): string {\n return value.toString()\n}\n\nexport function parseBigInt(value: string): bigint {\n return BigInt(value)\n}\n\nexport function generateEventId(log: Log): string {\n return `${log.blockHash}-${log.logIndex}`\n}\n\n/**\n * Get the current timestamp in seconds\n * from onchain\n * @param publicClient - The public client to use\n */\nexport async function getCurrentTimestamp(publicClient: PublicClient): Promise<bigint> {\n const block = await publicClient.getBlock()\n return block.timestamp\n}\n\n// Compute provider parameters structure\nexport interface ComputeProviderParams {\n name: string\n parallel: boolean\n batch_size: number\n}\n\n// Default compute provider configuration\nexport const DEFAULT_COMPUTE_PROVIDER_PARAMS: ComputeProviderParams = {\n name: 'risc0',\n parallel: false,\n batch_size: 2,\n}\n\n// Default E3 configuration (`committeeSize` is `IInterfold.CommitteeSize`, not circuit N_PARTIES).\nexport const DEFAULT_E3_CONFIG = {\n committeeSize: 0, // CommitteeSize.Minimum\n duration: 1800, // 30 minutes in seconds\n payment_amount: '0', // 0 ETH in wei\n} as const\n\n/**\n * Encode BFV parameters for the smart contract\n * BFV (Brakerski-Fan-Vercauteren) is a type of fully homomorphic encryption\n */\nexport function encodeBfvParams(params: BfvParams): `0x${string}` {\n const { degree, plaintextModulus, moduli, error1Variance } = params\n\n if (error1Variance === undefined) {\n throw new SDKError(\n 'error1Variance is required in ProtocolParams. All BFV parameter sets must specify error1_variance.',\n 'MISSING_ERROR1_VARIANCE',\n )\n }\n\n return encodeAbiParameters(\n [\n {\n name: 'bfvParams',\n type: 'tuple',\n components: [\n { name: 'degree', type: 'uint256' },\n { name: 'plaintext_modulus', type: 'uint256' },\n { name: 'moduli', type: 'uint256[]' },\n { name: 'error1_variance', type: 'string' },\n ],\n },\n ],\n [\n {\n degree: BigInt(degree),\n plaintext_modulus: BigInt(plaintextModulus),\n moduli: [...moduli],\n error1_variance: error1Variance,\n },\n ],\n )\n}\n\n/**\n * Encode compute provider parameters for the smart contract'\n * If mock is true, the compute provider parameters will return 32 bytes of 0x00\n */\nexport function encodeComputeProviderParams(params: ComputeProviderParams, mock: boolean = false): `0x${string}` {\n if (mock) {\n return `0x${'00'.repeat(32)}` as `0x${string}`\n }\n\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n/**\n * Encode custom parameters for the smart contract.\n */\nexport function encodeCustomParams(params: Record<string, unknown>): `0x${string}` {\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n// inputWindow[0] is always larger than now and dkg deadline\nexport const inputWindowStartBuffer = 15n\n\n/**\n * Calculate start window for E3 request\n * @dev This function can be used for testing purposes, or for E3s which need to start as soon as possible.\n * @param publicClient - The public client to use\n * @param duration - The duration of the input window in seconds\n * @param startBuffer - Buffer in seconds added to current timestamp for input window start\n */\nexport async function calculateInputWindow(\n publicClient: PublicClient,\n duration: number = DEFAULT_E3_CONFIG.duration,\n startBuffer: bigint = inputWindowStartBuffer,\n): Promise<[bigint, bigint]> {\n const now = await getCurrentTimestamp(publicClient)\n return [BigInt(now) + startBuffer, BigInt(now) + startBuffer + BigInt(duration)]\n}\n\n/**\n * Decode plaintextOutput bytes to get the actual result number\n */\nexport function decodePlaintextOutput(plaintextOutput: string): number | null {\n try {\n // Remove '0x' prefix if present\n const hex = plaintextOutput.startsWith('0x') ? plaintextOutput.slice(2) : plaintextOutput\n\n // Convert hex to bytes\n const bytes = new Uint8Array(hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [])\n\n if (bytes.length < 8) {\n console.warn('Plaintext output too short for u64 decoding')\n return null\n }\n\n // Decode first u64 (8 bytes) as little-endian\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const result = view.getBigUint64(0, true) // true for little-endian\n\n return Number(result)\n } catch (error) {\n console.error('Failed to decode plaintext output:', error)\n return null\n }\n}\n\n// Helper function to convert proof bytes to field elements\nexport function proofToFields(proof: Uint8Array): string[] {\n const fields: string[] = []\n for (let i = 0; i < proof.length; i += 32) {\n const chunk = proof.slice(i, i + 32)\n fields.push('0x' + Buffer.from(chunk).toString('hex'))\n }\n return fields\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { SDKError } from '../utils'\n\nexport interface ContractAddresses {\n interfold: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n}\n\n/** On-chain `IInterfold.CommitteeSize`: Minimum (N=3), Micro (N=9), Small (N=19). */\nexport enum CommitteeSize {\n Minimum = 0,\n Micro = 1,\n Small = 2,\n}\n\n/** Fail fast on out-of-range committee sizes before they hit the contract. */\nexport function validateCommitteeSize(value: number | CommitteeSize): CommitteeSize {\n if (!Number.isInteger(value) || value < CommitteeSize.Minimum || value > CommitteeSize.Small) {\n throw new SDKError(\n `Invalid committeeSize ${value}. Use CommitteeSize.Minimum (0), CommitteeSize.Micro (1), or CommitteeSize.Small (2).`,\n 'INVALID_COMMITTEE_SIZE',\n )\n }\n return value\n}\n\nexport enum ParamSet {\n Insecure512 = 0,\n Secure8192 = 1,\n}\n\nexport interface E3 {\n seed: bigint\n committeeSize: number\n requestBlock: bigint\n inputWindow: readonly [bigint, bigint]\n encryptionSchemeId: string\n e3Program: string\n paramSet: number\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n ciphertextCommitment: string\n plaintextOutput: string\n}\n\nexport interface RequestParams {\n gasLimit?: bigint\n}\n\nexport interface E3RequestParams extends RequestParams {\n committeeSize: number\n inputWindow: readonly [bigint, bigint]\n e3Program: `0x${string}`\n paramSet: number\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n /** Maximum fee token amount accepted. Defaults to a fresh quote. */\n maxFee?: bigint\n}\n\nexport enum E3Stage {\n None,\n Requested,\n CommitteeFinalized,\n KeyPublished,\n CiphertextReady,\n Complete,\n Failed,\n}\n\nexport enum FailureReason {\n None,\n CommitteeFormationTimeout,\n InsufficientCommitteeMembers,\n DKGTimeout,\n DKGInvalidShares,\n NoInputsReceived,\n ComputeTimeout,\n ComputeProviderExpired,\n ComputeProviderFailed,\n RequesterCancelled,\n DecryptionTimeout,\n DecryptionInvalidShares,\n VerificationFailed,\n}\n"],"mappings":";AAMA;AAAA,EAOE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AAEpC,SAAS,oCAAoC,oBAAoB,+BAA+B;;;ACfhG,SAA0D,2BAA2B;AAG9E,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,eAAe,SAAqC;AACl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Ae;AAAA,MACjB,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,mCAAmC,KAAK,IAAI,yBAAyB;AAAA,IAC1F;AAAA,EACF;AACF;","names":["E3Stage","FailureReason"]}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/contract-client.ts","../../src/utils.ts","../../src/contracts/types.ts"],"sourcesContent":["// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport {\n type Abi,\n type Chain,\n type Hash,\n type PublicClient,\n type TransactionReceipt,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n webSocket,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\n\nimport { CiphernodeRegistryOwnable__factory, Interfold__factory, InterfoldToken__factory } from '@interfold/contracts/types'\nimport type { ContractAddresses, E3, E3RequestParams, E3Stage, FailureReason } from './types'\nimport { validateCommitteeSize } from './types'\nimport { SDKError, isValidAddress } from '../utils'\n\nexport interface ContractClientConfig {\n publicClient: PublicClient\n walletClient?: WalletClient\n contracts: ContractAddresses\n}\n\nexport class ContractClient {\n private publicClient: PublicClient\n private walletClient?: WalletClient\n private contracts: ContractAddresses\n private contractInfo: {\n interfold: { address: `0x${string}`; abi: Abi }\n ciphernodeRegistry: { address: `0x${string}`; abi: Abi }\n feeToken: { address: `0x${string}`; abi: Abi }\n }\n\n constructor(config: ContractClientConfig) {\n const { publicClient, walletClient, contracts } = config\n\n if (!isValidAddress(contracts.interfold)) {\n throw new SDKError('Invalid Interfold contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.ciphernodeRegistry)) {\n throw new SDKError('Invalid CiphernodeRegistry contract address', 'INVALID_ADDRESS')\n }\n if (!isValidAddress(contracts.feeToken)) {\n throw new SDKError('Invalid FeeToken contract address', 'INVALID_ADDRESS')\n }\n\n this.publicClient = publicClient\n this.walletClient = walletClient\n this.contracts = contracts\n\n this.contractInfo = {\n interfold: {\n address: contracts.interfold,\n abi: Interfold__factory.abi,\n },\n ciphernodeRegistry: {\n address: contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n },\n feeToken: {\n address: contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n },\n }\n }\n\n public static create(options: {\n rpcUrl: string\n contracts: ContractAddresses\n privateKey?: `0x${string}`\n chain: Chain\n }): ContractClient {\n const isWebSocket = options.rpcUrl.startsWith('ws://') || options.rpcUrl.startsWith('wss://')\n const transport = isWebSocket\n ? webSocket(options.rpcUrl, {\n keepAlive: { interval: 30_000 },\n reconnect: { attempts: 5, delay: 2_000 },\n })\n : http(options.rpcUrl)\n\n const publicClient = createPublicClient({\n chain: options.chain,\n transport,\n }) as PublicClient\n\n let walletClient: WalletClient | undefined\n if (options.privateKey) {\n const account = privateKeyToAccount(options.privateKey)\n walletClient = createWalletClient({\n account,\n chain: options.chain,\n transport,\n })\n }\n\n return new ContractClient({ publicClient, walletClient, contracts: options.contracts })\n }\n\n public getPublicClient(): PublicClient {\n return this.publicClient\n }\n\n public async approveFeeToken(amount: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.feeToken,\n abi: InterfoldToken__factory.abi,\n functionName: 'approve',\n args: [this.contracts.interfold, amount],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to approve fee token: ${error}`, 'APPROVE_FEE_TOKEN_FAILED')\n }\n }\n\n public async requestE3(params: E3RequestParams): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const committeeSize = validateCommitteeSize(params.committeeSize)\n const maxFee = params.maxFee ?? (await this.getE3Quote(params))\n const expectedCryptoConfigId = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'activeCryptoConfigId',\n })\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'request',\n args: [\n {\n committeeSize,\n inputWindow: params.inputWindow,\n e3Program: params.e3Program,\n paramSet: params.paramSet,\n computeProviderParams: params.computeProviderParams,\n customParams: params.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId,\n maxFee,\n },\n ],\n account,\n gas: params.gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to request E3: ${error}`, 'REQUEST_E3_FAILED')\n }\n }\n\n public async cancelE3(e3Id: bigint): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n try {\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'cancelE3',\n args: [e3Id],\n account,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to cancel E3: ${error}`, 'CANCEL_E3_FAILED')\n }\n }\n\n public async publishCiphertextOutput(\n e3Id: bigint,\n ciphertextOutput: `0x${string}`,\n ciphertextCommitment: `0x${string}`,\n proof: `0x${string}`,\n gasLimit?: bigint,\n ): Promise<Hash> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for write operations', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const { request } = await this.publicClient.simulateContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'publishCiphertextOutput',\n args: [e3Id, ciphertextOutput, ciphertextCommitment, proof],\n account,\n gas: gasLimit,\n })\n\n return await this.walletClient.writeContract(request)\n } catch (error) {\n throw new SDKError(`Failed to publish ciphertext output: ${error}`, 'PUBLISH_CIPHERTEXT_OUTPUT_FAILED')\n }\n }\n\n public async getE3(e3Id: bigint): Promise<E3> {\n try {\n const result: E3 = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3: ${error}`, 'GET_E3_FAILED')\n }\n }\n\n public async getE3Quote(requestParams: E3RequestParams): Promise<bigint> {\n try {\n const committeeSize = validateCommitteeSize(requestParams.committeeSize)\n const expectedCryptoConfigId = await this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'activeCryptoConfigId',\n })\n\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Quote',\n args: [\n {\n committeeSize,\n inputWindow: requestParams.inputWindow,\n e3Program: requestParams.e3Program,\n paramSet: requestParams.paramSet,\n computeProviderParams: requestParams.computeProviderParams,\n customParams: requestParams.customParams || '0x',\n expectedFeeToken: this.contracts.feeToken,\n expectedCryptoConfigId,\n maxFee: requestParams.maxFee ?? 0n,\n },\n ],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 quote: ${error}`, 'GET_E3_QUOTE_FAILED')\n }\n }\n\n public async getFailureReason(e3Id: bigint): Promise<FailureReason> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getFailureReason',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get failure reason: ${error}`, 'GET_FAILURE_REASON_FAILED')\n }\n }\n\n public async getE3PublicKey(e3Id: bigint): Promise<`0x${string}`> {\n try {\n const result: `0x${string}` = await this.publicClient.readContract({\n address: this.contracts.ciphernodeRegistry,\n abi: CiphernodeRegistryOwnable__factory.abi,\n functionName: 'committeePublicKey',\n args: [e3Id],\n })\n\n return result\n } catch (error) {\n throw new SDKError(`Failed to get E3 public key: ${error}`, 'GET_E3_PUBLIC_KEY_FAILED')\n }\n }\n\n public async getE3Stage(e3Id: bigint): Promise<E3Stage> {\n try {\n return this.publicClient.readContract({\n address: this.contracts.interfold,\n abi: Interfold__factory.abi,\n functionName: 'getE3Stage',\n args: [e3Id],\n })\n } catch (error) {\n throw new SDKError(`Failed to get E3 stage: ${error}`, 'GET_E3_STAGE_FAILED')\n }\n }\n\n public async estimateGas(\n functionName: string,\n args: readonly unknown[],\n contractAddress: `0x${string}`,\n abi: Abi,\n value?: bigint,\n ): Promise<bigint> {\n if (!this.walletClient) {\n throw new SDKError('Wallet client required for gas estimation', 'NO_WALLET')\n }\n\n try {\n const account = this.walletClient.account\n if (!account) {\n throw new SDKError('No account connected', 'NO_ACCOUNT')\n }\n\n const estimateParams = {\n address: contractAddress,\n abi,\n functionName,\n args,\n account,\n ...(value !== undefined && { value }),\n }\n\n return await this.publicClient.estimateContractGas(estimateParams)\n } catch (error) {\n throw new SDKError(`Failed to estimate gas: ${error}`, 'GAS_ESTIMATION_FAILED')\n }\n }\n\n public async waitForTransaction(hash: Hash): Promise<TransactionReceipt> {\n try {\n return await this.publicClient.waitForTransactionReceipt({\n hash,\n confirmations: 1,\n })\n } catch (error) {\n throw new SDKError(`Failed to wait for transaction: ${error}`, 'TRANSACTION_WAIT_FAILED')\n }\n }\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { type Address, type Hash, type Log, PublicClient, encodeAbiParameters } from 'viem'\nimport type { BfvParams } from './types'\n\nexport class SDKError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n }\n}\n\nexport function isValidAddress(address: string): address is Address {\n return /^0x[a-fA-F0-9]{40}$/.test(address)\n}\n\nexport function isValidHash(hash: string): hash is Hash {\n return /^0x[a-fA-F0-9]{64}$/.test(hash)\n}\n\nexport function formatEventName(contractName: string, eventName: string): string {\n return `${contractName}.${eventName}`\n}\n\nexport function parseEventData<T>(log: Log): T {\n return log.data as unknown as T\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport const sleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport function formatBigInt(value: bigint): string {\n return value.toString()\n}\n\nexport function parseBigInt(value: string): bigint {\n return BigInt(value)\n}\n\nexport function generateEventId(log: Log): string {\n return `${log.blockHash}-${log.logIndex}`\n}\n\n/**\n * Get the current timestamp in seconds\n * from onchain\n * @param publicClient - The public client to use\n */\nexport async function getCurrentTimestamp(publicClient: PublicClient): Promise<bigint> {\n const block = await publicClient.getBlock()\n return block.timestamp\n}\n\n// Compute provider parameters structure\nexport interface ComputeProviderParams {\n name: string\n parallel: boolean\n batch_size: number\n}\n\n// Default compute provider configuration\nexport const DEFAULT_COMPUTE_PROVIDER_PARAMS: ComputeProviderParams = {\n name: 'risc0',\n parallel: false,\n batch_size: 2,\n}\n\n// Default E3 configuration (`committeeSize` is `IInterfold.CommitteeSize`, not circuit N_PARTIES).\nexport const DEFAULT_E3_CONFIG = {\n committeeSize: 0, // CommitteeSize.Minimum\n duration: 1800, // 30 minutes in seconds\n payment_amount: '0', // 0 ETH in wei\n} as const\n\n/**\n * Encode BFV parameters for the smart contract\n * BFV (Brakerski-Fan-Vercauteren) is a type of fully homomorphic encryption\n */\nexport function encodeBfvParams(params: BfvParams): `0x${string}` {\n const { degree, plaintextModulus, moduli, error1Variance } = params\n\n if (error1Variance === undefined) {\n throw new SDKError(\n 'error1Variance is required in ProtocolParams. All BFV parameter sets must specify error1_variance.',\n 'MISSING_ERROR1_VARIANCE',\n )\n }\n\n return encodeAbiParameters(\n [\n {\n name: 'bfvParams',\n type: 'tuple',\n components: [\n { name: 'degree', type: 'uint256' },\n { name: 'plaintext_modulus', type: 'uint256' },\n { name: 'moduli', type: 'uint256[]' },\n { name: 'error1_variance', type: 'string' },\n ],\n },\n ],\n [\n {\n degree: BigInt(degree),\n plaintext_modulus: BigInt(plaintextModulus),\n moduli: [...moduli],\n error1_variance: error1Variance,\n },\n ],\n )\n}\n\n/**\n * Encode compute provider parameters for the smart contract'\n * If mock is true, the compute provider parameters will return 32 bytes of 0x00\n */\nexport function encodeComputeProviderParams(params: ComputeProviderParams, mock: boolean = false): `0x${string}` {\n if (mock) {\n return `0x${'00'.repeat(32)}` as `0x${string}`\n }\n\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n/**\n * Encode custom parameters for the smart contract.\n */\nexport function encodeCustomParams(params: Record<string, unknown>): `0x${string}` {\n const jsonString = JSON.stringify(params)\n const encoder = new TextEncoder()\n const bytes = encoder.encode(jsonString)\n\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n}\n\n// inputWindow[0] is always larger than now and dkg deadline\nexport const inputWindowStartBuffer = 15n\n\n/**\n * Calculate start window for E3 request\n * @dev This function can be used for testing purposes, or for E3s which need to start as soon as possible.\n * @param publicClient - The public client to use\n * @param duration - The duration of the input window in seconds\n * @param startBuffer - Buffer in seconds added to current timestamp for input window start\n */\nexport async function calculateInputWindow(\n publicClient: PublicClient,\n duration: number = DEFAULT_E3_CONFIG.duration,\n startBuffer: bigint = inputWindowStartBuffer,\n): Promise<[bigint, bigint]> {\n const now = await getCurrentTimestamp(publicClient)\n return [BigInt(now) + startBuffer, BigInt(now) + startBuffer + BigInt(duration)]\n}\n\n/**\n * Decode plaintextOutput bytes to get the actual result number\n */\nexport function decodePlaintextOutput(plaintextOutput: string): number | null {\n try {\n // Remove '0x' prefix if present\n const hex = plaintextOutput.startsWith('0x') ? plaintextOutput.slice(2) : plaintextOutput\n\n // Convert hex to bytes\n const bytes = new Uint8Array(hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [])\n\n if (bytes.length < 8) {\n console.warn('Plaintext output too short for u64 decoding')\n return null\n }\n\n // Decode first u64 (8 bytes) as little-endian\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const result = view.getBigUint64(0, true) // true for little-endian\n\n return Number(result)\n } catch (error) {\n console.error('Failed to decode plaintext output:', error)\n return null\n }\n}\n\n// Helper function to convert proof bytes to field elements\nexport function proofToFields(proof: Uint8Array): string[] {\n const fields: string[] = []\n for (let i = 0; i < proof.length; i += 32) {\n const chunk = proof.slice(i, i + 32)\n fields.push('0x' + Buffer.from(chunk).toString('hex'))\n }\n return fields\n}\n","// SPDX-License-Identifier: LGPL-3.0-only\n//\n// This file is provided WITHOUT ANY WARRANTY;\n// without even the implied warranty of MERCHANTABILITY\n// or FITNESS FOR A PARTICULAR PURPOSE.\n\nimport { SDKError } from '../utils'\n\nexport interface ContractAddresses {\n interfold: `0x${string}`\n ciphernodeRegistry: `0x${string}`\n feeToken: `0x${string}`\n}\n\n/** On-chain `IInterfold.CommitteeSize`: Minimum (N=3), Micro (N=9), Small (N=19). */\nexport enum CommitteeSize {\n Minimum = 0,\n Micro = 1,\n Small = 2,\n}\n\n/** Fail fast on out-of-range committee sizes before they hit the contract. */\nexport function validateCommitteeSize(value: number | CommitteeSize): CommitteeSize {\n if (!Number.isInteger(value) || value < CommitteeSize.Minimum || value > CommitteeSize.Small) {\n throw new SDKError(\n `Invalid committeeSize ${value}. Use CommitteeSize.Minimum (0), CommitteeSize.Micro (1), or CommitteeSize.Small (2).`,\n 'INVALID_COMMITTEE_SIZE',\n )\n }\n return value\n}\n\nexport enum ParamSet {\n Insecure512 = 0,\n Secure8192 = 1,\n}\n\nexport interface E3 {\n seed: bigint\n committeeSize: number\n requestBlock: bigint\n inputWindow: readonly [bigint, bigint]\n encryptionSchemeId: string\n e3Program: string\n paramSet: number\n decryptionVerifier: string\n committeePublicKey: string\n ciphertextOutput: string\n ciphertextCommitment: string\n plaintextOutput: string\n}\n\nexport interface RequestParams {\n gasLimit?: bigint\n}\n\nexport interface E3RequestParams extends RequestParams {\n committeeSize: number\n inputWindow: readonly [bigint, bigint]\n e3Program: `0x${string}`\n paramSet: number\n computeProviderParams: `0x${string}`\n customParams?: `0x${string}`\n /** Maximum fee token amount accepted. Defaults to a fresh quote. */\n maxFee?: bigint\n}\n\nexport enum E3Stage {\n None,\n Requested,\n CommitteeFinalized,\n KeyPublished,\n CiphertextReady,\n Complete,\n Failed,\n}\n\nexport enum FailureReason {\n None,\n CommitteeFormationTimeout,\n InsufficientCommitteeMembers,\n DKGTimeout,\n DKGInvalidShares,\n NoInputsReceived,\n ComputeTimeout,\n ComputeProviderExpired,\n ComputeProviderFailed,\n RequesterCancelled,\n DecryptionTimeout,\n DecryptionInvalidShares,\n VerificationFailed,\n}\n"],"mappings":";AAMA;AAAA,EAOE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AAEpC,SAAS,oCAAoC,oBAAoB,+BAA+B;;;ACdhG,SAA0D,2BAA2B;AAG9E,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,eAAe,SAAqC;AAClE,SAAO,sBAAsB,KAAK,OAAO;AAC3C;;;ACCO,SAAS,sBAAsB,OAA8C;AAClF,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,mBAAyB,QAAQ,eAAqB;AAC5F,UAAM,IAAI;AAAA,MACR,yBAAyB,KAAK;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAqCO,IAAK,UAAL,kBAAKA,aAAL;AACL,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA,EAAAA,kBAAA;AACA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,aAAO;AAAA,IACT,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,gCAAgC,KAAK,IAAI,0BAA0B;AAAA,IACxF;AAAA,EACF;AAAA,EAEA,MAAa,WAAW,MAAgC;AACtD,QAAI;AACF,aAAO,KAAK,aAAa,aAAa;AAAA,QACpC,SAAS,KAAK,UAAU;AAAA,QACxB,KAAK,mBAAmB;AAAA,QACxB,cAAc;AAAA,QACd,MAAM,CAAC,IAAI;AAAA,MACb,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,2BAA2B,KAAK,IAAI,qBAAqB;AAAA,IAC9E;AAAA,EACF;AAAA,EAEA,MAAa,YACX,cACA,MACA,iBACA,KACA,OACiB;AACjB,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,SAAS,6CAA6C,WAAW;AAAA,IAC7E;AAEA,QAAI;AACF,YAAM,UAAU,KAAK,aAAa;AAClC,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,SAAS,wBAAwB,YAAY;AAAA,MACzD;AAEA,YAAM,iBAAiB;AAAA,QACrB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAI,UAAU,UAAa,EAAE,MAAM;AAAA,MACrC;AAEA,aAAO,MAAM,KAAK,aAAa,oBAAoB,cAAc;AAAA,IACnE,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,2BAA2B,KAAK,IAAI,uBAAuB;AAAA,IAChF;AAAA,EACF;AAAA,EAEA,MAAa,mBAAmB,MAAyC;AACvE,QAAI;AACF,aAAO,MAAM,KAAK,aAAa,0BAA0B;AAAA,QACvD;AAAA,QACA,eAAe;AAAA,MACjB,CAAC;AAAA,IACH,SAAS,OAAO;AACd,YAAM,IAAI,SAAS,mCAAmC,KAAK,IAAI,yBAAyB;AAAA,IAC1F;AAAA,EACF;AACF;","names":["E3Stage","FailureReason"]}
|
package/dist/index.cjs
CHANGED
|
@@ -430,6 +430,11 @@ var ContractClient = class _ContractClient {
|
|
|
430
430
|
async getE3Quote(requestParams) {
|
|
431
431
|
try {
|
|
432
432
|
const committeeSize = validateCommitteeSize(requestParams.committeeSize);
|
|
433
|
+
const expectedCryptoConfigId = await this.publicClient.readContract({
|
|
434
|
+
address: this.contracts.interfold,
|
|
435
|
+
abi: import_types.Interfold__factory.abi,
|
|
436
|
+
functionName: "activeCryptoConfigId"
|
|
437
|
+
});
|
|
433
438
|
return this.publicClient.readContract({
|
|
434
439
|
address: this.contracts.interfold,
|
|
435
440
|
abi: import_types.Interfold__factory.abi,
|
|
@@ -443,7 +448,7 @@ var ContractClient = class _ContractClient {
|
|
|
443
448
|
computeProviderParams: requestParams.computeProviderParams,
|
|
444
449
|
customParams: requestParams.customParams || "0x",
|
|
445
450
|
expectedFeeToken: this.contracts.feeToken,
|
|
446
|
-
expectedCryptoConfigId
|
|
451
|
+
expectedCryptoConfigId,
|
|
447
452
|
maxFee: requestParams.maxFee ?? 0n
|
|
448
453
|
}
|
|
449
454
|
]
|