#### Summary
| Mode | Encryption | Persistent | Chain | Speed | Usage |
| ----------------- | ------------------ | ---------- | --------- | ------------ | ------------------------------------------------- |
| Hardhat (default) | 🧪 Mock | ❌ No | In-Memory | ⚡⚡ Very Fast | Fast local testing and coverage |
| Hardhat Node | 🧪 Mock | ✅ Yes | Server | ⚡ Fast | Frontend integration and local persistent testing |
| Sepolia Testnet | 🔐 Real Encryption | ✅ Yes | Server | 🐢 Slow | Full-stack validation with real encrypted data |
### The FHEVM Hardhat Template
To demonstrate the three available testing modes, we'll use the [fhevm-hardhat-template](https://github.com/zama-ai/fhevm-hardhat-template), which comes with the FHEVM Hardhat Plugin pre-installed, a basic `FHECounter` smart contract, and ready-to-use tasks for interacting with a deployed instance of this contract.
### Run on Hardhat (default)
To run your tests in-memory using FHEVM mock values, simply run the following:
```sh
npx hardhat test --network hardhat
```
### Run on Hardhat Node
You can also run your tests against a local Hardhat node, allowing you to deploy contract instances and interact with them in a persistent environment.
{% stepper %}
{% step %}
**Launch the Hardhat Node server:**
* Open a new terminal window.
* From the root project directory, run the following:
```sh
npx hardhat node
```
{% endstep %}
{% step %}
**Run your test suite (optional):**
From the root project directory:
```sh
npx hardhat test --network localhost
```
{% endstep %}
{% step %}
**Deploy the `FHECounter` smart contract on Hardhat Node**
From the root project directory:
```sh
npx hardhat deploy --network localhost
```
Check the deployed contract FHEVM configuration:
```sh
npx hardhat fhevm check-fhevm-compatibility --network localhost --address <deployed contract address>
```
{% endstep %}
{% step %}
**Interact with the deployed `FHECounter` smart contract**
From the root project directory:
1. Decrypt the current counter value:
```sh
npx hardhat --network localhost task:decrypt-count
```
2. Increment the counter by 1:
```sh
npx hardhat --network localhost task:increment --value 1
```
3. Decrypt the new counter value:
```sh
npx hardhat --network localhost task:decrypt-count
```
{% endstep %}
{% endstepper %}
### Run on Sepolia Ethereum Testnet
To test your FHEVM smart contract using real encrypted values, you can run your tests on the Sepolia Testnet.
{% stepper %}
{% step %}
**Rebuild the project for Sepolia**
From the root project directory:
```sh
npx hardhat clean
npx hardhat compile --network sepolia
```
{% endstep %}
{% step %}
**Deploy the `FHECounter` smart contract on Sepolia**
```sh
npx hardhat deploy --network sepolia
```
{% endstep %}
{% step %}
**Check the deployed `FHECounter` contract FHEVM configuration**
From the root project directory:
```sh
npx hardhat fhevm check-fhevm-compatibility --network sepolia --address <deployed contract address>
```
If an internal exception is raised, it likely means the contract was not properly compiled for the Sepolia network.
{% endstep %}
{% step %}
**Interact with the deployed `FHECounter` contract**
From the root project directory:
1. Decrypt the current counter value (⏳ wait...):
```sh
npx hardhat --network sepolia task:decrypt-count
```
2. Increment the counter by 1 (⏳ wait...):
```sh
npx hardhat --network sepolia task:increment --value 1
```
3. Decrypt the new counter value (⏳ wait...):
```sh
npx hardhat --network sepolia task:decrypt-count
```
{% endstep %}
{% endstepper %}
# Write FHEVM-enabled Hardhat Tasks
In this section, you'll learn how to write a custom FHEVM Hardhat task.
Writing tasks is a gas-efficient and flexible way to test your FHEVM smart contracts on the Sepolia network. Creating a custom task is straightforward.
## Prerequisite
* You should be familiar with Hardhat tasks. If you're new to them, refer to the [Hardhat Tasks official documentation](https://hardhat.org/hardhat-runner/docs/guides/tasks#writing-tasks).
* You should have already **completed** the [FHEVM Tutorial](https://docs.zama.ai/protocol/solidity-guides/getting-started/setup).
* This page provides a step-by-step walkthrough of the `task:decrypt-count` tasks included in the file [tasks/FHECounter.ts](https://github.com/zama-ai/fhevm-hardhat-template/blob/main/tasks/FHECounter.ts) file, located in the [fhevm-hardhat-template](https://github.com/zama-ai/fhevm-hardhat-template) repository.
{% stepper %}
{% step %}
## A Basic Hardhat Task.
Let’s start with a simple example: fetching the current counter value from a basic `Counter.sol` contract.
If you're already familiar with Hardhat and custom tasks, the TypeScript code below should look familiar and be easy to follow:
```ts
task("task:get-count", "Calls the getCount() function of Counter Contract")
.addOptionalParam("address", "Optionally specify the Counter contract address")
.setAction(async function (taskArguments: TaskArguments, hre) {
const { ethers, deployments } = hre;
const CounterDeployment = taskArguments.address
? { address: taskArguments.address }
: await deployments.get("Counter");
console.log(`Counter: ${CounterDeployment.address}`);
const counterContract = await ethers.getContractAt("Counter", CounterDeployment.address);
const clearCount = await counterContract.getCount();
console.log(`Clear count : ${clearCount}`);
});
```
Now, let’s modify this task to work with FHEVM encrypted values.
{% endstep %}
{% step %}
## Comment Out Existing Logic and rename
First, comment out the existing logic so we can incrementally add the necessary changes for FHEVM integration.
```ts
task("task:get-count", "Calls the getCount() function of Counter Contract")
.addOptionalParam("address", "Optionally specify the Counter contract address")
.setAction(async function (taskArguments: TaskArguments, hre) {
// const { ethers, deployments } = hre;
// const CounterDeployment = taskArguments.address
// ? { address: taskArguments.address }
// : await deployments.get("Counter");
// console.log(`Counter: ${CounterDeployment.address}`);
// const counterContract = await ethers.getContractAt("Counter", CounterDeployment.address);
// const clearCount = await counterContract.getCount();
// console.log(`Clear count : ${clearCount}`);
});
```
Next, rename the task by replacing:
```ts
task("task:get-count", "Calls the getCount() function of Counter Contract")
```
With:
```ts
task("task:decrypt-count", "Calls the getCount() function of Counter Contract")
```
This updates the task name from `task:get-count` to `task:decrypt-count`, reflecting that it now includes decryption logic for FHE-encrypted values.
{% endstep %}
{% step %}
## Initialize FHEVM CLI API
Replace the line:
```ts
// const { ethers, deployments } = hre;
```
With:
```ts
const { ethers, deployments, fhevm } = hre;
await fhevm.initializeCLIApi();
```
{% hint style="warning" %}
Calling `initializeCLIApi()` is essential. Unlike built-in Hardhat tasks like `test` or `compile`, which automatically initialize the FHEVM runtime environment, custom tasks require you to call this function explicitly. **Make sure to call it at the very beginning of your task** to ensure the environment is properly set up.
{% endhint %}
{% endstep %}
{% step %}
## Call the view function `getCount` from the FHECounter contract
Replace the following commented-out lines:
```ts
// const CounterDeployment = taskArguments.address
// ? { address: taskArguments.address }
// : await deployments.get("Counter");
// console.log(`Counter: ${CounterDeployment.address}`);
// const counterContract = await ethers.getContractAt("Counter", CounterDeployment.address);
// const clearCount = await counterContract.getCount();
```
With the FHEVM equivalent:
```ts
const FHECounterDeployment = taskArguments.address
? { address: taskArguments.address }
: await deployments.get("FHECounter");
console.log(`FHECounter: ${FHECounterDeployment.address}`);
const fheCounterContract = await ethers.getContractAt("FHECounter", FHECounterDeployment.address);
const encryptedCount = await fheCounterContract.getCount();
if (encryptedCount === ethers.ZeroHash) {
console.log(`encrypted count: ${encryptedCount}`);
console.log("clear count : 0");
return;
}
```
Here, `encryptedCount` is an FHE-encrypted `euint32` primitive. To retrieve the actual value, we need to decrypt it in the next step.
{% endstep %}
{% step %}
## Decrypt the encrypted count value.
Now replace the following commented-out line:
```ts
// console.log(`Clear count : ${clearCount}`);
```
With the decryption logic:
```ts
const signers = await ethers.getSigners();
const clearCount = await fhevm.userDecryptEuint(
FhevmType.euint32,
encryptedCount,
FHECounterDeployment.address,
signers[0],
);
console.log(`Encrypted count: ${encryptedCount}`);
console.log(`Clear count : ${clearCount}`);
```
At this point, your custom Hardhat task is fully configured to work with FHE-encrypted values and ready to run!
{% endstep %}
{% step %}
## Step 6: Run your custom task using Hardhat Node
**Start the Local Hardhat Node:**
* Open a new terminal window.
* From the root project directory, run the following:
```sh
npx hardhat node
```
**Deploy the FHECounter smart contract on the local Hardhat Node**
```sh
npx hardhat deploy --network localhost
```
**Run your custom task**
```sh
npx hardhat task:decrypt-count --network localhost
```
{% endstep %}
{% step %}
## Step 7: Run your custom task using Sepolia
**Deploy the FHECounter smart contract on Sepolia Testnet (if not already deployed)**
```sh
npx hardhat deploy --network sepolia
```
**Execute your custom task**
```sh
npx hardhat task:decrypt-count --network sepolia
```
{% endstep %}
{% endstepper %}
# Foundry
This guide explains how to use Foundry with FHEVM for developing smart contracts.
While a Foundry template is currently in development, we strongly recommend using the [Hardhat template](/protocol/solidity-guides/v0.12/getting-started/setup)) for now, as it provides a fully tested and supported development environment for FHEVM smart contracts.
However, you could still use Foundry with the mocked version of the FHEVM, but please be aware that this approach is **NOT** recommended, since the mocked version is not fully equivalent to the real FHEVM node's implementation (see warning in hardhat). In order to do this, you will need to rename your `FHE.sol` imports from `@fhevm/solidity/lib/FHE.sol` to `fhevm/mocks/FHE.sol` in your solidity source files.
# HCU
This guide explains how to use Fully Homomorphic Encryption (FHE) operations in your smart contracts on FHEVM. Understanding HCU is critical for designing efficient confidential smart contracts.
## Overview
FHE operations in FHEVM are computationally intensive compared to standard Ethereum operations, as they require complex mathematical computations to maintain privacy and security. To manage computational load and prevent potential denial-of-service attacks, FHEVM implements a metering system called **Homomorphic Complexity Units ("HCU")**.
To represent this complexity, we introduced the **Homomorphic Complexity Unit ("HCU")**. In Solidity, each FHE operation consumes a set amount of HCU based on the operational computational complexity for hardware computation. Since FHE transactions are symbolic, this helps preventing resource exhaustion outside of the blockchain.
To do so, there is a contract named `HCULimit`, which monitors HCU consumption for each transaction and enforces two key limits:
* **Sequential homomorphic operations depth limit per transaction**: Controls HCU usage for operations that must be processed in order.
* **Global homomorphic operations complexity per transaction**: Controls HCU usage for operations that can be processed in parallel.
If either limit is exceeded, the transaction will revert.
## HCU limit
The current devnet has an HCU limit of **20,000,000** per transaction and an HCU depth limit of **5,000,000** per transaction. If either HCU limit is exceeded, the transaction will revert.
To resolve this, you must do one of the following:
* Refactor your code to reduce the number of FHE operations in your transaction.
* Split your FHE operations across multiple independent transactions.
## HCU costs for common operations
### Boolean operations (`ebool`)
| Function name | HCU (scalar) | HCU (non-scalar) |
| ------------- | ------------ | ---------------- |
| `and` | 22,000 | 25,000 |
| `or` | 22,000 | 24,000 |
| `xor` | 2,000 | 22,000 |
| `not` | - | 2 |
| `select` | - | 55,000 |
| `randEbool` | - | 19,000 |
***
### Unsigned integer operations
HCU increase with the bit-width of the encrypted integer type. Below are the detailed costs for various operations on encrypted types.
#### **8-bit Encrypted integers (`euint8`)**
| Function name | HCU (scalar) | HCU (non-scalar) |
| ------------- | ------------ | ---------------- |
| `add` | 84,000 | 88,000 |
| `sub` | 84,000 | 91,000 |
| `mul` | 122,000 | 150,000 |
| `div` | 210,000 | - |
| `rem` | 440,000 | - |
| `and` | 31,000 | 31,000 |
| `or` | 30,000 | 30,000 |
| `xor` | 31,000 | 31,000 |
| `shr` | 32,000 | 91,000 |
| `shl` | 32,000 | 92,000 |
| `rotr` | 31,000 | 93,000 |
| `rotl` | 31,000 | 91,000 |
| `eq` | 55,000 | 55,000 |
| `ne` | 55,000 | 55,000 |
| `ge` | 52,000 | 63,000 |
| `gt` | 52,000 | 59,000 |
| `le` | 58,000 | 58,000 |
| `lt` | 52,000 | 59,000 |
| `min` | 84,000 | 119,000 |
| `max` | 89,000 | 121,000 |
| `neg` | - | 79,000 |
| `not` | - | 9 |
| `select` | - | 55,000 |
| `randEuint8` | - | 23,000 |
#### **16-bit Encrypted integers (`euint16`)**
| Function name | HCU (scalar) | HCU (non-scalar) |
| ------------- | ------------ | ---------------- |
| `add` | 93,000 | 93,000 |
| `sub` | 93,000 | 93,000 |
| `mul` | 193,000 | 222,000 |
| `div` | 302,000 | - |
| `rem` | 580,000 | - |
| `and` | 31,000 | 31,000 |
| `or` | 30,000 | 31,000 |
| `xor` | 31,000 | 31,000 |
| `shr` | 32,000 | 123,000 |
| `shl` | 32,000 | 125,000 |
| `rotr` | 31,000 | 125,000 |
| `rotl` | 31,000 | 125,000 |
| `eq` | 55,000 | 83,000 |
| `ne` | 55,000 | 83,000 |
| `ge` | 55,000 | 84,000 |
| `gt` | 55,000 | 84,000 |
| `le` | 58,000 | 83,000 |
| `lt` | 58,000 | 84,000 |
| `min` | 88,000 | 146,000 |
| `max` | 89,000 | 145,000 |
| `neg` | - | 93,000 |
| `not` | - | 16 |
| `select` | - | 55,000 |
| `randEuint16` | - | 23,000 |
#### **32-bit Encrypted Integers (`euint32`)**
| Function name | HCU (scalar) | HCU (non-scalar) |
| ------------- | ------------ | ---------------- |
| `add` | 95,000 | 125,000 |
| `sub` | 95,000 | 125,000 |
| `mul` | 265,000 | 328,000 |
| `div` | 438,000 | - |
| `rem` | 792,000 | - |
| `and` | 32,000 | 32,000 |
| `or` | 32,000 | 32,000 |
| `xor` | 32,000 | 32,000 |
| `shr` | 32,000 | 163,000 |
| `shl` | 32,000 | 162,000 |
| `rotr` | 32,000 | 160,000 |
| `rotl` | 32,000 | 163,000 |
| `eq` | 82,000 | 86,000 |
| `ne` | 83,000 | 85,000 |
| `ge` | 84,000 | 118,000 |
| `gt` | 84,000 | 118,000 |
| `le` | 84,000 | 117,000 |
| `lt` | 83,000 | 117,000 |
| `min` | 117,000 | 182,000 |
| `max` | 117,000 | 180,000 |
| `neg` | - | 131,000 |
| `not` | - | 32 |
| `select` | - | 55,000 |
| `randEuint32` | - | 24,000 |
#### **64-bit Encrypted integers (`euint64`)**
| Function name | HCU (scalar) | HCU (non-scalar) |
| ------------- | ------------ | ---------------- |
| `add` | 133,000 | 162,000 |
| `sub` | 133,000 | 162,000 |
| `mul` | 365,000 | 596,000 |
| `div` | 715,000 | - |
| `rem` | 1,153,000 | - |
| `and` | 34,000 | 34,000 |
| `or` | 34,000 | 34,000 |
| `xor` | 34,000 | 34,000 |
| `shr` | 34,000 | 209,000 |
| `shl` | 34,000 | 208,000 |
| `rotr` | 34,000 | 209,000 |
| `rotl` | 34,000 | 209,000 |
| `eq` | 83,000 | 120,000 |
| `ne` | 84,000 | 118,000 |
| `ge` | 116,000 | 152,000 |
| `gt` | 117,000 | 152,000 |
| `le` | 119,000 | 149,000 |
| `lt` | 118,000 | 146,000 |
| `min` | 150,000 | 219,000 |
| `max` | 149,000 | 218,000 |
| `neg` | - | 131,000 |
| `not` | - | 63 |
| `select` | - | 55,000 |
| `randEuint64` | - | 24,000 |
#### **128-bit Encrypted integers (`euint128`)**
| Function name | HCU (scalar) | HCU (non-scalar) |
| -------------- | ------------ | ---------------- |
| `add` | 172,000 | 259,000 |
| `sub` | 172,000 | 260,000 |
| `mul` | 696,000 | 1,686,000 |
| `div` | 1,225,000 | - |
| `rem` | 1,943,000 | - |
| `and` | 37,000 | 37,000 |
| `or` | 37,000 | 37,000 |
| `xor` | 37,000 | 37,000 |
| `shr` | 37,000 | 272,000 |
| `shl` | 37,000 | 272,000 |
| `rotr` | 37,000 | 283,000 |
| `rotl` | 37,000 | 278,000 |
| `eq` | 117,000 | 122,000 |
| `ne` | 117,000 | 122,000 |
| `ge` | 149,000 | 210,000 |
| `gt` | 150,000 | 218,000 |
| `le` | 150,000 | 218,000 |
| `lt` | 149,000 | 215,000 |
| `min` | 186,000 | 289,000 |
| `max` | 180,000 | 290,000 |
| `neg` | - | 168,000 |
| `not` | - | 130 |
| `select` | - | 57,000 |
| `randEuint128` | - | 25,000 |
#### **256-bit Encrypted integers (`euint256`)**
| Function name | HCU (scalar) | HCU (non-scalar) |
| -------------- | ------------ | ---------------- |
| `and` | 38,000 | 38,000 |
| `or` | 38,000 | 38,000 |
| `xor` | 39,000 | 39,000 |
| `shr` | 38,000 | 369,000 |
| `shl` | 39,000 | 378,000 |
| `rotr` | 40,000 | 375,000 |
| `rotl` | 38,000 | 378,000 |
| `eq` | 118,000 | 152,000 |
| `ne` | 117,000 | 150,000 |
| `neg` | - | 269,000 |
| `not` | - | 130 |
| `select` | - | 108,000 |
| `randEuint256` | - | 30,000 |
#### **Encrypted addresses (`euint160`)**
When using `eaddress` (internally represented as `euint160`), the HCU costs for equality and inequality checks and select are as follows:
| Function name | HCU (scalar) | HCU (non-scalar) |
| ------------- | ------------ | ---------------- |
| `eq` | 115,000 | 125,000 |
| `ne` | 115,000 | 124,000 |
| `select` | - | 83,000 |
## Additional Operations
| Function name | HCU |
| ---------------- | ------------- |
| `cast` | 32 |
| `trivialEncrypt` | 32 |
| `randBounded` | 23,000-30,000 |
# Migrate to v0.9
FHEVM v0.9 introduces major architectural changes, including:
* Removal of the Zama Oracle
* Introduction of a self-relaying public decryption workflow
* Unified `ZamaEthereumConfig` replacing `SepoliaConfig`
This guide explains what changed and how to migrate your project smoothly.
## What Changed in FHEVM v0.9?
Before diving into migration steps, it’s important to understand the main breaking change: public decryption is no longer handled by a Zama Oracle, but by your dApp’s off-chain logic.
### FHEVM v0.8 Oracle-Based Decryption
In FHEVM v0.8, the decryption process relies on a trusted **Oracle** to relay the decryption request and proof between the dApp and the Zama Key Management System (KMS). This approach abstracts the complexity but introduces an external dependency.
**Decryption Steps:**
| Step | Component | Action |
| ------ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **1.** | **dApp (Solidity)** | Calls `FHE.requestDecryption()` to signal a need for clear data. |
| **2.** | **Oracle** | Listens for the on-chain decryption request event. |
| **3.** | **Oracle (Off-chain)** | Performs the `publicDecryption` with the Zama KMS, retrieving the **clear values** and the **decryption proof**. |
| **4.** | **Oracle** | Calls the user-specified dApp **callback Solidity function** with the clear values and the associated proof. |
| **5.** | **dApp (Solidity Callback)** | Calls `FHE.verifySignatures()` to verify the authenticity of the clear values using the provided proof. |
> **Key takeaway for v0.8:** The Oracle is the trusted intermediary responsible for performing the off-chain decryption and submitting the result back to the dApp contract.
### FHEVM v0.9 Self-Relaying Decryption & dApp Responsibility
The FHEVM v0.9 architecture shifts to a **self-relaying model**, empowering the dApp client (the user) to execute th프로젝트로 돌아가기