bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 61쪽
---------------------------------------- |
| **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 the off-chain decryption and re-submission. This decentralizes the process and removes the dependency on a general-purpose Oracle.
**Example Scenario: Checking a Player's Encrypted Score**
Consider a **Game contract** where Alice's final score is stored encrypted on-chain. Alice needs to prove her clear score to claim a reward.
| Step | Component | Action |
| ------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **1.** | **Game Contract (Solidity)** | An on-chain function is called to make Alice's encrypted score **publicly decryptable**. |
| **2.** | **Alice (Client/Off-chain)** | Alice fetches the publicly decryptable encrypted score from the Game contract. |
| **3.** | **Alice (Client/Off-chain)** | Alice or any third-party service uses the **`@zama-fhe/relayer-sdk`** to call the off-chain `publicDecrypt` function. This returns the clear score value and a **proof of decryption**. |
| **4.** | **Alice (Client/On-chain)** | Alice calls a function on the **Game contract** with the decrypted clear score and the proof. |
| **5.** | **Game Contract (Solidity)** | The contract calls `FHE.verifySignatures()` to **verify the score's validity** using the provided proof. |
| **6.** | **Game Contract (Solidity)** | If the score is valid, the contract executes the game logic (e.g., distributing Alice's prize). |
> **Key takeaway for FHEVM v0.9:** Decryption is a **user-driven, off-chain process**. The dApp client is responsible for off-chain decryption, fetching the proof, and relaying the result back on-chain for verification.
**Why this matters:** If your dApp previously relied on the Oracle, you must rewrite your decryption flow. The migration steps below guide you through this change.
## Migration Checklist
Here is a brief, ordered list of the steps required to successfully migrate your project to FHEVM v0.9:
1. **Update Dependencies:** Upgrade all key Zama FHE packages to their **FHEVM v0.9 versions**.
2. **Update Solidity Config:** Replace the removed `SepoliaConfig` with the unified **`ZamaEthereumConfig`**.
3. **Update Solidity Code:** Remove all calls to the discontinued Oracle-based FHE library functions.
4. **Re-compile & Re-deploy:** Due to new FHEVM addresses, all affected contracts must be re-compiled and re-deployed on Sepolia.
5. **Rewrite Public Decryption Logic:** Eliminate reliance on the discontinued Zama Oracle and implement the **self-relaying** workflow using the `@zama-fhe/relayer-sdk` and `FHE.verifySignatures()`.
Follow these steps for a smooth transition to FHEVM v0.9:
### Step 1: Update Core Dependencies
Ensure your project uses the latest versions of the FHEVM development tools.
| Dependency | Minimum Required Version | Notes |
| ----------------------- | ------------------------ | --------------------------------------------------------------------- |
| `@fhevm/solidity` | `v0.9.1` | Contains the updated FHE library contracts. |
| `@zama-fhe/relayer-sdk` | `v0.3.0-5` | **Crucial for v0.9:** Enables the new self-relaying decryption model. |
| `@fhevm/hardhat-plugin` | `v0.3.0-1` | Latest tooling support for development and deployment. |
### Step 2: Update Network Configuration in Solidity
The Solidity contracts now use a unified configuration contract defined in `@fhevm/solidity/config/ZamaConfig.sol`.
* **⚠️ Removal:** The `SepoliaConfig` contract is now **removed**.
* **✅ New Standard:** Update your imports and usages to use the new standard **`ZamaEthereumConfig`** contract. This change simplifies future cross-chain compatibility.
The new `ZamaEthereumConfig` abstract contract now dynamically resolves the FHEVM host addresses according to the `block.chainid`.
Replace:
```solidity
import { SepoliaConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
```
With:
```solidity
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
```
You can read more about [Configuration on the dedicated page](/protocol/solidity-guides/v0.11/smart-contract/configure).
### Step 3: Update Solidity Code
The Zama public decryption Oracle is discontinued. The following functions are no more available in the FHE Solidity library:
* `FHE.loadRequestedHandles`
* `FHE.requestDecryptionWithoutSavingHandles`
* `FHE.requestDecryption`
### Step 4: Re-compile and Re-deploy Smart Contracts
Due to fundamental changes in the FHEVM implementation and underlying infrastructure:
* **New FHEVM Addresses:** The contract addresses for core FHE components have changed.
* **Action:** You **must** re-compile your entire Solidity codebase and re-deploy all affected contracts to the **Sepolia** network.
### Step 5: Adjust Public Decryption Logic (Crucial Architectural Change)
The most significant change is the discontinuation of the Zama Oracle. This requires substantial adjustments to how your dApp handles decryption on-chain.
| Aspect | FHEVM v0.8 (Old Logic) | FHEVM v0.9 (New Logic) |
| ---------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| **Decryption Handler** | **Zama Oracle** actively listens for requests and submits the result. | **dApp Client/User** performs the off-chain decryption (self-relaying). |
| **Solidity Function** | Used `FHE.requestDecryption()`. | You will now create custom functions that accept the decrypted value and the proof. |
| **Client-Side Tool** | N/A | **Use `@zama-fhe/relayer-sdk`** to perform the `publicDecrypt` and obtain the proof. |
> **Action:** Thoroughly review your Solidity code, dApp logic, and backend services. Any code relying on the external Oracle must be rewritten to implement the self-relaying workflow using the `@zama-fhe/relayer-sdk`.
## FHEVM v0.9 Code Examples: Public Decryption Logic
The following code examples illustrate the **new public decryption logic** introduced in v0.9. This new workflow uses the combination of:
* **On-chain public decyption permission** via `FHE.makePubliclyDecryptable`
* **Off-chain decryption** via `publicDecrypt` using the `@zama-fhe/relayer-sdk` or the FHEVM Hardhat Plugin
* **On-chain signature verification** via `FHE.checkSignatures`
#### Code Examples
* [HeadsOrTails](https://github.com/zama-ai/fhevm/blob/release/0.11.x/docs/examples/heads-or-tails.md): Demonstrates the complete public decryption workflow where a cipher text is first marked as decryptable on-chain via `FHE.makePubliclyDecryptable`, and its cleartext value is subsequently verified on-chain using `FHE.checkSignatures` after being fetched off-chain via `publicDecrypt`.
* [HighestDieRoll](https://github.com/zama-ai/fhevm/blob/release/0.11.x/docs/examples/highest-die-roll.md): Extends the public decryption workflow to a multi-input scenario, demonstrating how the on-chain `FHE.checkSignatures` function ensures the authenticity of multiple cleartext values derived from multiple encrypted on-chain cypher texts.
# How to Transform Your Smart Contract into a FHEVM Smart Contract?
This short guide will walk you through converting a standard Solidity contract into one that leverages Fully Homomorphic Encryption (FHE) using FHEVM. This approach lets you develop your contract logic as usual, then adapt it to support encrypted computation for privacy.
For this guide, we will focus on a voting contract example.
***
## 1. Start with a Standard Solidity Contract
Begin by writing your voting contract in Solidity as you normally would. Focus on implementing the core logic and functionality.
```solidity
// Standard Solidity voting contract example
pragma solidity ^0.8.0;
contract SimpleVoting {
mapping(address => bool) public hasVoted;
uint64 public yesVotes;
uint64 public noVotes;
uint256 public voteDeadline;
function vote(bool support) public {
require(block.timestamp <= voteDeadline, "Too late to vote");
require(!hasVoted[msg.sender], "Already voted");
hasVoted[msg.sender] = true;
if (support) {
yesVotes += 1;
} else {
noVotes += 1;
}
}
function getResults() public view returns (uint64, uint64) {
return (yesVotes, noVotes);
}
}
```
***
## 2. Identify Sensitive Data and Operations
Review your contract and determine which variables, functions, or computations require privacy. In this example, the vote counts (`yesVotes`, `noVotes`) and individual votes should be encrypted.
***
## 3. Integrate FHEVM and update your business logic accordingly.
Replace standard data types and operations with their FHEVM equivalents for the identified sensitive parts. Use encrypted types and FHEVM library functions to perform computations on encrypted data.
```solidity
pragma solidity ^0.8.0;
import "@fhevm/solidity/lib/FHE.sol";
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";
contract EncryptedSimpleVoting is ZamaEthereumConfig {
enum VotingStatus {
Open,
DecryptionInProgress,
ResultsDecrypted
}
mapping(address => bool) public hasVoted;
VotingStatus public status;
uint64 public decryptedYesVotes;
uint64 public decryptedNoVotes;
uint256 public voteDeadline;
euint64 private encryptedYesVotes;
euint64 private encryptedNoVotes;
constructor() {
encryptedYesVotes = FHE.asEuint64(0);
encryptedNoVotes = FHE.asEuint64(0);
FHE.allowThis(encryptedYesVotes);
FHE.allowThis(encryptedNoVotes);
}
function vote(externalEbool support, bytes memory inputProof) public {
require(block.timestamp <= voteDeadline, "Too late to vote");
require(!hasVoted[msg.sender], "Already voted");
hasVoted[msg.sender] = true;
ebool isSupport = FHE.fromExternal(support, inputProof);
encryptedYesVotes = FHE.select(isSupport, FHE.add(encryptedYesVotes, 1), encryptedYesVotes);
encryptedNoVotes = FHE.select(isSupport, encryptedNoVotes, FHE.add(encryptedNoVotes, 1));
FHE.allowThis(encryptedYesVotes);
FHE.allowThis(encryptedNoVotes);
}
function requestVoteDecryption() public {
require(block.timestamp > voteDeadline, "Voting is not finished");
bytes32[] memory cts = new bytes32[](2);
cts[0] = FHE.toBytes32(encryptedYesVotes);
cts[1] = FHE.toBytes32(encryptedNoVotes);
uint256 requestId = FHE.requestDecryption(cts, this.callbackDecryptVotes.selector);
status = VotingStatus.DecryptionInProgress;
}
function callbackDecryptVotes(uint256 requestId, bytes memory cleartexts, bytes memory decryptionProof) public {
FHE.checkSignatures(requestId, cleartexts, decryptionProof);
(uint64 yesVotes, uint64 noVotes) = abi.decode(cleartexts, (uint64, uint64));
decryptedYesVotes = yesVotes;
decryptedNoVotes = noVotes;
status = VotingStatus.ResultsDecrypted;
}
function getResults() public view returns (uint64, uint64) {
require(status == VotingStatus.ResultsDecrypted, "Results were not decrypted");
return (
decryptedYesVotes,
decryptedNoVotes
);
}
}
```
Adjust your contract’s code to accept and return encrypted data where necessary. This may involve changing function parameters and return types to work with ciphertexts instead of plaintext values, as shown above.
* The `vote` function now has two parameters: `support` and `inputProof`.
* The `getResults` can only be called after the decryption occurred. Otherwise, the decrypted results are not visible to anyone.
However, it is far from being the main change. As this example illustrates, working with FHEVM often requires re-architecting the original logic to support privacy.
In the updated code, the logic becomes async; results are hidden until a request (to the oracle) explicitly has to be made to decrypt publicly the vote results.
## Conclusion
As this short guide showed, integrating with FHEVM not only requires integration with the FHEVM stack, it also requires refactoring your business logic to support mechanism to swift between encrypted and non-encrypted components of the logic.
# Overview
**Welcome to Solidity Guides!**
This section will guide you through writing confidential smart contracts in Solidity using the FHEVM library. With Fully Homomorphic Encryption(FHE), your contracts can operate directly on encrypted data without ever decrypting it onchain.
## Where to go next
If you’re new to the Zama Protocol, start with the [Litepaper](https://docs.zama.ai/protocol/zama-protocol-litepaper) or the [Protocol Overview](https://docs.zama.ai/protocol) to understand the foundations.
Otherwise:
🟨 Go to [**What is FHEVM**](/protocol/solidity-guides/v0.12/getting-started/overview) to learn about the core concepts and features.
🟨 Go to [**Quick Start Tutorial**](/protocol/solidity-guides/v0.12/getting-started/quick-start-tutorial) to build and test your first confidential smart contract.
🟨 Go to [**Smart Contract Guides**](/protocol/solidity-guides/v0.12/smart-contract/configure) for details on encrypted types, supported operations, inputs, ACL, and decryption flows.
🟨 Go to [**Development Guides**](/protocol/solidity-guides/v0.12/development-guide/hardhat) to set up your local environment with Hardhat or Foundry and deploy FHEVM contracts.
🟨 Go to [**Migration Guide**](/protocol/solidity-guides/v0.12/development-guide/migration) if you're upgrading from a previous version to v0.7.
## Help center
Ask technical questions and discuss with the community.
* [Community forum](https://community.zama.ai/c/fhevm/15)
* [Discord channel](https://discord.com/invite/zama)
# What is FHEVM Solidity
This document provides an overview of key features of the FHEVM smart contract library.
### Configuration and initialization
Smart contracts using FHEVM require proper configuration and initialization:
* **Environment setup**: Import and inherit from environment-specific configuration contracts
* **Relayer configuration**: Configure secure relayer access for cryptographic operations
* **Initialization checks**: Validate encrypted variables are properly initialized before use
For more information see [Configuration](/protocol/solidity-guides/v0.12/smart-contract/configure).
### Encrypted data types
FHEVM introduces encrypted data types compatible with Solidity:
* **Booleans**: `ebool`
* **Unsigned Integers**: `euint8`, `euint16`, `euint32`, `euint64`, `euint128`, `euint256`
* **Addresses**: `eaddress`
* **Input**: `externalEbool`, `externalEaddress`, `externalEuintXX` for handling encrypted input data
Encrypted data is represented as ciphertext handles, ensuring secure computation and interaction.
For more information see [use of encrypted types](/protocol/solidity-guides/v0.12/smart-contract/types).
### Casting types
fhevm provides functions to cast between encrypted types:
* **Casting between encrypted types**: `FHE.asEbool` converts encrypted integers to encrypted booleans
* **Casting to encrypted types**: `FHE.asEuintX` converts plaintext values to encrypted types
* **Casting to encrypted addresses**: `FHE.asEaddress` converts plaintext addresses to encrypted addresses
For more information see [use of encrypted types](/protocol/solidity-guides/v0.12/smart-contract/types).
### Confidential computation
fhevm enables symbolic execution of encrypted operations, supporting:
* **Arithmetic:** `FHE.add`, `FHE.sub`, `FHE.mul`, `FHE.min`, `FHE.max`, `FHE.neg`, `FHE.div`, `FHE.rem`
* Note: `div` and `rem` operations are supported only with plaintext divisors
* **Bitwise:** `FHE.and`, `FHE.or`, `FHE.xor`, `FHE.not`, `FHE.shl`, `FHE.shr`, `FHE.rotl`, `FHE.rotr`
* **Comparison:** `FHE.eq`, `FHE.ne`, `FHE.lt`, `FHE.le`, `FHE.gt`, `FHE.ge`
* **Advanced:** `FHE.select` for branching on encrypted conditions, `FHE.randEuintX` for on-chain randomness.
For more information on operations, see [Operations on encrypted types](/protocol/solidity-guides/v0.12/smart-contract/operations).
For more information on conditional branching, see [Conditional logic in FHE](/protocol/solidity-guides/v0.12/smart-contract/logics/conditions).
For more information on random number generation, see [Generate Random Encrypted Numbers](/protocol/solidity-guides/v0.12/smart-contract/operations/random).
### Access control mechanism
fhevm enforces access control with a blockchain-based Access Control List (ACL):
* **Persistent access**: `FHE.allow`, `FHE.allowThis` grants permanent permissions for ciphertexts.
* **Transient access**: `FHE.allowTransient` provides temporary access for specific transactions.
* **Validation**: `FHE.isSenderAllowed` ensures that only authorized entities can interact with ciphertexts.
* **Persistent public decryption**: `FHE.makePubliclyDecryptable`, `FHE.isPubliclyDecryptable` makes a given ciphertext permanently publicly decryptable.
For more information see [ACL](/protocol/solidity-guides/v0.12/smart-contract/acl).
# Set up Hardhat
In this section, you’ll learn how to set up a FHEVM Hardhat development environment using the **FHEVM Hardhat template** as a starting point for building and testing fully homomorphic encrypted smart contracts.
## Create a local Hardhat Project
{% stepper %}
{% step %}
#### Install a Node.js TLS version
Ensure that Node.js is installed on your machine.
* Download and install the recommended LTS (Long-Term Support) version from the [official website](https://nodejs.org/en).
* Use an **even-numbered** version (e.g., `v18.x`, `v20.x`)
{% hint style="warning" %}
**Hardhat** does not support odd-numbered Node.js versions. If you’re using one (e.g., v21.x, v23.x), Hardhat will display a persistent warning message and may behave unexpectedly.
{% endhint %}
To verify your installation:
```sh
node -v
npm -v
```
{% endstep %}
{% step %}
#### Create a new GitHub repository from the FHEVM Hardhat template.
1. On GitHub, navigate to the main page of the [FHEVM Hardhat template](https://github.com/zama-ai/fhevm-hardhat-template) repository.
2. Above the file list, click the green **Use this template** button.
3. Follow the instructions to create a new repository from the FHEVM Hardhat template.
{% hint style="info" %}
See Github doc: [Creating a repository from a template](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template#creating-a-repository-from-a-template)
{% endhint %}
{% endstep %}
{% step %}
#### Clone your newly created GitHub repository locally
Now that your GitHub repository has been created, you can clone it to your local machine:
```sh
cd <your-preferred-location>
git clone <url-to-your-new-repo>
# Navigate to the root of your new FHEVM Hardhat project
cd <your-new-repo-name>
```
Next, let’s install your local Hardhat development environment.
{% endstep %}
{% step %}
#### Install your FHEVM Hardhat project dependencies
From the project root directory, run:
```sh
npm install
```
This will install all required dependencies defined in your `package.json`, setting up your local FHEVM Hardhat development environment.
{% endstep %}
{% step %}
#### Set up the H프로젝트로 돌아가기