### Native Wrapper Example Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Example of deploying a wrapper for native ETH. ```APIDOC ## Native Wrapper Example ### Description Demonstrates how to deploy a wrapper for native ETH, enabling it to be shielded and managed within the FHErc20 system. ### Contract Definition ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.25; import { FHERC20NativeWrapper } from "@fhenixprotocol/confidential-contracts/contracts/FHERC20/extensions/FHERC20NativeWrapper.sol"; contract ShieldedETH is FHERC20NativeWrapper { constructor(address wethAddress) FHERC20NativeWrapper(wethAddress, "Shielded ETH", "sETH") {} } ``` ``` -------------------------------- ### Install SDK and Dependencies Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start/javascript Install the @cofhe/sdk and viem packages using npm, pnpm, or yarn. ```bash npm install @cofhe/sdk@^0.5.1 viem ``` ```bash pnpm add @cofhe/sdk@^0.5.1 viem ``` ```bash yarn add @cofhe/sdk@^0.5.1 viem ``` -------------------------------- ### ERC20 Wrapper Example Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Example of deploying a wrapper for an existing ERC20 token. ```APIDOC ## ERC20 Wrapper Example ### Description Demonstrates how to deploy a contract that wraps an existing ERC20 token, making it compatible with FHErc20 functionalities. ### Contract Definition ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.25; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { FHERC20ERC20Wrapper } from "@fhenixprotocol/confidential-contracts/contracts/FHERC20/extensions/FHERC20ERC20Wrapper.sol"; contract MyTokenWrapper is FHERC20ERC20Wrapper { constructor(IERC20 underlyingToken) FHERC20ERC20Wrapper(underlyingToken, "Shielded MTK", "sMTK") {} } ``` ``` -------------------------------- ### Install and Initialize Client SDK Source: https://cofhe-docs.fhenix.zone/deep-dive/data-flows/encryption-request-flow Install the Client SDK using npm. Import necessary modules for encryption and client creation. ```bash npm install @cofhe/sdk ``` ```javascript const { Encryptable, FheTypes } = require("@cofhe/sdk"); const { createCofheConfig, createCofheClient } = require("@cofhe/sdk/node"); ``` -------------------------------- ### Clone Foundry Starter Project Source: https://cofhe-docs.fhenix.zone/client-sdk/examples/templates Clone this template to start building FHE contracts with Foundry immediately. Includes installation and testing commands. ```bash git clone https://github.com/FhenixProtocol/cofhe-foundry-starter.git cd cofhe-foundry-starter npm install forge build forge test -vvv ``` -------------------------------- ### Install FHE SDK and Viem Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start Install the necessary packages for the FHE client SDK and Viem for blockchain interaction. ```bash npm install @cofhe/sdk@^0.5.1 viem ``` -------------------------------- ### Clone Hardhat Starter Project Source: https://cofhe-docs.fhenix.zone/client-sdk/examples/templates Clone this template to start building FHE contracts with Hardhat immediately. Includes installation and testing commands. ```bash git clone https://github.com/FhenixProtocol/cofhe-hardhat-starter.git cd cofhe-hardhat-starter npm install npx hardhat test ``` -------------------------------- ### Install Dependencies with npm, pnpm, or yarn Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start/foundry Install the necessary CoFHE packages and forge-std as development dependencies. Ensure Node.js 18+ is installed. ```bash npm install -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts forge install foundry-rs/forge-std ``` ```bash pnpm add -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts forge install foundry-rs/forge-std ``` ```bash yarn add -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts forge install foundry-rs/forge-std ``` -------------------------------- ### Install Dependencies with npm, pnpm, or yarn Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start/hardhat Install the necessary Fhenix SDK and Hardhat plugin packages using your preferred package manager. ```bash npm install @cofhe/hardhat-plugin@^0.5.1 @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` ```bash pnpm add @cofhe/hardhat-plugin@^0.5.1 @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` ```bash yarn add @cofhe/hardhat-plugin@^0.5.1 @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### CofheTest Setup Source: https://cofhe-docs.fhenix.zone/client-sdk/reference/foundry-reference Functions to set up the testing environment by deploying mock contracts and creating a CofheClient. ```APIDOC ## `CofheTest` ### Setup | Function | | --------------------- | | `deployMocks()` | | `createCofheClient()` | ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://cofhe-docs.fhenix.zone/fhe-library/introduction/quick-start Install all necessary project dependencies using the pnpm package manager. Ensure Node.js v20 or later is installed. ```bash pnpm install ``` -------------------------------- ### Install Cofhe SDK and Contracts with npm Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Use this command to install the core Cofhe SDK and its associated smart contract library using npm. ```bash npm install @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### Install forge-std Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/getting-started Install the forge-std library, which is a dependency for the plugin. ```bash forge install foundry-rs/forge-std ``` -------------------------------- ### Install Cofhe SDK and Contracts with pnpm Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Use this command to install the core Cofhe SDK and its associated smart contract library using pnpm. ```bash pnpm add @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### Install @cofhe/sdk Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/migrating-from-cofhejs Uninstall the old cofhejs package and install the new @cofhe/sdk using npm. ```bash npm uninstall cofhejs && npm install @cofhe/sdk ``` -------------------------------- ### Install Cofhe SDK and Contracts with yarn Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Use this command to install the core Cofhe SDK and its associated smart contract library using yarn. ```bash yarn add @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### Install Cofhe SDK, Contracts, and Hardhat Plugin with pnpm Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Install the Cofhe SDK, contracts, and the Hardhat plugin using pnpm for Hardhat projects. ```bash pnpm add @cofhe/hardhat-plugin@^0.5.1 @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### Setup Permit Source: https://cofhe-docs.fhenix.zone/client-sdk/guides/decrypt-to-view Connect to the client and create or retrieve a permit if one doesn't exist. This permit is then used for subsequent decryption operations. ```typescript await client.connect(publicClient, walletClient); // Creates a permit if needed, stores it, and selects it as the active permit. await client.permits.getOrCreateSelfPermit(); ``` -------------------------------- ### Install Cofhe SDK, Contracts, and Hardhat Plugin with npm Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Install the Cofhe SDK, contracts, and the Hardhat plugin using npm for Hardhat projects. ```bash npm install @cofhe/hardhat-plugin@^0.5.1 @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### Full Client SDK Flow Example Source: https://cofhe-docs.fhenix.zone/fhe-library/introduction/quick-start Demonstrates a complete client-side interaction flow including encrypting inputs, interacting with a contract, and decrypting results for viewing. ```typescript it('Full Client SDK flow', async function () { const [bob] = await hre.ethers.getSigners() const CounterFactory = await hre.ethers.getContractFactory('Counter') const counter = await CounterFactory.connect(bob).deploy() // Create a connected client (batteries included) const client = await hre.cofhe.createClientWithBatteries(bob) // Encrypt a value const [encryptedInput] = await client .encryptInputs([Encryptable.uint32(5n)]) .onStep((step) => console.log(`Encrypt step - ${step}`)) .execute() // Use the encrypted input to reset the counter await counter.connect(bob).reset(encryptedInput) // Fetch the hash of the encrypted counter value const encryptedValue = await counter.count() // Decrypt the value (view decryption) const result = await client .decryptForView(encryptedValue, FheTypes.Uint32) .withPermit() .execute() // Check the decrypted result expect(result).equal(5n) }) ``` -------------------------------- ### Install Cofhe SDK, Contracts, and Hardhat Plugin with yarn Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Install the Cofhe SDK, contracts, and the Hardhat plugin using yarn for Hardhat projects. ```bash yarn add @cofhe/hardhat-plugin@^0.5.1 @cofhe/sdk@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 ``` -------------------------------- ### Install Cofhe Foundry Plugin Dependencies (pnpm) Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/getting-started Install the plugin and its dependencies as dev dependencies using pnpm. ```bash pnpm add -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts ``` -------------------------------- ### Allow Other Contracts Example Source: https://cofhe-docs.fhenix.zone/tutorials/acl-usage-examples Example demonstrating how to grant access to other contracts, either persistently or for a single transaction. ```APIDOC ## Allow Other Contracts You can also allow other contracts to use your ciphertexts, either persistently or only for the course of this transaction via `FHE.allowTransient(handle, address)`. ```solidity theme={null} contract A { function doAdd(InEuint32 input1) { euint32 handle1 = FHE.asEuint32(input1); // Contract A gets temporary ownership of handle1 FHE.allowTransient(handle1, addressB); // Contract B is allowed to use handle1 in this transaction alone // or FHE.allow(handle1, addressB); // Contract B is allowed to use handle1 forever IContractB(addressB).doSomethingWithHandle1(handle1); } } ``` ``` -------------------------------- ### Install @cofhe/hardhat-plugin with npm Source: https://cofhe-docs.fhenix.zone/client-sdk/hardhat-plugin/getting-started Install the necessary packages for Hardhat FHE development using npm. ```bash npm install @cofhe/hardhat-plugin @cofhe/sdk @cofhe/mock-contracts @fhenixprotocol/cofhe-contracts ``` -------------------------------- ### Install @cofhe/hardhat-plugin with pnpm Source: https://cofhe-docs.fhenix.zone/client-sdk/hardhat-plugin/getting-started Install the necessary packages for Hardhat FHE development using pnpm. ```bash pnpm add @cofhe/hardhat-plugin @cofhe/sdk @cofhe/mock-contracts @fhenixprotocol/cofhe-contracts ``` -------------------------------- ### Install @cofhe/hardhat-plugin with yarn Source: https://cofhe-docs.fhenix.zone/client-sdk/hardhat-plugin/getting-started Install the necessary packages for Hardhat FHE development using yarn. ```bash yarn add @cofhe/hardhat-plugin @cofhe/sdk @cofhe/mock-contracts @fhenixprotocol/cofhe-contracts ``` -------------------------------- ### Format Specification Prompt for FHE Tutorial Source: https://cofhe-docs.fhenix.zone/get-started/build-with-ai/build-with-ai Request the AI to structure its response as a tutorial, including code examples for FHE operations, explanations, and best practices for gas optimization. ```markdown Please structure your response as a tutorial with: - Code examples for encrypting and decrypting data - Explanations of each FHE operation - Best practices for gas optimization ``` -------------------------------- ### Install Cofhe Foundry Plugin and Dependencies with yarn Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Install the Cofhe Foundry plugin, mock contracts, Cofhe contracts, OpenZeppelin contracts, and forge-std using yarn. ```bash yarn add -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts forge install foundry-rs/forge-std ``` -------------------------------- ### Install Cofhe Foundry Plugin and Dependencies with pnpm Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Install the Cofhe Foundry plugin, mock contracts, Cofhe contracts, OpenZeppelin contracts, and forge-std using pnpm. ```bash pnpm add -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts forge install foundry-rs/forge-std ``` -------------------------------- ### Install Cofhe Foundry Plugin and Dependencies with npm Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/installation Install the Cofhe Foundry plugin, mock contracts, Cofhe contracts, OpenZeppelin contracts, and forge-std using npm. ```bash npm install -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts forge install foundry-rs/forge-std ``` -------------------------------- ### Install Cofhe Foundry Plugin Dependencies (yarn) Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/getting-started Install the plugin and its dependencies as dev dependencies using yarn. ```bash yarn add -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts ``` -------------------------------- ### Verify Cofhe Foundry Plugin Setup Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/getting-started Run `forge build` to verify your remappings and `foundry.toml` configuration. Then, run `forge test` to ensure tests can be executed. ```bash forge build forge test ``` -------------------------------- ### Install Cofhe Foundry Plugin Dependencies (npm) Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/getting-started Install the plugin and its dependencies as dev dependencies using npm. ```bash npm install -D @cofhe/foundry-plugin@^0.5.1 @cofhe/mock-contracts@^0.5.1 @fhenixprotocol/cofhe-contracts@^0.1.3 @openzeppelin/contracts ``` -------------------------------- ### Create and Connect Client (Node.js) Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start/javascript Configure and create a Cofhe client for Node.js scripts, including viem clients and account setup using a private key. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/node'; import { chains } from '@cofhe/sdk/chains'; import { createPublicClient, createWalletClient, http } from 'viem'; import { sepolia } from 'viem/chains'; import { privateKeyToAccount } from 'viem/accounts'; // 1. Configure const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); // 2. Create viem clients const account = privateKeyToAccount('0xYOUR_PRIVATE_KEY'); const publicClient = createPublicClient({ chain: sepolia, transport: http(), }); const walletClient = createWalletClient({ chain: sepolia, transport: http(), account, }); // 3. Connect await client.connect(publicClient, walletClient); ``` -------------------------------- ### Deploy FH-ERC20 Native Wrapper Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Example of deploying a wrapper contract for native ETH. Requires the address of the WETH contract. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.25; import { FHERC20NativeWrapper } from "@fhenixprotocol/confidential-contracts/contracts/FHERC20/extensions/FHERC20NativeWrapper.sol"; // Deploy a wrapper for native ETH contract ShieldedETH is FHERC20NativeWrapper { constructor(address wethAddress) FHERC20NativeWrapper(wethAddress, "Shielded ETH", "sETH") {} } ``` -------------------------------- ### Test Setup with CofheClient Source: https://cofhe-docs.fhenix.zone/client-sdk/hardhat-plugin/testing Use `hre.cofhe.createClientWithBatteries` in a `before` hook to create and connect a fully configured `CofheClient` for testing. This includes a self-permit, making the client ready for all tests in the suite. ```typescript 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); }); ``` -------------------------------- ### Operator Full Access Example Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/operators Demonstrates how an operator can transfer the entire balance of a holder's tokens. Only grant operator permissions to trusted addresses. ```solidity euint64 balance = token.confidentialBalanceOf(holder); token.confidentialTransferFrom(holder, attacker, balance); ``` -------------------------------- ### Write a Test Inheriting CofheTest Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/getting-started Create a test file that inherits from `CofheTest` and calls `deployMocks()` in the `setUp()` function to deploy the CoFHE mock stack. ```solidity import { CofheTest } from "@cofhe/foundry-plugin/contracts/CofheTest.sol"; contract MyTest is CofheTest { function setUp() public { deployMocks(); // ... your contract deploys } } ``` -------------------------------- ### FHE RC20 Operator Workflow Example Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/operators Demonstrates the complete lifecycle of an operator: granting permission, performing a confidential transfer as an operator, and the automatic revocation after expiration. ```solidity // 1. Token holder grants operator permission await token.connect(holder).setOperator( operatorAddress, Math.floor(Date.now() / 1000) + 86400 // 1 day from now ); // 2. Operator can now transfer on behalf of holder const [encryptedAmount] = await cofheClient .encryptInputs([Encryptable.uint64(100n)]) .execute(); await token.connect(operator).confidentialTransferFrom( holderAddress, recipientAddress, encryptedAmount ); // 3. After expiration, operator can no longer transfer // (automatically revoked when timestamp passes) ``` -------------------------------- ### Deploy FH-ERC20 ERC20 Wrapper Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Example of deploying a wrapper contract for an existing ERC20 token. Requires the underlying ERC20 token contract address. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.25; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { FHERC20ERC20Wrapper } from "@fhenixprotocol/confidential-contracts/contracts/FHERC20/extensions/FHERC20ERC20Wrapper.sol"; // Deploy a wrapper for an existing ERC20 token contract MyTokenWrapper is FHERC20ERC20Wrapper { constructor(IERC20 underlyingToken) FHERC20ERC20Wrapper(underlyingToken, "Shielded MTK", "sMTK") {} } ``` -------------------------------- ### Basic FHE Operations with Direct Functions Source: https://cofhe-docs.fhenix.zone/fhe-library/reference/fhe-sol An example of performing encrypted arithmetic and comparison using direct FHE functions, followed by conditional logic and access control setup for decryption. ```solidity // Use secure encrypted input InEuint8 encryptedInputA; // Provided by client-side encryption InEuint8 encryptedInputB; // Provided by client-side encryption euint8 a = FHE.asEuint8(encryptedInputA); euint8 b = FHE.asEuint8(encryptedInputB); // Perform operations euint8 sum = FHE.add(a, b); // Encrypted addition euint8 product = FHE.mul(a, b); // Encrypted multiplication ebool isGreater = FHE.gt(b, a); // Encrypted comparison // Conditional logic euint8 result = FHE.select(isGreater, sum, product); // Grant access for future use and allow public decryption FHE.allowThis(result); FHE.allowPublic(result); // Off-chain: client calls decryptForTx(ctHash) to get plaintext + signature // On-chain: publish the verified result // FHE.publishDecryptResult(result, plaintext, signature); ``` -------------------------------- ### Initialize @cofhe/sdk (After) Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/migrating-from-cofhejs Demonstrates the new three-step initialization process for @cofhe/sdk using Viem clients for web or Node.js environments. ```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); ``` ```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); ``` -------------------------------- ### Quick Start: Create and Sign Self Permit Source: https://cofhe-docs.fhenix.zone/client-sdk/guides/permits Recommended approach using `client.permits` to automatically sign and manage permits. Alternatively, `PermitUtils` offers direct control over signing and storage. ```typescript 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(); ``` ```typescript import { PermitUtils, setPermit, setActivePermitHash, } from '@cofhe/sdk/permits'; 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); ``` -------------------------------- ### Solidity Example with Bindings Source: https://cofhe-docs.fhenix.zone/fhe-library/reference/fhe-sol Demonstrates using encrypted input types and performing operations like addition, multiplication, and comparison using dot notation. Shows how to grant access for future use and allow public decryption. ```solidity // Use secure encrypted input InEuint8 encryptedInputA; // Provided by client-side encryption InEuint8 encryptedInputB; // Provided by client-side encryption euint8 a = FHE.asEuint8(encryptedInputA); euint8 b = FHE.asEuint8(encryptedInputB); // Perform operations using dot notation euint8 sum = a.add(b); // Encrypted addition euint8 product = a.mul(b); // Encrypted multiplication ebool isGreater = b.gt(a); // Encrypted comparison // Conditional logic euint8 result = isGreater.select(sum, product); // Grant access for future use and allow public decryption result.allowThis(); result.allowPublic(); ``` -------------------------------- ### Configure Testnet Environment Variables Source: https://cofhe-docs.fhenix.zone/fhe-library/introduction/quick-start Set up your private key and RPC URLs in a `.env` file for testnet deployment. Ensure this file is added to your `.gitignore` to prevent committing sensitive information. ```bash PRIVATE_KEY=your_private_key_here SEPOLIA_RPC_URL=your_sepolia_rpc_url ARBITRUM_SEPOLIA_RPC_URL=your_arbitrum_sepolia_rpc_url ``` -------------------------------- ### Allowance for Decryptions Example Source: https://cofhe-docs.fhenix.zone/tutorials/acl-usage-examples Example showing how to allow specific users to decrypt their encrypted values off-chain. ```APIDOC ## Allowance for Decryptions To decrypt a ciphertext off-chain via the decryption network, the issuer must be allowed on the ciphertext handle via `FHE.allow(userAddress)`. ```solidity theme={null} contract A { private mapping(address => euint32) balances; function transfer(InEuint32 _amount, address to) { euint32 amount = FHE.asEuint32(_amount); balances[msg.sender] = FHE.sub(balances[msg.sender], amount); balances[to] = FHE.add(balances[to], amount); FHE.allow(balances[msg.sender], msg.sender); // now the sender can decrypt her balance FHE.allow(balances[to], to); // now the receiver can decrypt his balance // enable balance manipulation for future transactions FHE.allowThis(balances[msg.sender]); FHE.allowThis(balances[to]); } } ``` ``` -------------------------------- ### Create instructions.md for Fhenix Project Source: https://cofhe-docs.fhenix.zone/get-started/build-with-ai/build-with-ai Use this prompt to generate a comprehensive instructions.md file for your Fhenix project, detailing its structure, FHE patterns, and coding standards. ```markdown Create a detailed instructions.md file for my Fhenix project with the following sections: 1. Overview: Summarize the project goals, problem statements, and core FHE functionality 2. Tech Stack: List all technologies, libraries, frameworks with versions (including Fhenix SDK version) 3. Project Structure: Document the file organization with explanations 4. FHE Patterns: Document encryption/decryption patterns and FHE operations used 5. Coding Standards: Document style conventions, linting rules, and patterns 6. User Stories: Key functionality from the user perspective 7. APIs and Integrations: External services and how they connect ``` -------------------------------- ### Client Lifecycle and Usage Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/overview Demonstrates the client lifecycle: configuring, creating the client, connecting to a public and wallet client, encrypting inputs, and decrypting for UI display. Ensure you have the necessary publicClient and walletClient instances. ```typescript 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(); ``` -------------------------------- ### Creating and Connecting CofheClient Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/cofhe-client Demonstrates how to create a CofheClient instance and connect it to a specific private key to act as a user's account. After connecting, all subsequent operations like creating encrypted inputs or permits will be signed by the connected account. ```APIDOC ## Creating and connecting Spin up a client from inside [`CofheTest`](/client-sdk/foundry-plugin/cofhe-test) with `createCofheClient()`, then bind it to an address with `connect(pkey)`: ```solidity theme={null} CofheClient bob = createCofheClient(); bob.connect(0xB0B); // bob.account() == vm.addr(0xB0B) ``` After `connect`, the client knows which address to sign as. All `createInEuintN` and `permit_*` calls use that account automatically — there's no `account` argument to pass. To act on-chain as that user, prank with `client.account()`: ```solidity theme={null} vm.prank(bob.account()); counter.reset(bob.createInEuint32(2000)); ``` ``` -------------------------------- ### Install Cofhe-Errors Package Source: https://cofhe-docs.fhenix.zone/fhe-library/reference/cofhe-errors Install the package using npm, yarn, or pnpm if you need to import the error database programmatically in your code. ```bash npm install @fhenixprotocol/cofhe-errors ``` ```bash yarn add @fhenixprotocol/cofhe-errors ``` ```bash pnpm add @fhenixprotocol/cofhe-errors ``` -------------------------------- ### Persistent Allowance for This Contract Example Source: https://cofhe-docs.fhenix.zone/tutorials/acl-usage-examples Example demonstrating how to grant persistent allowance for the current contract to use encrypted values in future transactions. ```APIDOC ## Persistent Allowance for This Contract To use the results in other transactions, explicit ownership must be granted with `FHE.allow(address)` or `FHE.allowThis()`. ```solidity theme={null} contract A { private euint32 result; private euint32 handle1; function doAdd(InEuint32 input1, InEuint32 input2) { handle1 = FHE.asEuint32(input1); // Contract A gets temporary ownership of handle1 euint32 handle2 = FHE.asEuint32(input2); // Contract A gets temporary ownership of handle2 result = FHE.add(handle1, handle2); // Contract A gets temporary ownership of result FHE.allowThis(result); // result is allowed for future transactions } function doSomethingWithResult() { FHE.allowPublic(result); // Allowed — marks result as publicly decryptable FHE.add(handle1, result); // ACLNotAllowed (handle1 is not owned persistently) } } ``` ``` -------------------------------- ### Create and Connect CofheClient Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/cofhe-client Instantiate a CofheClient and connect it to a specific private key to establish the signing account. After connecting, all subsequent calls to create encrypted inputs or permits will automatically use this account. ```solidity CofheClient bob = createCofheClient(); bob.connect(0xB0B); // bob.account() == vm.addr(0xB0B) ``` -------------------------------- ### Create and Connect CofheClient Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/testing Instantiate a CofheClient and connect it to a deterministic plaintext private key for testing. Avoid reusing real keys as they appear in test output. ```solidity CofheClient bob = createCofheClient(); bob.connect(0xB0B); // bob.account() == vm.addr(0xB0B) ``` -------------------------------- ### Configure remappings.txt Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start/foundry Set up path remappings for imported contracts. The `hardhat/=node_modules/forge-std/src/` alias is crucial for resolving `hardhat/console.sol`. ```text forge-std/=node_modules/forge-std/src/ hardhat/=node_modules/forge-std/src/ @openzeppelin/contracts/=node_modules/@openzeppelin/contracts/ @fhenixprotocol/cofhe-contracts/=node_modules/@fhenixprotocol/cofhe-contracts/ @cofhe/mock-contracts/=node_modules/@cofhe/mock-contracts/ @cofhe/foundry-plugin/=node_modules/@cofhe/foundry-plugin/ ``` -------------------------------- ### Create and Connect CofheClient Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/cofhe-test Create a CofheClient instance for a specific scenario address and connect it with a private key. Using a deterministic private key aids in debugging test outputs. ```solidity CofheClient bob = createCofheClient(); bob.connect(0xB0B); ``` -------------------------------- ### Initialize @cofhe/sdk with Ethers v6 Adapter Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/migrating-from-cofhejs Shows how to initialize @cofhe/sdk using an adapter for Ethers v6, converting Ethers providers and signers to Viem clients. ```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); ``` -------------------------------- ### Create and Connect Client (Browser) Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start/javascript Configure and create a Cofhe client for browser applications, including viem clients for public and wallet interactions. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { chains } from '@cofhe/sdk/chains'; import { createPublicClient, createWalletClient, http, custom } from 'viem'; import { sepolia } from 'viem/chains'; // 1. Configure const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); // 2. Create viem clients (browser wallet) const publicClient = createPublicClient({ chain: sepolia, transport: http(), }); const walletClient = createWalletClient({ chain: sepolia, transport: custom(window.ethereum), }); // 3. Connect await client.connect(publicClient, walletClient); ``` -------------------------------- ### Get Encrypted Counter Value Source: https://cofhe-docs.fhenix.zone/tutorials/your-first-fhe-contract Returns the current encrypted value of the counter. This value can be used for private decryption off-chain. ```solidity function get_encrypted_counter_value() external view returns(euint64) { return counter; } ``` -------------------------------- ### Indicator Value Example Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/core-features Demonstrates how an indicator value is represented. Indicators range from 0 to 9999, corresponding to values from 0.0000 to 0.9999. ```solidity uint16 indicator = 7984; // Represents 0.7984 ``` -------------------------------- ### Create and Get Permits with @cofhe/sdk (After) Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/migrating-from-cofhejs Shows the new explicit way to create permits using `client.permits.createSelf` or the convenience method `client.permits.getOrCreateSelfPermit`. The active permit is automatically used by decrypt methods. ```typescript // Create a self permit (prompts for wallet signature) const permit = await client.permits.createSelf({ issuer: account, name: 'My dApp permit', }); // Or use the convenience method that creates one only if needed const permit2 = await client.permits.getOrCreateSelfPermit(); // Use with decryptForView (active permit is used automatically) const value = await client .decryptForView(ctHash, FheTypes.Uint32) .execute(); ``` -------------------------------- ### Format Booleans and Addresses for Display Source: https://cofhe-docs.fhenix.zone/client-sdk/guides/decrypt-to-view Provides examples for creating user-friendly string representations of boolean and address values obtained after decryption. ```typescript const statusLabel = decryptedIsAllowed ? 'Allowed' : 'Not allowed'; const shortOwner = `${decryptedOwner.slice(0, 6)}…${decryptedOwner.slice(-4)}`; ``` -------------------------------- ### Automatic Transaction-Scoped Allowance Source: https://cofhe-docs.fhenix.zone/tutorials/acl-usage-examples The contract creating a value automatically gets ownership for the transaction's duration. This is handled by `ACL.allowTransient(this)` internally. ```solidity contract A { function doAdd(InEuint32 input1, InEuint32 input2) { euint32 handle1 = FHE.asEuint32(input1); // Contract A gets temporary ownership of handle1 euint32 handle2 = FHE.asEuint32(input2); // Contract A gets temporary ownership of handle2 euint32 result = FHE.add(handle1, handle2); // possible because Contract A has ownership of handle1 and handle2 } } ``` -------------------------------- ### Get Decrypted Result - Solidity Source: https://cofhe-docs.fhenix.zone/fhe-library/reference/fhe-sol/decryption Retrieves a previously published decryption result. This function will revert if the result is not yet available on-chain. ```solidity uint256 result = FHE.getDecryptResult(ctHash); ``` -------------------------------- ### Get FH-ERC20 User Claims Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Retrieves all pending (unclaimed) claims for a given user address. Useful for tracking outstanding claims. ```solidity function getUserClaims(address user) public view returns (Claim[] memory); ``` ```typescript // Get all pending claims const claims = await wrapper.getUserClaims(myAddress); console.log(`You have ${claims.length} pending claims`); for (const claim of claims) { console.log(`Claim ${claim.ctHash} - requested: ${claim.requestedAmount}`); } ``` -------------------------------- ### Get FH-ERC20 Claim Information Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Retrieves detailed information about a specific claim using its ciphertext hash. Requires the `ctHash` of the claim. ```solidity function getClaim(bytes32 ctHash) public view returns (Claim memory); ``` ```typescript // Get claim info const claim = await wrapper.getClaim(ctHash); console.log(`To: ${claim.to}`); console.log(`Requested: ${claim.requestedAmount}`); console.log(`Decrypted: ${claim.decryptedAmount}`); console.log(`Claimed: ${claim.claimed}`); ``` -------------------------------- ### Clone Fhenix Hardhat Starter Repository Source: https://cofhe-docs.fhenix.zone/fhe-library/introduction/quick-start Clone the official Fhenix Hardhat starter repository to begin your FHE smart contract development. Navigate into the cloned directory afterwards. ```bash git clone https://github.com/fhenixprotocol/cofhe-hardhat-starter.git cd cofhe-hardhat-starter ``` -------------------------------- ### Get Conversion Rate - Solidity Source: https://cofhe-docs.fhenix.zone/fhe-library/confidential-contracts/fherc20/fherc20-wrapper Retrieves the conversion rate between underlying and confidential token precision. This is used to normalize token decimals. ```solidity function rate() external view returns (uint256); ``` -------------------------------- ### FHE Bindings: Utility and Access Control Source: https://cofhe-docs.fhenix.zone/fhe-library/reference/fhe-sol Demonstrates utility functions for checking initialization and unwrapping encrypted values, as well as managing access control permissions using FHE bindings. ```solidity // Utility bool initialized = a.isInitialized(); // Check if initialized bytes32 handle = a.unwrap(); // Get raw handle // Access control a.allow(address); a.allowThis(); // Allow this contract a.allowPublic(); // Allow public access a.allowSender(); // Allow sender a.allowTransient(address); // Allow transient access bool hasAccess = a.isAllowed(address); // Check access ``` -------------------------------- ### Decode CoFHE Errors with cofhe-errors CLI Source: https://cofhe-docs.fhenix.zone/fhe-library/core-concepts/common-errors Use the @fhenixprotocol/cofhe-errors package to decode cryptic execution reverted errors. Ensure you have the package installed. ```bash npx cofhe-errors 0x118cdaa7 ``` -------------------------------- ### createCofheClient() Source: https://cofhe-docs.fhenix.zone/client-sdk/foundry-plugin/cofhe-test Returns a fresh `CofheClient` instance. It is recommended to follow this call with `connect(pkey)` to establish a connection with a private key for debugging purposes. ```APIDOC ## `createCofheClient()` Returns a fresh [`CofheClient`](/client-sdk/foundry-plugin/cofhe-client). You typically follow it with `connect(pkey)`: ```solidity theme={null} CofheClient bob = createCofheClient(); bob.connect(0xB0B); ``` One client per scenario address. Connecting with a deterministic plaintext private key keeps test output debuggable. ``` -------------------------------- ### Unauthorized FHE Operation Reverts Source: https://cofhe-docs.fhenix.zone/fhe-library/core-concepts/access-control Shows an example of an FHE operation that will revert with an ACLNotAllowed error because the caller lacks permission for the ciphertext handle. ```solidity FHE.add(notAllowedCt, allowedCt); // -> will revert with ACLNotAllowed ``` -------------------------------- ### Requesting Decryption for View Source: https://cofhe-docs.fhenix.zone/deep-dive/data-flows/off-chain-decryption-flow Call decryptForView with the CtHash and a permit to get the decrypted value for UI display. This method does not require an on-chain transaction. ```typescript const result = await client .decryptForView(ctHash) .withPermit() .execute(); console.log(`Balance: ${result.decryptedValue}`); ``` -------------------------------- ### Create CofheClient with Manual Configuration Source: https://cofhe-docs.fhenix.zone/client-sdk/hardhat-plugin/client Instantiate a CofheClient using a pre-defined configuration object. ```typescript const cofheClient = hre.cofhe.createClient(config); ``` -------------------------------- ### Get or Create Self Permit Source: https://cofhe-docs.fhenix.zone/client-sdk/introduction/mental-model Obtains or creates a permit for authorizing decryption operations. This is necessary for retrieving encrypted data for UI display. ```typescript client.permits.getOrCreateSelfPermit() ``` -------------------------------- ### Builder API: .onStep(callback) Source: https://cofhe-docs.fhenix.zone/client-sdk/guides/encrypting-inputs Registers a callback function that is invoked at the start and end of each encryption step. This is useful for implementing progress indicators. ```APIDOC ## .onStep(callback) ### Description Register a callback that fires at the start and end of each encryption step. Useful for building progress indicators. ### Method Signature ```typescript onStep(callback: (step: EncryptStep, ctx?: { isStart?: boolean; isEnd?: boolean; duration?: number }) => void): EncryptionPipeline ``` ### Parameters - `callback` ((step: EncryptStep, ctx?: { isStart?: boolean; isEnd?: boolean; duration?: number }) => void): A function that receives the current encryption step and context information (like start/end status and duration). ### Returns The `EncryptionPipeline` object for chaining further methods. ### Example ```typescript import { EncryptStep } from '@cofhe/sdk'; const encrypted = await cofheClient .encryptInputs([Encryptable.uint64(10n)]) .onStep((step, ctx) => { if (ctx?.isStart) console.log(`Starting: ${step}`); if (ctx?.isEnd) console.log(`Done: ${step} (${ctx.duration}ms)`); }) .execute(); ``` ``` -------------------------------- ### Check cofhe-contracts Version with pnpm Source: https://cofhe-docs.fhenix.zone/fhe-library/core-concepts/common-errors Verify the installed version of the cofhe-contracts package using pnpm. This helps in diagnosing 'Missing revert data' errors. ```bash pnpm list @fhenixprotocol/cofhe-contracts ``` -------------------------------- ### Full Example of FHE Bindings Operations Source: https://cofhe-docs.fhenix.zone/fhe-library/reference/fhe-sol/bindings Demonstrates a comprehensive set of operations using FHE.sol bindings, including arithmetic, bitwise, comparison, type conversion, utility, and access control methods on encrypted types. ```solidity InEuint8 encryptedInputA; InEuint8 encryptedInputB; euint8 a = FHE.asEuint8(encryptedInputA); euint8 b = FHE.asEuint8(encryptedInputB); // Arithmetic euint8 sum = a.add(b); euint8 diff = a.sub(b); euint8 product = a.mul(b); euint8 quotient = a.div(b); euint8 remainder = a.rem(b); euint8 squared = a.square(); // Bitwise euint8 bitwiseAnd = a.and(b); euint8 bitwiseOr = a.or(b); euint8 bitwiseXor = a.xor(b); euint8 bitwiseNot = a.not(); euint8 shiftLeft = a.shl(b); euint8 shiftRight = a.shr(b); euint8 rotateLeft = a.rol(b); euint8 rotateRight = a.ror(b); // Comparison ebool isEqual = a.eq(b); ebool isNotEqual = a.ne(b); ebool isLessThan = a.lt(b); ebool isLessEqual = a.lte(b); ebool isGreaterThan = a.gt(b); ebool isGreaterEqual = a.gte(b); // Min/Max euint8 minimum = a.min(b); euint8 maximum = a.max(b); // Type conversion ebool converted = a.toBool(); euint16 toU16 = a.toU16(); euint32 toU32 = a.toU32(); euint64 toU64 = a.toU64(); euint128 toU128 = a.toU128(); // Utility bool initialized = a.isInitialized(); bytes32 handle = a.unwrap(); // Access control a.allow(address); a.allowThis(); a.allowPublic(); a.allowSender(); a.allowTransient(address); bool hasAccess = a.isAllowed(address); ``` -------------------------------- ### Check cofhe-contracts Version with yarn Source: https://cofhe-docs.fhenix.zone/fhe-library/core-concepts/common-errors Verify the installed version of the cofhe-contracts package using yarn. This helps in diagnosing 'Missing revert data' errors. ```bash yarn list --pattern "@fhenixprotocol/cofhe-contracts" ``` -------------------------------- ### Create and Connect FHE Client (Web) Source: https://cofhe-docs.fhenix.zone/client-sdk/quick-start Configure and connect the FHE client for browser applications using Viem. Ensure your wallet is connected to the desired network. ```typescript import { createCofheConfig, createCofheClient } from '@cofhe/sdk/web'; import { chains } from '@cofhe/sdk/chains'; import { createPublicClient, createWalletClient, http, custom } from 'viem'; import { sepolia } from 'viem/chains'; // 1. Configure const config = createCofheConfig({ supportedChains: [chains.sepolia], }); const client = createCofheClient(config); // 2. Create viem clients (browser wallet) const publicClient = createPublicClient({ chain: sepolia, transport: http(), }); const walletClient = createWalletClient({ chain: sepolia, transport: custom(window.ethereum), }); // 3. Connect await client.connect(publicClient, walletClient); ```