bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 49쪽
utEuint32, bytes calldata inputProof) external {
euint32 evalue = FHE.fromExternal(inputEuint32, inputProof);
// _count += value;
}
```
**With :**
```solidity
/// @notice Increments the counter by a specific value
function increment(externalEuint32 inputEuint32, bytes calldata inputProof) external {
euint32 evalue = FHE.fromExternal(inputEuint32, inputProof);
_count = FHE.add(_count, evalue);
}
```
{% hint style="info" %}
This FHE operation allows the smart contract to process encrypted values without ever decrypting them — a core feature of FHEVM that enables on-chain privacy.
{% endhint %}
{% endstep %}
{% endstepper %}
## Grant FHE Permissions
{% hint style="warning" %}
This step is critical! You must grant FHE permissions to both the contract and the caller to ensure the encrypted `_count` value can be decrypted off-chain by the caller. Without these 2 permissions, the caller will not be able to compute the clear result.
{% endhint %}
To grant FHE permission we will call the `FHE.allow()` function.
#### Replace
```solidity
/// @notice Increments the counter by a specific value
function increment(externalEuint32 inputEuint32, bytes calldata inputProof) external {
euint32 evalue = FHE.fromExternal(inputEuint32, inputProof);
_count = FHE.add(_count, evalue);
}
```
#### With :
```solidity
/// @notice Increments the counter by a specific value
function increment(externalEuint32 inputEuint32, bytes calldata inputProof) external {
euint32 evalue = FHE.fromExternal(inputEuint32, inputProof);
_count = FHE.add(_count, evalue);
FHE.allowThis(_count);
FHE.allow(_count, msg.sender);
}
```
{% hint style="info" %}
We grant **two** FHE permissions here — not just one. In the next part of the tutorial, you'll learn why **both** are necessary.
{% endhint %}
## Convert `decrement()` to its FHEVM equivalent
Just like with the `increment()` migration, we’ll now convert the `decrement()` function to its FHEVM-compatible version.
Replace :
```solidity
/// @notice Decrements the counter by a specific value
function decrement(uint32 value) external {
require(_count >= value, "Counter: cannot decrement below zero");
_count -= value;
}
```
with the following :
```solidity
/// @notice Decrements the counter by a specific value
/// @dev This example omits overflow/underflow checks for simplicity and readability.
/// In a production contract, proper range checks should be implemented.
function decrement(externalEuint32 inputEuint32, bytes calldata inputProof) external {
euint32 encryptedEuint32 = FHE.fromExternal(inputEuint32, inputProof);
_count = FHE.sub(_count, encryptedEuint32);
FHE.allowThis(_count);
FHE.allow(_count, msg.sender);
}
```
{% hint style="warning" %}
The `increment()` and `decrement()` functions do not perform any overflow or underflow checks.
{% endhint %}
## Compile `FHECounter.sol`
From your project's root directory, run:
```sh
npx hardhat compile
```
Congratulations! Your smart contract is now fully **FHEVM-compatible**.
Now you should have the following files in your project:
* [`contracts/FHECounter.sol`](https://docs.zama.ai/protocol/examples/basic/fhe-counter#fhecounter.sol) — your Solidity smart FHEVM contract
* [`test/FHECounter.ts`](https://docs.zama.ai/protocol/examples/basic/fhe-counter#fhecounter.ts) — your FHEVM Hardhat test suite written in TypeScript
In the [next tutorial](https://github.com/zama-ai/fhevm/blob/release/0.10.x/docs/solidity-guides/getting-started/quick-start-tutorial/test_fhevm_contract.md), we’ll move on to the **TypeScript integration**, where you’ll learn how to interact with your newly upgraded FHEVM contract in a test suite.
# Write a simple contract
In this tutorial, you'll write and test a simple regular Solidity smart contract within the FHEVM Hardhat template to get familiar with Hardhat workflow.
In the [next tutorial](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/turn_it_into_fhevm), you'll learn how to convert this contract into an FHEVM contract.
## Prerequisite
* [Set up your Hardhat envrionment](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/setup).
* Make sure that you Hardhat project is clean and ready to start. See the instructions [here](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/setup#rest-set-the-hardhat-envrionment).
## What you'll learn
By the end of this tutorial, you will learn to:
* Write a minimal Solidity contract using Hardhat.
* Test the contract using TypeScript and Hardhat’s testing framework.
## Write a simple contract
{% stepper %}
{% step %}
### Create `Counter.sol`
Go to your project's `contracts` directory:
```sh
cd <your-project-root-directory>/contracts
```
From there, create a new file named `Counter.sol` and copy/paste the following Solidity code in it.
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
/// @title A simple counter contract
contract Counter {
uint32 private _count;
/// @notice Returns the current count
function getCount() external view returns (uint32) {
return _count;
}
/// @notice Increments the counter by a specific value
function increment(uint32 value) external {
_count += value;
}
/// @notice Decrements the counter by a specific value
function decrement(uint32 value) external {
require(_count >= value, "Counter: cannot decrement below zero");
_count -= value;
}
}
```
{% endstep %}
{% step %}
### Compile `Counter.sol`
From your project's root directory, run:
```sh
npx hardhat compile
```
Great! Your Smart Contract is now compiled.
{% endstep %}
{% endstepper %}
## Set up the testing environment
{% stepper %}
{% step %}
### Create a test script `test/Counter.ts`
Go to your project's `test` directory
```sh
cd <your-project-root-directory>/test
```
From there, create a new file named `Counter.ts` and copy/paste the following Typescript skeleton code in it.
```ts
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { ethers } from "hardhat";
describe("Counter", function () {
it("empty test", async function () {
console.log("Cool! The test basic skeleton is running!");
});
});
```
The file contains the following:
* all the required `import` statements we will need during the various tests
* The `chai` basic statements to run a first empty test named `empty test`
{% endstep %}
{% step %}
### Run the test `test/Counter.ts`
From your project's root directory, run:
```sh
npx hardhat test
```
Output:
```sh
Counter
Cool! The test basic skeleton is running!
✔ empty test
1 passing (1ms)
```
Great! Your Hardhat test environment is properly setup.
{% endstep %}
{% step %}
### Set up the test signers
Before interacting with smart contracts in Hardhat tests, we need to initialize signers.
{% hint style="info" %}
In the context of Ethereum development, a signer represents an entity (usually a wallet) that can send transactions and sign messages. In Hardhat, `ethers.getSigners()` returns a list of pre-funded test accounts.
{% endhint %}
We’ll define three named signers for convenience:
* `owner` — the deployer of the contract
* `alice` and `bob` — additional simulated users
**Replace the contents of `test/Counter.ts` with the following:**
```ts
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { ethers } from "hardhat";
type Signers = {
owner: HardhatEthersSigner;
alice: HardhatEthersSigner;
bob: HardhatEthersSigner;
};
describe("Counter", function () {
let signers: Signers;
before(async function () {
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1], bob: ethSigners[2] };
});
it("should work", async function () {
console.log(`address of user owner is ${signers.owner.address}`);
console.log(`address of user alice is ${signers.alice.address}`);
console.log(`address of user bob is ${signers.bob.address}`);
});
});
```
**Run the test**
From your project's root directory, run:
```sh
npx hardhat test
```
**Expected Output**
```sh
Counter
address of user owner is 0x37AC010c1c566696326813b840319B58Bb5840E4
address of user alice is 0xD9F9298BbcD72843586e7E08DAe577E3a0aC8866
address of user bob is 0x3f0CdAe6ebd93F9F776BCBB7da1D42180cC8fcC1
✔ should work
1 passing (2ms)
```
{% endstep %}
{% step %}
### Set up testing instance
Now that we have our signers set up, we can deploy the smart contract.
To ensure isolated and deterministic tests, we should deploy a fresh instance of `Counter.sol` before each test. This avoids any side effects from previous tests.
The standard approach is to define a `deployFixture()` function that handles contract deployment.
```ts
async function deployFixture() {
const factory = (await ethers.getContractFactory("Counter")) as Counter__factory;
const counterContract = (await factory.deploy()) as Counter;
const counterContractAddress = await counterContract.getAddress();
return { counterContract, counterContractAddress };
}
```
To run this setup before each test case, call `deployFixture()` inside a `beforeEach` block:
```ts
beforeEach(async () => {
({ counterContract, counterContractAddress } = await deployFixture());
});
```
This ensures each test runs with a clean, independent contract instance.
Let's put it together. Now your`test/Counter.ts` should look like the following:
```ts
import { Counter, Counter__factory } from "../types";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers } from "hardhat";
type Signers = {
deployer: HardhatEthersSigner;
alice: HardhatEthersSigner;
bob: HardhatEthersSigner;
};
async function deployFixture() {
const factory = (await ethers.getContractFactory("Counter")) as Counter__factory;
const counterContract = (await factory.deploy()) as Counter;
const counterContractAddress = await counterContract.getAddress();
return { counterContract, counterContractAddress };
}
describe("Counter", function () {
let signers: Signers;
let counterContract: Counter;
let counterContractAddress: Counter;
before(async function () {
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { deployer: ethSigners[0], alice: ethSigners[1], bob: ethSigners[2] };
});
beforeEach(async () => {
// Deploy a new instance of the contract before each test
({ counterContract, counterContractAddress } = await deployFixture());
});
it("should be deployed", async function () {
console.log(`Counter has been deployed at address ${counterContractAddress}`);
// Test the deployed address is valid
expect(ethers.isAddress(counterContractAddress)).to.eq(true);
});
});
```
**Run the test:**
From your project's root directory, run:
```sh
npx hardhat test
```
**Expected Output:**
```sh
Counter
Counter has been deployed at address 0x7553CB9124f974Ee475E5cE45482F90d5B6076BC
✔ should be deployed
1 passing (7ms)
```
{% endstep %}
{% endstepper %}
## Test functions
Now everything is up and running, you can start testing your contract functions.
{% stepper %}
{% step %}
### Call the contract `getCount()` view function
Everything is up and running, we can now call the `Counter.sol` view function `getCount()` !
Just below the test block `it("should be deployed", async function () {...}`,
add the following unit test:
```ts
it("count should be zero after deployment", async function () {
const count = await counterContract.getCount();
console.log(`Counter.getCount() === ${count}`);
// Expect initial count to be 0 after deployment
expect(count).to.eq(0);
});
```
**Run the test**
From your project's root directory, run:
```sh
npx hardhat test
```
**Expected Output**
```sh
Counter
Counter has been deployed at address 0x7553CB9124f974Ee475E5cE45482F90d5B6076BC
✔ should be deployed
Counter.getCount() === 0
✔ count should be zero after deployment
1 passing (7ms)
```
{% endstep %}
{% step %}
### Call the contract `increment()` transaction function
Just below the test block `it("count should be zero after deployment", async function () {...}`, add the following test block:
```ts
it("increment the counter by 1", async function () {
const countBeforeInc = await counterContract.getCount();
const tx = await counterContract.connect(signers.alice).increment(1);
await tx.wait();
const countAfterInc = await counterContract.getCount();
expect(countAfterInc).to.eq(countBeforeInc + 1n);
});
```
**Remarks:**
* `increment()` is a transactional function that modifies the blockchain state.
* It must be signed by a user — here we use `alice`.
* `await wait()` to wait for the transaction to mined.
* The test compares the counter before and after the transaction to ensure it incremented as expected.
**Run the test**
From your project's root directory, run:
```sh
npx hardhat test
```
**Expected Output**
```sh
Counter
Counter has been deployed at address 0x7553CB9124f974Ee475E5cE45482F90d5B6076BC
✔ should be deployed
Counter.getCount() === 0
✔ count should be zero after deployment
✔ increment the counter by 1
2 passing (12ms)
```
{% endstep %}
{% step %}
### Call the contract `decrement()` transaction function
Just below the test block `it("increment the counter by 1", async function () {...}`,
add the following test block:
```ts
it("decrement the counter by 1", async function () {
// First increment, count becomes 1
let tx = await counterContract.connect(signers.alice).increment(1);
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);
});
```
***
**Run the test**
From your project's root directory, run:
```sh
npx hardhat test
```
**Expected Output**
```sh
Counter
Counter has been deployed at address 0x7553CB9124f974Ee475E5cE45482F90d5B6076BC
✔ should be deployed
Counter.getCount() === 0
✔ count should be zero after deployment
✔ increment the counter by 1
✔ decrement the counter by 1
2 passing (12ms)
```
{% endstep %}
{% endstepper %}
Now you have successfully written and tested your counter contract. You should have the following files in your project:
* [`contracts/Counter.sol`](https://docs.zama.ai/protocol/examples/basic/fhe-counter#counter.sol) — your Solidity smart contract
* [`test/Counter.ts`](https://docs.zama.ai/protocol/examples/basic/fhe-counter#counter.ts) — your Hardhat test suite written in TypeScript
These files form the foundation of a basic Hardhat-based smart contract project.
## Next step
Now that you've written and tested a basic Solidity smart contract, you're ready to take the next step.
In the [next tutorial](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/turn_it_into_fhevm), we’ll transform this standard `Counter.sol` contract into `FHECounter.sol`, a trivial FHEVM-compatible version — allowing the counter value to be stored and updated using trivial fully homomorphic encryption.
# hardhat
This section will guide you through writing and testing FHEVM smart contracts in Solidity using [Hardhat](https://hardhat.org).
### The FHEVM Hardhat Plugin
To write FHEVM smart contracts using Hardhat, you need to install the [FHEVM Hardhat Plugin](https://www.npmjs.com/package/@fhevm/hardhat-plugin) in your Hardhat project.
This plugin enables you to develop, test, and interact with FHEVM contracts right out of the box.
It extends Hardhat’s functionality with a complete FHEVM API that allows you:
* Encrypt data
* Decrypt data
* Run tests using various FHEVM execution modes
* Write FHEVM-enabled Hardhat Tasks
### Where to go next
🟨 Go to [**Setup Hardhat**](https://docs.zama.ai/protocol/solidity-guides/getting-started/setup) to initialize your FHEVM Hardhat project.
🟨 Go to [**Write FHEVM Tests in Hardhat**](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat/write_test) for details on writing tests of FHEVM smart contracts using Hardhat.
🟨 Go to [**Run FHEVM Tests in Hardhat**](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat/run_test) to learn how to execute those tests in different FHEVM environments.
🟨 Go to [**Write FHEVM Hardhat Task**](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat/write_task) to learn how to write your own custom FHEVM Hardhat task.
# run\_test
In this section, you'll find everything you need to test your FHEVM smart contracts in your [Hardhat](https://hardhat.org) project.
### FHEVM Runtime Modes
The FHEVM Hardhat plugin provides three **FHEVM runtime modes** tailored for different stages of contract development and testing. Each mode offers a trade-off between speed, encryption, and persistence.
1. The **Hardhat (In-Memory)** default network: 🧪 *Uses mock encryption.* Ideal for regular tests, CI test coverage, and fast feedback during early contract development. No real encryption is used.
2. The **Hardhat Node (Local Server)** network: 🧪 *Uses mock encryption.* Ideal when you need persistent state - for example, when testing frontend interactions, simulating user flows, or validating deployments in a realistic local environment. Still uses mock encryption.
3. The **Sepolia Testnet** network: 🔐 *Uses real encryption.* Use this mode once your contract logic is stable and validated locally. This is the only mode that runs on the full FHEVM stack with **real encrypted values**. It simulates real-world production conditions but is slower and requires Sepolia ETH.
{% hint style="success" %}
**Zama Testnet** is not a blockchain itself. It is a protocol that enables you to run confidential smart contracts on existing blockchains (such as Ethereum, Base, and others) with the support of encrypted types. See the [FHE on blockchain](https://docs.zama.ai/protocol/protocol/overview) guide to learn more about the protocol architecture.
Currently, **Zama Protocol** is available on the **Sepolia Testnet**. Support for additional chains will be added in the future. [See the roadmap↗](https://docs.zama.ai/protocol/zama-protocol-litepaper#roadmap)
{% endhint %}
#### 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 depl프로젝트로 돌아가기