### Install and Run React Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/examples/react/README.md Commands to install dependencies and start the development server for the React example. ```bash cd examples/react pnpm install pnpm dev ``` -------------------------------- ### Install and Run React Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/examples/README.md Navigate to the react directory, install dependencies using pnpm, and start the development server. Access the examples at http://localhost:3000. ```bash cd react pnpm install pnpm dev ``` -------------------------------- ### Navigate to Example Directory and Develop Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/README.md Manually navigate to the example directory and start the development server to explore React components. ```sh cd example && pnpm dev ``` -------------------------------- ### Quickstart Cofhe SDK Permit Setup Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/sdk/decrypt-to-view.mdx Initialize the Cofhe SDK for web applications, connect to Viem clients, and ensure a self-permit is created or retrieved for automatic use with `decryptForView` during `.execute()` calls. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { chains } from '@cofhe/sdk/chains'; import { createPublicClient, createWalletClient, http } from 'viem'; import { sepolia } from 'viem/chains'; const config = createCofheConfig({ supportedChains: [chains.sepolia] }); const client = createCofheClient(config); declare const account: `0x${string}`; // ---cut--- const publicClient = createPublicClient({ chain: sepolia, transport: http(), }); const walletClient = createWalletClient({ chain: sepolia, transport: http(), account, }); await client.connect(publicClient, walletClient); // Creates a permit if needed, stores it, and selects it as the active permit. await client.permits.getOrCreateSelfPermit(); ``` -------------------------------- ### Add a New Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/examples/README.md Follow these steps to contribute a new example: create a framework-specific directory, add a README, list the example in this file, and update pnpm-workspace.yaml if necessary. ```bash examples/{framework}/ Add a `README.md` describing the example Update this file to list the new example Update `pnpm-workspace.yaml` if needed ``` -------------------------------- ### Run Interactive React Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/README.md Execute the interactive example to see the React components in action. Alternatively, navigate to the example directory and run `pnpm dev`. ```sh ./run-example.sh ``` -------------------------------- ### Build and Preview React Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/examples/react/README.md Commands to build the React example for production and preview it. ```bash pnpm build pnpm preview ``` -------------------------------- ### Install @cofhe/react and @cofhe/sdk Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/react/README.md Install the necessary packages for React integration and the core SDK. ```bash npm install @cofhe/react @cofhe/sdk # or pnpm add @cofhe/react @cofhe/sdk ``` -------------------------------- ### Environment Variable Configuration Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/test/setup/README.md Shows how environment variables are defined and used within the test setup. These variables are inlined at build time by tsup.config.ts, making them available in browser test environments. ```typescript export const TEST_PRIVATE_KEY = process.env.TEST_PRIVATE_KEY; export const TEST_LOCALCOFHE_PRIVATE_KEY = process.env.TEST_LOCALCOFHE_PRIVATE_KEY; export const PRIMARY_TEST_CHAIN = process.env.PRIMARY_TEST_CHAIN || "421614"; ``` -------------------------------- ### Install Mock Contracts with Foundry Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/mock-contracts/README.md Install the mock contracts package using forge for Foundry projects. ```bash forge install fhenixprotocol/cofhe-mock-contracts ``` -------------------------------- ### Setup Functions Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/foundry.mdx Functions for initializing and connecting the CofheClient. ```APIDOC ## `connect(uint256 pkey)` ### Description Stores the private key, derives the account address, and marks the client as ready. Must be called before all other functions. ### Parameters #### Path Parameters - **pkey** (uint256) - Required - The private key to connect with. ``` ```APIDOC ## `account()` ### Description Returns the address derived from the connected private key. ### Returns - **address** - The derived account address. ``` -------------------------------- ### Run Test Setup and Build Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/test/setup/README.md Execute the test setup script which deploys contracts and initializes the primary test chain, followed by building the distributable package. This command is typically run from the repository root. ```bash pnpm test:setup ``` -------------------------------- ### Install Mock Contracts with npm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/mock-contracts/README.md Install the mock contracts package using npm for use in your project. ```bash npm install @fhenixprotocol/cofhe-mock-contracts ``` -------------------------------- ### Project Structure Overview Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/examples/README.md This bash snippet outlines the directory structure of the CoFHE SDK examples, highlighting the current React example and planned directories for future framework integrations. ```bash examples/ ├── react/ # React example application │ ├── src/ │ ├── package.json │ └── README.md ├── vue/ # (Future) Vue.js examples ├── node/ # (Future) Node.js examples └── README.md # This file ``` -------------------------------- ### Install with Forge Git Submodule Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/foundry.mdx Install the foundry plugin and mock contracts as git submodules using forge install. ```bash forge install fhenixprotocol/foundry-plugin # @cofhe/foundry-plugin forge install fhenixprotocol/cofhe-mock-contracts # @cofhe/mock-contracts ``` -------------------------------- ### Run Development Server Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/README.md Use this command to start the local development server for the CofheSDK site. ```bash pnpm --filter @cofhe/site dev ``` -------------------------------- ### Install @cofhe/hardhat-3-plugin Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/hardhat-3-plugin/README.md Install the plugin using npm or pnpm. ```bash npm install @cofhe/hardhat-3-plugin # or pnpm add @cofhe/hardhat-3-plugin ``` -------------------------------- ### Encrypt Inputs and Monitor Encryption Steps Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/sdk/encrypting-inputs.mdx Encrypts a uint64 value and logs the start and end of each encryption step, including the duration for the end step. Requires client connection and setup. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { Encryptable, EncryptStep } from '@cofhe/sdk'; import { chains } from '@cofhe/sdk/chains'; import type { PublicClient, WalletClient } from 'viem'; const config = createCofheConfig({ supportedChains: [chains.sepolia] }); const cofheClient = createCofheClient(config); declare const publicClient: PublicClient; declare const walletClient: WalletClient; // ---cut--- await cofheClient.connect(publicClient, walletClient); const encrypted = await cofheClient .encryptInputs([Encryptable.uint64(10n)]) .onStep((step, ctx) => { // [!code focus] if (ctx?.isStart) console.log(`Starting: ${step}`); // [!code focus] if (ctx?.isEnd) console.log(`Done: ${step} (${ctx.duration}ms)`); // [!code focus] }) // [!code focus] .execute(); ``` -------------------------------- ### Install Cofhe SDK and Hardhat Plugin Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/quick-start.mdx Install the necessary packages for the Cofhe SDK and Hardhat plugin using npm, pnpm, or yarn. ```bash npm install @cofhe/hardhat-plugin@^0.4.0 @cofhe/sdk@^0.4.0 @fhenixprotocol/cofhe-contracts@^0.1.0 ``` ```bash pnpm add @cofhe/hardhat-plugin@^0.4.0 @cofhe/sdk@^0.4.0 @fhenixprotocol/cofhe-contracts@^0.1.0 ``` ```bash yarn add @cofhe/hardhat-plugin@^0.4.0 @cofhe/sdk@^0.4.0 @fhenixprotocol/cofhe-contracts@^0.1.0 ``` -------------------------------- ### Install @cofhe/abi Package Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/abi/README.md Install the package using npm, pnpm, or yarn. Ensure peer dependencies are met. ```bash npm install @cofhe/abi # or pnpm add @cofhe/abi # or yarn add @cofhe/abi ``` -------------------------------- ### Install @cofhe/sdk and uninstall cofhejs Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/migrating-from-cofhejs.mdx Before migrating, remove the old `cofhejs` package and install the new `@cofhe/sdk` using npm. ```bash npm uninstall cofhejs && npm install @cofhe/sdk ``` -------------------------------- ### Run Tests with Automatic Setup Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/test/setup/README.md Run all tests in the monorepo. This command automatically executes the test setup script before running the tests, ensuring a consistent environment. ```bash pnpm test ``` -------------------------------- ### React Project Structure Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/examples/react/README.md Overview of the directory structure for the React example project. Shows the organization of components, providers, and configuration files. ```tree react/ ├── src/ │ ├── components/ │ │ ├── examples/ # Component demonstrations │ │ │ ├── Overview.tsx │ │ │ ├── HooksExample.tsx │ │ │ └── CofheEncryptInputExample.tsx │ │ ├── Navigation.tsx # Sidebar navigation │ │ └── ComponentRenderer.tsx │ ├── providers/ │ │ └── ExampleProvider.tsx # CoFHE SDK setup │ ├── styles.css # Tailwind CSS │ ├── App.tsx │ └── main.tsx # App entry point ├── public/ ├── vite.config.ts # Vite + WASM configuration └── package.json ``` -------------------------------- ### Install @cofhe/foundry-plugin with pnpm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/foundry.mdx Install the foundry plugin using pnpm. This is a development dependency. ```bash pnpm add --save-dev @cofhe/foundry-plugin ``` -------------------------------- ### Complete Encrypted Counter Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat-3.mdx This example demonstrates encrypting a uint32, storing it on-chain, and verifying its plaintext value using Hardhat 3 and the Cofhe SDK. It requires the Cofhe SDK and Viem to be set up. ```typescript import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { network } from 'hardhat'; import { Encryptable, FheTypes } from '@cofhe/sdk'; describe('Encrypted counter', async () => { const { viem, cofhe } = await network.connect(); const publicClient = await viem.getPublicClient(); const [walletClient] = await viem.getWalletClients(); const simpleTestArtifact = /* your compiled SimpleTest artifact */; const deployHash = await walletClient.deployContract({ abi: simpleTestArtifact.abi, bytecode: simpleTestArtifact.bytecode.object as `0x${string}`, }); const deployReceipt = await publicClient.waitForTransactionReceipt({ hash: deployHash }); if (!deployReceipt.contractAddress) throw new Error('SimpleTest deployment failed'); const simpleTest = { address: deployReceipt.contractAddress, abi: simpleTestArtifact.abi } as const; it('encrypts, stores, and reads back a uint32', async () => { const client = await cofhe.createClientWithBatteries(walletClient); const [enc] = await client .encryptInputs([Encryptable.uint32(42n)]) .execute(); await walletClient.writeContract({ ...simpleTest, functionName: 'setValue', args: [enc], }); const ctHash = await publicClient.readContract({ ...simpleTest, functionName: 'getValueHash', }); await cofhe.mocks.expectPlaintext(ctHash, 42n); }); }); ``` -------------------------------- ### Initialize @cofhe/sdk client with Ethers v6 Adapter Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/migrating-from-cofhejs.mdx This example shows how to initialize `@cofhe/sdk` using an adapter for Ethers v6. It follows the new config-client-connect pattern and defers key fetching. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { Ethers6Adapter } from '@cofhe/sdk/adapters'; import { chains } from '@cofhe/sdk/chains'; const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); const { publicClient, walletClient } = await Ethers6Adapter( provider, signer ); await client.connect(publicClient, walletClient); ``` -------------------------------- ### Install CoFHE Hardhat Plugin and SDK Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat/getting-started.mdx Install the necessary packages for Hardhat FHE integration using npm, pnpm, or yarn. ```bash npm install @cofhe/hardhat-plugin @cofhe/sdk @fhenixprotocol/cofhe-contracts ``` ```bash pnpm add @cofhe/hardhat-plugin @cofhe/sdk @fhenixprotocol/cofhe-contracts ``` ```bash yarn add @cofhe/hardhat-plugin @cofhe/sdk @fhenixprotocol/cofhe-contracts ``` -------------------------------- ### Environment Variables for Test Setup Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/test/setup/README.md Lists environment variables used by the test setup script. These variables configure the deployer key, the primary test chain ID, and the deployer key for localcofhe. Note that `TEST_PRIVATE_KEY` is required. ```markdown TEST_PRIVATE_KEY PRIMARY_TEST_CHAIN TEST_LOCALCOFHE_PRIVATE_KEY ``` -------------------------------- ### Complete test example for Encrypted counter Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/hardhat-3-plugin/README.md This example demonstrates encrypting, storing, and decrypting a uint32 value on-chain using the cofhe SDK and Hardhat. It includes deploying a SimpleTest contract, encrypting a value, storing it, and then decrypting it off-chain for verification. ```typescript import { describe, it, beforeEach } from 'node:test'; import assert from 'node:assert/strict'; import { network } from 'hardhat'; import { Encryptable, FheTypes } from '@cofhe/sdk'; describe('Encrypted counter', async () => { const { viem, cofhe } = await network.connect(); const publicClient = await viem.getPublicClient(); const [walletClient] = await viem.getWalletClients(); const simpleTestArtifact = /* your compiled SimpleTest artifact */; const deployHash = await walletClient.deployContract({ abi: simpleTestArtifact.abi, bytecode: simpleTestArtifact.bytecode.object as `0x${string}`, }); const deployReceipt = await publicClient.waitForTransactionReceipt({ hash: deployHash }); if (!deployReceipt.contractAddress) throw new Error('SimpleTest deployment failed'); const simpleTest = { address: deployReceipt.contractAddress, abi: simpleTestArtifact.abi } as const; it('encrypts, stores, and decrypts a uint32', async () => { const client = await cofhe.createClientWithBatteries(walletClient); // Encrypt const [enc] = await client.encryptInputs([Encryptable.uint32(42n)]).execute(); // Store on-chain via SimpleTest await walletClient.writeContract({ ...simpleTest, functionName: 'setValue', args: [enc], }); const ctHash = (await publicClient.readContract({ ...simpleTest, functionName: 'getValueHash', })) as `0x${string}`; // Decrypt via view (off-chain, instant) const decryptedView = await client.decryptForView(ctHash, FheTypes.Uint32).execute(); assert.equal(decryptedView, 42n); // Alternatively, verify plaintext without decryption await cofhe.mocks.expectPlaintext(ctHash, 42n); }); }); ``` -------------------------------- ### Solidity: Hash plus proof function implementation Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/sdk/writing-encrypted-data-to-contract.mdx This is an example implementation of a Solidity function that uses the hash plus proof convention, allowing both the value and the sender. ```solidity function setValueHashPlusProof(externalEuint32 inValue, bytes calldata proof) external { storedValue = FHE.asEuint32(inValue, proof); FHE.allowThis(storedValue); FHE.allowSender(storedValue); } ``` -------------------------------- ### Basic Foundry Test Contract with CofheTest and CofheClient Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/foundry-plugin/README.md Inherit `CofheTest` in your test contract and initialize `CofheClient` in `setUp`. Connect the client to a user's private key before use. ```solidity import { CofheTest } from "@cofhe/foundry-plugin/CofheTest.sol"; import { CofheClient } from "@cofhe/foundry-plugin/CofheClient.sol"; contract MyTest is CofheTest { CofheClient client; MyContract target; uint256 constant USER_PKEY = 0xac09...; function setUp() public { deployMocks(); client = createCofheClient(); client.connect(USER_PKEY); target = new MyContract(); } function testEncryptAndStore() public { InEuint32 memory enc = client.createInEuint32(42); vm.prank(client.account()); target.store(enc); expectPlaintext(target.eValue(), uint32(42)); } } ``` -------------------------------- ### Hardhat Plugin Setup Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/mock-contracts/README.md Integrate the mock contracts into your Hardhat project by importing the plugin in your hardhat.config.ts. This automatically deploys mocks and enables the cofheClient to use them. ```typescript // hardhat.config.ts import 'cofhe-hardhat-plugin'; export default { cofhe: { logMocks: true, // optional }, }; ``` -------------------------------- ### Manual Permit Creation in cofhejs Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/migrating-from-cofhejs.mdx Shows how to manually create a permit using the older cofhejs library. This example highlights the explicit creation process when auto-generation is not desired. ```TypeScript // Auto-generated during init (default) await cofhejs.initializeWithEthers({ ethersProvider: provider, ethersSigner: signer, environment: 'TESTNET', // generatePermit: true ← default }); // Manual creation const result = await cofhejs.createPermit({ type: 'self', issuer: wallet.address, }); if (!result.success) { console.error(result.error); return; } ``` -------------------------------- ### Quick Start: FHE Contract Interaction Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/abi/README.md Demonstrates a full workflow for interacting with FHE smart contracts, including argument preparation, encryption, contract calls, and return value transformation. ```typescript import { extractEncryptableValues, insertEncryptedValues, transformEncryptedReturnTypes } from '@cofhe/abi'; import type { CofheInputArgs, CofheInputArgsPreTransform, CofheReturnType } from '@cofhe/abi'; import { encrypt } from '@cofhe/sdk'; const abi = [ { type: 'function', name: 'add', inputs: [ { name: 'a', type: 'uint256', internalType: 'uint256' }, { name: 'b', type: 'tuple', internalType: 'struct InEuint32', components: [...] } ], outputs: [{ name: '', type: 'uint256', internalType: 'euint32' }], stateMutability: 'nonpayable' } ] as const; // 1. Prepare arguments with primitive values const args: CofheInputArgsPreTransform = [100n, 200n]; // 2. Extract encryptable values const encryptables = extractEncryptableValues(abi, 'add', args); // ^? [Encryptable.uint32(200n)] // 3. Encrypt the values const encrypted = await encrypt(encryptables); // ^? [EncryptedUint32Input] // 4. Insert encrypted values back into arguments const encryptedArgs: CofheInputArgs = insertEncryptedValues(abi, 'add', args, encrypted); // ^? [100n, EncryptedUint32Input] // 5. Call contract and transform return value const result = await contract.add(...encryptedArgs); // ^? bigint // 6. Transform raw return value into correct encrypted value type const transformed: CofheReturnType = transformEncryptedReturnTypes(abi, 'add', result); // ^? Euint32 ``` -------------------------------- ### Run Hardhat Tests with Mocks Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/mock-contracts/README.md Execute your Hardhat tests or start a Hardhat node after integrating the mock contracts plugin. The plugin ensures mocks are deployed and available. ```bash npx hardhat test # or npx hardhat node ``` -------------------------------- ### Create CofheClient with Batteries in Hardhat Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat/client.mdx Use `createClientWithBatteries` for a one-liner setup that handles config, client creation, connection, and self-usage permit generation. Defaults to the first Hardhat signer if none is provided. ```typescript import '@cofhe/hardhat-plugin'; import '@nomicfoundation/hardhat-ethers'; // ---cut--- import hre from 'hardhat'; const [signer] = await hre.ethers.getSigners(); const cofheClient = await hre.cofhe.createClientWithBatteries(signer); // [!code focus] cofheClient.connected; // true ``` -------------------------------- ### Build Project for Production Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/README.md Execute this command to build the CofheSDK site for production deployment. ```bash pnpm --filter @cofhe/site build ``` -------------------------------- ### Install @cofhe/foundry-plugin with npm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/foundry.mdx Install the foundry plugin using npm. This is a development dependency. ```bash npm install --save-dev @cofhe/foundry-plugin ``` -------------------------------- ### Connect to Network and Initialize FHE Client Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/hardhat-3-plugin/README.md Demonstrates setting up the FHE environment within an async describe block. It automatically deploys mock contracts and attaches the 'cofhe' namespace to the network connection. ```typescript import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { network } from 'hardhat'; describe('My FHE contract', async () => { const { viem, cofhe } = await network.connect(); const publicClient = await viem.getPublicClient(); const [walletClient] = await viem.getWalletClients(); it('encrypts and decrypts a value', async () => { const client = await cofhe.createClientWithBatteries(walletClient); // ... test logic }); }); ``` -------------------------------- ### Install @cofhe/hardhat-3-plugin with pnpm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat-3.mdx Use pnpm to install the CoFHE Hardhat plugin as a development dependency. ```bash pnpm add --save-dev @cofhe/hardhat-3-plugin ``` -------------------------------- ### Preview Production Build Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/README.md Use this command to preview the production build of the CofheSDK site locally. ```bash pnpm --filter @cofhe/site preview ``` -------------------------------- ### Install @cofhe/hardhat-3-plugin with npm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat-3.mdx Use npm to install the CoFHE Hardhat plugin as a development dependency. ```bash npm install --save-dev @cofhe/hardhat-3-plugin ``` -------------------------------- ### Install @cofhe/hardhat-plugin with yarn Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat.mdx Install the Hardhat plugin using yarn. This command adds the plugin to your project dependencies. ```bash yarn add @cofhe/hardhat-plugin ``` -------------------------------- ### Initialize @cofhe/sdk client for Web (Viem) Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/migrating-from-cofhejs.mdx The new initialization process for `@cofhe/sdk` in a web environment using Viem. It uses a three-step config-client-connect flow and defers key fetching. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { chains } from '@cofhe/sdk/chains'; const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); await client.connect(publicClient, walletClient); ``` -------------------------------- ### Install @cofhe/hardhat-plugin with pnpm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat.mdx Install the Hardhat plugin using pnpm. This command adds the plugin to your project dependencies. ```bash pnpm add @cofhe/hardhat-plugin ``` -------------------------------- ### Initialize Cofhe SDK Client and Interact with Contract Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/intro.mdx Demonstrates the client lifecycle: configuration, connection to viem clients, encrypting inputs for contract deposit, and decrypting ciphertext handles for UI display. Ensure permits are managed for decryption. ```typescript import { type PublicClient, type WalletClient } from 'viem'; declare const publicClient: PublicClient; declare const walletClient: WalletClient; declare const contract: { deposit: (encrypted: any) => Promise; getBalance: () => Promise; }; // --- import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { Encryptable, FheTypes } from '@cofhe/sdk'; import { chains } from '@cofhe/sdk/chains'; const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); await client.connect(publicClient, walletClient); // Encrypt and send const [encrypted] = await client .encryptInputs([Encryptable.uint64(100n)]) .execute(); await contract.deposit(encrypted); // Decrypt for UI await client.permits.getOrCreateSelfPermit(); const ctHash = await contract.getBalance(); const balance = await client .decryptForView(ctHash, FheTypes.Uint64) .execute(); ``` -------------------------------- ### Create and Connect Client with Permits Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/sdk/permits.mdx This snippet demonstrates how to create a CoFHE client configuration, connect it to a public and wallet client, and then obtain or create a self-permit. The `getOrCreateSelfPermit` function is recommended for automatically managing permits. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { chains } from '@cofhe/sdk/chains'; import type { PublicClient, WalletClient } from 'viem'; const config = createCofheConfig({ supportedChains: [chains.sepolia] }); const client = createCofheClient(config); declare const publicClient: PublicClient; declare const walletClient: WalletClient; // ---cut--- await client.connect(publicClient, walletClient); // Returns the active self permit if one exists, otherwise creates and signs a new one. const permit = await client.permits.getOrCreateSelfPermit(); ``` -------------------------------- ### Install @cofhe/foundry-plugin with npm/pnpm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/foundry-plugin/README.md Install the foundry plugin using npm or pnpm. This command adds the package as a development dependency. ```sh npm install --save-dev @cofhe/foundry-plugin ``` -------------------------------- ### Initialize @cofhe/sdk client for Node (Viem) Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/migrating-from-cofhejs.mdx The new initialization process for `@cofhe/sdk` in a Node.js environment using Viem. It uses a three-step config-client-connect flow and defers key fetching. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/node'; import { chains } from '@cofhe/sdk/chains'; const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); await client.connect(publicClient, walletClient); ``` -------------------------------- ### Create and Connect CofheClient Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/hardhat-3-plugin/README.md Initializes a CofheClient using a configuration object and then connects it to the Viem public and wallet clients. This client is not connected by default. ```typescript const config = await cofhe.createConfig(); const client = cofhe.createClient(config); await client.connect(publicClient, walletClient); ``` -------------------------------- ### Initialize, Encrypt, and Decrypt with @cofhe/sdk (After) Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/migrating-from-cofhejs.mdx Demonstrates the equivalent process using the new @cofhe/sdk with Ethers.js. It uses a new initialization pattern with adapters and a more streamlined encryption/decryption API. ```typescript // @noErrors import { createCofheConfig, createCofheClient } from '@cofhe/sdk/node'; import { Encryptable, FheTypes, EncryptStep } from '@cofhe/sdk'; import { Ethers6Adapter } from '@cofhe/sdk/adapters'; import { chains } from '@cofhe/sdk/chains'; import { ethers } from 'ethers'; declare const PRIVATE_KEY: string; declare const contract: any; // 1. Initialize const provider = new ethers.JsonRpcProvider('https://rpc.sepolia.org'); const wallet = new ethers.Wallet(PRIVATE_KEY, provider); const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); const { publicClient, walletClient } = await Ethers6Adapter( provider, wallet ); await client.connect(publicClient, walletClient); // 2. Encrypt const [eAmount] = await client .encryptInputs([Encryptable.uint64(100n)]) .onStep((step) => console.log(step)) .execute(); // 3. Send transaction await contract.deposit(eAmount); // 4. Create permit & decrypt await client.permits.getOrCreateSelfPermit(); const ctHash = await contract.getBalance(); const balance = await client .decryptForView(ctHash, FheTypes.Uint64) .execute(); console.log(balance); ``` -------------------------------- ### Install @cofhe/hardhat-plugin with npm Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat.mdx Install the Hardhat plugin using npm. This is the first step to enable FHE development capabilities in your Hardhat project. ```bash npm install @cofhe/hardhat-plugin ``` -------------------------------- ### Install CoFHE Hardhat Plugin Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/hardhat-plugin/README.md Install the plugin using npm, yarn, or pnpm. This is the first step to integrating FHE capabilities into your Hardhat project. ```bash npm install cofhe-hardhat-plugin # or yarn add cofhe-hardhat-plugin # or pnpm add cofhe-hardhat-plugin ``` -------------------------------- ### Create Turborepo Project with Changesets Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/README.md Use this command to initialize a new Turborepo project with Changesets for versioning and publishing. ```sh npx create-turbo@latest -e with-changesets ``` -------------------------------- ### Set up CofheClient in Hardhat Tests Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/hardhat/testing.mdx Use `hre.cofhe.createClientWithBatteries` in a `before` hook to create and connect a fully configured `CofheClient` for each test suite. This includes a self-permit, making the client ready for all tests. ```typescript import '@cofhe/hardhat-plugin'; import '@nomicfoundation/hardhat-ethers'; import hre from 'hardhat'; import { CofheClient } from '@cofhe/sdk'; import { HardhatEthersSigner } from '@nomicfoundation/hardhat-ethers/signers'; let cofheClient: CofheClient; let signer: HardhatEthersSigner; before(async () => { [signer] = await hre.ethers.getSigners(); cofheClient = await hre.cofhe.createClientWithBatteries(signer); // [!code focus] }); ``` -------------------------------- ### Create and Sign Self Permit with PermitUtils Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/sdk/permits.mdx This snippet shows how to use the lower-level `PermitUtils` to create and sign a self-permit. It also demonstrates the manual steps of storing and activating the permit using `setPermit` and `setActivePermitHash`. ```typescript import { PermitUtils, setPermit, setActivePermitHash, } from '@cofhe/sdk/permits'; import type { PublicClient, WalletClient } from 'viem'; declare const publicClient: PublicClient; declare const walletClient: WalletClient; // ---cut--- const permit = await PermitUtils.createSelfAndSign( { issuer: walletClient.account!.address }, publicClient, walletClient ); // Manually store and activate the permit const chainId = await publicClient.getChainId(); const account = walletClient.account!.address; setPermit(chainId, account, permit); setActivePermitHash(chainId, account, permit.hash); ``` -------------------------------- ### Type Alias Migration Example Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/README.md Illustrates the migration of a type alias from `CofheInUint8` to `EncryptedUint8Input`. ```typescript Type `CofheInUint8` -> `EncryptedUint8Input` ``` -------------------------------- ### cofhe.createClientWithBatteries Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/hardhat-3-plugin/README.md Creates and fully initializes a CofheClient in a single step. It configures the client for Hardhat, connects it, and sets up a self-permit for immediate decryption capabilities. ```APIDOC ## `cofhe.createClientWithBatteries(walletClient?)` ### Description Creates a fully initialized `CofheClient` in one call — configures it for Hardhat, connects it, and creates a self-permit so it can decrypt encrypted FHE variables out of the box. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `walletClient` (ViemWalletClient) - Optional - A specific account-bound wallet client to use. If not provided, the first account from the connection is used automatically. ### Returns A fully initialized and connected `CofheClient` instance. ``` -------------------------------- ### Foundry TOML Configuration Source: https://github.com/fhenixprotocol/cofhesdk/blob/master/packages/site/pages/foundry.mdx Configure remappings in your foundry.toml file to use the installed foundry plugin and its dependencies. ```toml [profile.default] src = "contracts" out = "out" libs = ["node_modules", "lib"] remappings = [ "@cofhe/foundry-plugin/=node_modules/@cofhe/foundry-plugin/", "@cofhe/mock-contracts/=node_modules/@cofhe/mock-contracts/", "@fhenixprotocol/cofhe-contracts/=node_modules/@fhenixprotocol/cofhe-contracts/", "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/", "forge-std/=node_modules/forge-std/src/", ] ```