bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 72쪽
## Call the `getCount()` function and Decrypt the value
Now that the counter has been incremented using an encrypted input, it's time to **read the updated encrypted value** from the smart contract and **decrypt it** using the `userDecryptEuint` function provided by the FHEVM Hardhat Plugin.
The `userDecryptEuint` function takes four parameters:
1. **FhevmType**: The integer type of the FHE-encrypted value. In this case, we're using `FhevmType.euint32` because the counter is a `uint32`.
2. **Encrypted handle**: A 32-byte FHEVM handle representing the encrypted value you want to decrypt.
3. **Smart contract address**: The address of the contract that has permission to access the encrypted handle.
4. **User signer**: The signer (e.g., signers.alice) who has permission to access the handle.
{% hint style="info" %}
Note: Permissions to access the FHEVM handle are set on-chain using the `FHE.allow()` Solidity function (see FHECounter.sol).
{% endhint %}
Replace :
```ts
// const countAfterInc = await counterContract.getCount();
// expect(countAfterInc).to.eq(countBeforeInc + 1n);
```
with the following:
```ts
const encryptedCountAfterInc = await fheCounterContract.getCount();
const clearCountAfterInc = await fhevm.userDecryptEuint(
FhevmType.euint32,
encryptedCountAfterInc,
fheCounterContractAddress,
signers.alice,
);
expect(clearCountAfterInc).to.eq(clearCountBeforeInc + clearOne);
```
***
#### Run the test
From your project's root directory, run:
```sh
npx hardhat test
```
#### Expected Output
```sh
FHECounter
FHECounter has been deployed at address 0x7553CB9124f974Ee475E5cE45482F90d5B6076BC
✔ should be deployed
✔ encrypted count should be uninitialized after deployment
✔ increment the counter by 1
3 passing (7ms)
```
{% endstep %}
{% step %}
## Call the contract `decrement()` function
Similarly to the previous test, we’ll now call the `decrement()` function using an encrypted input.
Replace :
```ts
// it("decrement the counter by 1", async function () {
// // First increment, count becomes 1
// let tx = await counterContract.connect(signers.alice).increment();
// await tx.wait();
// // Then decrement, count goes back to 0
// tx = await counterContract.connect(signers.alice).decrement(1);
// await tx.wait();
// const count = await counterContract.getCount();
// expect(count).to.eq(0);
// });
```
with the following:
```ts
it("decrement the counter by 1", async function () {
// Encrypt constant 1 as a euint32
const clearOne = 1;
const encryptedOne = await fhevm
.createEncryptedInput(fheCounterContractAddress, signers.alice.address)
.add32(clearOne)
.encrypt();
// First increment by 1, count becomes 1
let tx = await fheCounterContract.connect(signers.alice).increment(encryptedOne.handles[0], encryptedOne.inputProof);
await tx.wait();
// Then decrement by 1, count goes back to 0
tx = await fheCounterContract.connect(signers.alice).decrement(encryptedOne.handles[0], encryptedOne.inputProof);
await tx.wait();
const encryptedCountAfterDec = await fheCounterContract.getCount();
const clearCountAfterDec = await fhevm.userDecryptEuint(
FhevmType.euint32,
encryptedCountAfterDec,
fheCounterContractAddress,
signers.alice,
);
expect(clearCountAfterDec).to.eq(0);
});
```
***
#### Run the test
From your project's root directory, run:
```sh
npx hardhat test
```
#### Expected Output
```sh
FHECounter
FHECounter has been deployed at address 0x7553CB9124f974Ee475E5cE45482F90d5B6076BC
✔ should be deployed
✔ encrypted count should be uninitialized after deployment
✔ increment the counter by 1
✔ decrement the counter by 1
4 passing (7ms)
```
{% endstep %}
{% endstepper %}
## Congratulations! You've completed the full tutorial.
You have successfully written and tested your FHEVM-based counter smart contract. By now, your project should include the following files:
* [`contracts/FHECounter.sol`](https://docs.zama.ai/protocol/examples#tab-fhecounter.sol) — your Solidity smart contract
* [`test/FHECounter.ts`](https://docs.zama.ai/protocol/examples#tab-fhecounter.ts) — your Hardhat test suite written in TypeScript
## Next step
If you would like to deploy your project on the testnet, or learn more about using FHEVM Hardhat Plugin, head to [Deploy contracts and run tests](/protocol/solidity-guides/development-guide/hardhat/run_test).
# Configuration
This document explains how to enable encrypted computations in your smart contract by setting up the `fhevm` environment. Learn how to integrate essential libraries, configure encryption, and add secure computation logic to your contracts.
## Core configuration setup
To utilize encrypted computations in Solidity contracts, you must configure the **FHE library**. The `fhevm` package simplifies this process with prebuilt configuration contracts, allowing you to focus on developing your contract's logic without handling the underlying cryptographic setup.
This library and its associated contracts provide a standardized way to configure and interact with Zama's FHEVM (Fully Homomorphic Encryption Virtual Machine) infrastructure on different Ethereum networks. It supplies the necessary contract addresses for Zama's FHEVM components (`ACL`, `FHEVMExecutor`, `KMSVerifier`), enabling seamless integration for Solidity contracts that require FHEVM support. The `InputVerifier` is not part of the inherited config — it is resolved at runtime via `FHEVMExecutor.getInputVerifierAddress()`.
## Key components configured automatically
1. **FHE library**: Sets up encryption parameters and cryptographic keys.
2. **Network-specific settings**: Adapts to local testing, testnets (Sepolia for example), or mainnet deployment.
By inheriting these configuration contracts, you ensure seamless initialization and functionality across environments.
## ZamaConfig.sol
The `ZamaConfig` library exposes functions to retrieve FHEVM configuration structs and contract addresses for supported networks: Ethereum mainnet, Sepolia testnet, and local Hardhat environments.
Under the hood, this library encapsulates the network-specific addresses of Zama's FHEVM infrastructure into a single struct (`CoprocessorConfig`).
## ZamaEthereumConfig
The `ZamaEthereumConfig` contract is designed to be inherited by a user contract. The constructor automatically sets up the FHEVM coprocessor using the configuration provided by the library for the respective network. When a contract inherits from `ZamaEthereumConfig`, the constructor calls `FHE.setCoprocessor` with the appropriate addresses. This ensures that the inheriting contract is automatically wired to the correct FHEVM contracts for the target network, abstracting away manual address management and reducing the risk of misconfiguration.
**Example**
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
contract MyERC20 is ZamaEthereumConfig {
constructor() {
// Additional initialization logic if needed
}
}
```
## Using `isInitialized`
The `isInitialized` utility function checks whether an encrypted variable has been properly initialized, preventing unexpected behavior due to uninitialized values.
**Function signature**
```solidity
function isInitialized(T v) internal pure returns (bool)
```
**Purpose**
* Ensures encrypted variables are initialized before use.
* Prevents potential logic errors in contract execution.
**Example: Initialization Check for Encrypted Counter**
```solidity
require(FHE.isInitialized(counter), "Counter not initialized!");
```
## Summary
By leveraging prebuilt a configuration contract like `ZamaEthereumConfig` in `ZamaConfig.sol`, you can efficiently set up your smart contract for encrypted computations. These tools abstract the complexity of cryptographic initialization, allowing you to focus on building secure, confidential smart contracts.
# Contract addresses
### Ethereum mainnet
| Contract/Service | Address |
| ------------------------- | ------------------------------------------ |
| ACL\_CONTRACT | 0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6 |
| FHEVM\_EXECUTOR\_CONTRACT | 0xD82385dADa1ae3E969447f20A3164F6213100e75 |
| KMS\_VERIFIER\_CONTRACT | 0x77627828a55156b04Ac0DC0eb30467f1a552BB03 |
### Sepolia testnet
| Contract/Service | Address/Value |
| ---------------------------- | ------------------------------------------ |
| ACL\_CONTRACT | 0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D |
| FHEVM\_EXECUTOR\_CONTRACT | 0x92C920834Ec8941d2C77D188936E1f7A6f49c127 |
| KMS\_VERIFIER\_CONTRACT | 0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A |
| HCU\_LIMIT\_CONTRACT | 0xa10998783c8CF88D886Bc30307e631D6686F0A22 |
| INPUT\_VERIFIER\_CONTRACT | 0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0 |
| DECRYPTION\_ADDRESS | 0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478 |
| INPUT\_VERIFICATION\_ADDRESS | 0x483b9dE06E4E4C7D35CCf5837A1668487406D955 |
| RELAYER\_URL | `https://relayer.testnet.zama.org` |
| GATEWAY\_CHAIN\_ID | 10901 |
{% hint style="info" %}
You do not need to configure these addresses manually. Inheriting from `ZamaEthereumConfig` automatically resolves the correct addresses based on the current `block.chainid`.
{% endhint %}
# Supported types
This document introduces the encrypted integer types provided by the `FHE` library in FHEVM and explains their usage, including casting, state variable declarations, and type-specific considerations.
## Introduction
The `FHE` library offers a robust type system with encrypted integer types, enabling secure computations on confidential data in smart contracts. These encrypted types are validated both at compile time and runtime to ensure correctness and security.
### Key features of encrypted types
* Encrypted integers function similarly to Solidity’s native integer types, but they operate on **Fully Homomorphic Encryption (FHE)** ciphertexts.
* Arithmetic operations on `e(u)int` types are **unchecked**, meaning they wrap around on overflow. This design choice ensures confidentiality by avoiding the leakage of information through error detection.
* Future versions of the `FHE` library will support encrypted integers with overflow checking, but with the trade-off of exposing limited information about the operands.
{% hint style="info" %}
Encrypted integers with overflow checking will soon be available in the `FHE` library. These will allow reversible arithmetic operations but may reveal some information about the input values.
{% endhint %}
Encrypted integers in FHEVM are represented as FHE ciphertexts, abstracted using ciphertext handles. These types, prefixed with `e` (for example, `euint64`) act as secure wrappers over the ciphertext handles.
## List of encrypted types
The `FHE` library currently supports the following encrypted types:
| Type | Bit Length | Supported Operators | Aliases (with supported operators) |
| -------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Ebool | 2 | and, or, xor, eq, ne, not, select, rand | |
| Euint8 | 8 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | |
| Euint16 | 16 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | |
| Euint32 | 32 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | |
| Euint64 | 64 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | |
| Euint128 | 128 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | |
| Euint160 | 160 | eq, ne, select | Eaddress — `eaddress` is an alias for `euint160`, used for encrypted Ethereum addresses |
| Euint256 | 256 | and, or, xor, shl, shr, rotl, rotr, eq, ne, neg, not, select, rand, randBounded | |
{% hint style="info" %}
Division (`div`) and remainder (`rem`) operations are only supported when the right-hand side (`rhs`) operand is a plaintext (non-encrypted) value. Attempting to use an encrypted value as `rhs` will result in a panic. This restriction ensures correct and secure computation within the current framework.
{% endhint %}
{% hint style="info" %}
Higher-precision integer types are available in the `TFHE-rs` library and can be added to `fhevm` as needed.
{% endhint %}
# Handles
Every encrypted value in FHEVM (`euint8`, `ebool`, `eaddress`, …) is referenced on-chain by a 32-byte **handle**. FHE operations take and return handles, and the ACL is enforced per handle.
## Glossary
Three concepts that look similar but live in different places:
| Term | What it is | Where it lives |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------- |
| **Plaintext** | The actual cleartext value (e.g. the number `42`). What `decrypt(...)` returns. | Off-chain, only after authorized decryption. |
| **Ciphertext** | The encrypted blob produced by FHE — the bytes the coprocessor stores and computes on. May be re-randomized at any time without changing the plaintext. | Off-chain, with the coprocessor. |
| **Handle** | A 32-byte on-chain identifier that points to a specific (plaintext, ciphertext) pair. The handle is what your Solidity code holds and passes around. | On-chain. |
| **Computation** | The sequence of FHE operations that produced a handle (e.g. `FHE.add(a, b)`). Two different computations may produce the same handle, or the same computation may produce different handles in different contexts. | Conceptual — not stored as such. |
The protocol guarantees a relationship between **handles** and **plaintexts**. It deliberately does not guarantee any relationship between handles and ciphertexts, or between handles and the computations that produced them.
## Core principle: handles are opaque
{% hint style="warning" %}
Treat handles like a name tag, not like the thing itself. The bytes don't tell you anything about how the handle was made or what ciphertext is behind it. The only thing you can read off a handle is which plaintext it points to — and only after decryption.
{% endhint %}
You **can** treat a handle like any other `bytes32`: compare it with `==` / `!=`, store it, log it, etc. The ACL itself works this way. What you **can't** do is guess from the bytes how the handle was made, or which ciphertext sits behind it.
## What you can rely on
The protocol gives you one rule:
> **If two handles are equal, they point to the same plaintext.**
That rule has a mirror that's also true: if two plaintexts are different, their handles must be different too. Anything beyond that, you can't assume.
| You can rely on | You can't rely on |
| ---------------------------------------- | ---------------------------------------------- |
| Equal handles → equal plaintexts | Different handles → different plaintexts |
| Different plaintexts → different handles | Equal plaintexts → equal handles |
| | Equal handles → same computation produced both |
| | Equal handles → same ciphertext underneath |
The protocol may produce equal handles for some equal-plaintext computations and different ones for others — across blocks, across chains, after ciphertext re-randomization, or under future optimizations. Your contract must work either way.
## Common mistakes
**Assuming "same operation, same inputs → same handle".** Today, the protocol mixes the previous block's hash into how each handle is built, so the same computation in two different blocks already gives you different handles. And the reverse — assuming two different operations always produce different handles — can break if the protocol ever optimizes them down to the same handle.
```solidity
// ❌ Don't depend on h3 == h4. Don't depend on h3 != h4 either.
euint64 h3 = FHE.add(h1, h2);
euint64 h4 = FHE.add(h1, h2);
```
**Mixing handles from different places.** A handle that was bridged from another chain, or built off-chain and brought in via `FHE.fromExternal(...)`, is not guaranteed to equal a handle produced by on-chain computation — even when both encode the same plaintext.
If you need to know whether two encrypted values are equal in plaintext, use the FHE operator. It returns an `ebool` that decrypts to `true` if and only if the underlying values match:
```solidity
ebool isEqual = FHE.eq(a, b);
```
# Operations on encrypted types
This document outlines the operations supported on encrypted types in the `FHE` library, enabling arithmetic, bitwise, comparison, and more on Fully Homomorphic Encryption (FHE) ciphertexts.
## Arithmetic operations
The following arithmetic operations are supported for encrypted integers (`euintX`):
| Name | Function name | Symbol | Type |
| ---------------------------- | ------------- | ------ | ------ |
| Add | `FHE.add` | `+` | Binary |
| Subtract | `FHE.sub` | `-` | Binary |
| Multiply | `FHE.mul` | `*` | Binary |
| Divide (plaintext divisor) | `FHE.div` | | Binary |
| Reminder (plaintext divisor) | `FHE.rem` | | Binary |
| Negation | `FHE.neg` | `-` | Unary |
| Min | `FHE.min` | | Binary |
| Max | `FHE.max` | | Binary |
{% hint style="info" %}
Division (FHE.div) and remainder (FHE.rem) operations are currently supported only with plaintext divisors.
{% endhint %}
## Bitwise operations
The FHE library also supports bitwise operations, including shifts and rotations:
| Name | Function name | Symbol | Type |
| ------------ | ------------- | ------ | ------ |
| Bitwise AND | `FHE.and` | `&` | Binary |
| Bitwise OR | `FHE.or` | `\|` | Binary |
| Bitwise XOR | `FHE.xor` | `^` | Binary |
| Bitwise NOT | `FHE.not` | `~` | Unary |
| Shift Right | `FHE.shr` | | Binary |
| Shift Left | `FHE.shl` | | Binary |
| Rotate Right | `FHE.rotr` | | Binary |
| Rotate Left | `FHE.rotl` | | Binary |
The shift operators `FHE.shr` and `FHE.shl` can take any encrypted type `euintX` as a first operand and either a `uint8`or a `euint8` as a second operand, however the second operand will always be computed modulo the number of bits of the first operand. For example, `FHE.shr(euint64 x, 70)` is equivalent to `FHE.shr(euint64 x, 6)` because `70 % 64 = 6`. This differs from the classical shift operators in Solidity, where there is no intermediate modulo operation, so for instance any `uint64` shifted right via `>>` would give a null result.
## Comparison operations
Encrypted integers can be compared using the following functions:
| Name | Function name | Symbol | Type |
| --------------------- | ------------- | ------ | ------ |
| Equal | `FHE.eq` | | Binary |
| Not equal | `FHE.ne` | | Binary |
| Greater than or equal | `FHE.ge` | | Binary |
| Greater than | `FHE.gt` | | Binary |
| Less than or equal | `FHE.le` | | Binary |
| Less than | `FHE.lt` | | Binary |
## Ternary operation
The `FHE.select` function is a ternary operation that selects one of two encrypted values based on an encrypted condition:
| Name | Function name | Symbol | Type |
| ------ | ------------- | ------ | ------- |
| Select | `FHE.select` | | Ternary |
## Random operations
You can generate cryptographically secure random numbers fully on-chain:
<table data-header-hidden><thead><tr><th></th><th width="206"></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Name</strong></td><td><strong>Function Name</strong></td><td><strong>Symbol</strong></td><td><strong>Type</strong></td></tr><tr><td>Random Unsigned Integer</td><td><code>FHE.randEuintX()</code></td><td></td><td>Random</td></프로젝트로 돌아가기