bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 33쪽
gleValue.ts" %}
```ts
import { UserDecryptSingleValue, UserDecryptSingleValue__factory } from "../../../types";
import type { Signers } from "../../types";
import { FhevmType, HardhatFhevmRuntimeEnvironment } from "@fhevm/hardhat-plugin";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers } from "hardhat";
import * as hre from "hardhat";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("UserDecryptSingleValue")) as UserDecryptSingleValue__factory;
const userUserDecryptSingleValue = (await factory.deploy()) as UserDecryptSingleValue;
const userUserDecryptSingleValue_address = await userUserDecryptSingleValue.getAddress();
return { userUserDecryptSingleValue, userUserDecryptSingleValue_address };
}
/**
* This trivial example demonstrates the FHE user decryption mechanism
* and highlights a common pitfall developers may encounter.
*/
describe("UserDecryptSingleValue", function () {
let contract: UserDecryptSingleValue;
let contractAddress: string;
let signers: Signers;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1] };
});
beforeEach(async function () {
// Deploy a new contract each time we run a new test
const deployment = await deployFixture();
contractAddress = deployment.userUserDecryptSingleValue_address;
contract = deployment.userUserDecryptSingleValue;
});
// ✅ Test should succeed
it("user decryption should succeed", async function () {
const tx = await contract.connect(signers.alice).initializeUint32(123456);
await tx.wait();
const encryptedUint32 = await contract.encryptedUint32();
// The FHEVM Hardhat plugin provides a set of convenient helper functions
// that make it easy to perform FHEVM operations within your Hardhat environment.
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
const clearUint32 = await fhevm.userDecryptEuint(
FhevmType.euint32, // Specify the encrypted type
encryptedUint32,
contractAddress, // The contract address
signers.alice, // The user wallet
);
expect(clearUint32).to.equal(123456 + 1);
});
// ❌ Test should fail
it("user decryption should fail", async function () {
const tx = await contract.connect(signers.alice).initializeUint32Wrong(123456);
await tx.wait();
const encryptedUint32 = await contract.encryptedUint32();
await expect(
hre.fhevm.userDecryptEuint(FhevmType.euint32, encryptedUint32, contractAddress, signers.alice),
).to.be.rejectedWith(new RegExp("^dapp contract (.+) is not authorized to user decrypt handle (.+)."));
});
});
```
{% endtab %}
{% endtabs %}
# fheadd
This example demonstrates how to write a simple "a + b" contract using FHEVM.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="FHEAdd.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { FHE, euint8, externalEuint8 } from "@fhevm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
contract FHEAdd is ZamaEthereumConfig {
euint8 private _a;
euint8 private _b;
// solhint-disable-next-line var-name-mixedcase
euint8 private _a_plus_b;
// solhint-disable-next-line no-empty-blocks
constructor() {}
function setA(externalEuint8 inputA, bytes calldata inputProof) external {
_a = FHE.fromExternal(inputA, inputProof);
FHE.allowThis(_a);
}
function setB(externalEuint8 inputB, bytes calldata inputProof) external {
_b = FHE.fromExternal(inputB, inputProof);
FHE.allowThis(_b);
}
function computeAPlusB() external {
// The sum `a + b` is computed by the contract itself (`address(this)`).
// Since the contract has FHE permissions over both `a` and `b`,
// it is authorized to perform the `FHE.add` operation on these values.
// It does not matter if the contract caller (`msg.sender`) has FHE permission or not.
_a_plus_b = FHE.add(_a, _b);
// At this point the contract ifself (`address(this)`) has been granted ephemeral FHE permission
// over `_a_plus_b`. This FHE permission will be revoked when the function exits.
//
// Now, to make sure `_a_plus_b` can be decrypted by the contract caller (`msg.sender`),
// we need to grant permanent FHE permissions to both the contract ifself (`address(this)`)
// and the contract caller (`msg.sender`)
FHE.allowThis(_a_plus_b);
FHE.allow(_a_plus_b, msg.sender);
}
function result() public view returns (euint8) {
return _a_plus_b;
}
}
```
{% endtab %}
{% tab title="FHEAdd.ts" %}
```ts
import { FHEAdd, FHEAdd__factory } from "../../../types";
import type { Signers } from "../../types";
import { FhevmType, HardhatFhevmRuntimeEnvironment } from "@fhevm/hardhat-plugin";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers } from "hardhat";
import * as hre from "hardhat";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("FHEAdd")) as FHEAdd__factory;
const fheAdd = (await factory.deploy()) as FHEAdd;
const fheAdd_address = await fheAdd.getAddress();
return { fheAdd, fheAdd_address };
}
/**
* This trivial example demonstrates the FHE encryption mechanism
* and highlights a common pitfall developers may encounter.
*/
describe("FHEAdd", function () {
let contract: FHEAdd;
let contractAddress: string;
let signers: Signers;
let bob: HardhatEthersSigner;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1] };
bob = ethSigners[2];
});
beforeEach(async function () {
// Deploy a new contract each time we run a new test
const deployment = await deployFixture();
contractAddress = deployment.fheAdd_address;
contract = deployment.fheAdd;
});
it("a + b should succeed", async function () {
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
let tx;
// Let's compute 80 + 123 = 203
const a = 80;
const b = 123;
// Alice encrypts and sets `a` as 80
const inputA = await fhevm.createEncryptedInput(contractAddress, signers.alice.address).add8(a).encrypt();
tx = await contract.connect(signers.alice).setA(inputA.handles[0], inputA.inputProof);
await tx.wait();
// Alice encrypts and sets `b` as 203
const inputB = await fhevm.createEncryptedInput(contractAddress, signers.alice.address).add8(b).encrypt();
tx = await contract.connect(signers.alice).setB(inputB.handles[0], inputB.inputProof);
await tx.wait();
// Why Bob has FHE permissions to execute the operation in this case ?
// See `computeAPlusB()` in `FHEAdd.sol` for a detailed answer
tx = await contract.connect(bob).computeAPlusB();
await tx.wait();
const encryptedAplusB = await contract.result();
const clearAplusB = await fhevm.userDecryptEuint(
FhevmType.euint8, // Specify the encrypted type
encryptedAplusB,
contractAddress, // The contract address
bob, // The user wallet
);
expect(clearAplusB).to.equal(a + b);
});
});
```
{% endtab %}
{% endtabs %}
# fheifthenelse
This example demonstrates how to write a simple contract with conditions using FHEVM, in comparison to a simple counter.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="FHEIfThenElse.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { FHE, ebool, euint8, externalEuint8 } from "@fhevm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
contract FHEIfThenElse is ZamaEthereumConfig {
euint8 private _a;
euint8 private _b;
euint8 private _max;
// solhint-disable-next-line no-empty-blocks
constructor() {}
function setA(externalEuint8 inputA, bytes calldata inputProof) external {
_a = FHE.fromExternal(inputA, inputProof);
FHE.allowThis(_a);
}
function setB(externalEuint8 inputB, bytes calldata inputProof) external {
_b = FHE.fromExternal(inputB, inputProof);
FHE.allowThis(_b);
}
function computeMax() external {
// a >= b
// solhint-disable-next-line var-name-mixedcase
ebool _a_ge_b = FHE.ge(_a, _b);
// a >= b ? a : b
_max = FHE.select(_a_ge_b, _a, _b);
// For more information about FHE permissions in this case,
// read the `computeAPlusB()` commentaries in `FHEAdd.sol`.
FHE.allowThis(_max);
FHE.allow(_max, msg.sender);
}
function result() public view returns (euint8) {
return _max;
}
}
```
{% endtab %}
{% tab title="FHEIfThenElse.ts" %}
```ts
import { FHEIfThenElse, FHEIfThenElse__factory } from "../../../types";
import type { Signers } from "../../types";
import { FhevmType, HardhatFhevmRuntimeEnvironment } from "@fhevm/hardhat-plugin";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers } from "hardhat";
import * as hre from "hardhat";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("FHEIfThenElse")) as FHEIfThenElse__factory;
const fheIfThenElse = (await factory.deploy()) as FHEIfThenElse;
const fheIfThenElse_address = await fheIfThenElse.getAddress();
return { fheIfThenElse, fheIfThenElse_address };
}
/**
* This trivial example demonstrates the FHE encryption mechanism
* and highlights a common pitfall developers may encounter.
*/
describe("FHEIfThenElse", function () {
let contract: FHEIfThenElse;
let contractAddress: string;
let signers: Signers;
let bob: HardhatEthersSigner;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1] };
bob = ethSigners[2];
});
beforeEach(async function () {
// Deploy a new contract each time we run a new test
const deployment = await deployFixture();
contractAddress = deployment.fheIfThenElse_address;
contract = deployment.fheIfThenElse;
});
it("a >= b ? a : b should succeed", async function () {
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
let tx;
// Let's compute `a >= b ? a : b`
const a = 80;
const b = 123;
// Alice encrypts and sets `a` as 80
const inputA = await fhevm.createEncryptedInput(contractAddress, signers.alice.address).add8(a).encrypt();
tx = await contract.connect(signers.alice).setA(inputA.handles[0], inputA.inputProof);
await tx.wait();
// Alice encrypts and sets `b` as 203
const inputB = await fhevm.createEncryptedInput(contractAddress, signers.alice.address).add8(b).encrypt();
tx = await contract.connect(signers.alice).setB(inputB.handles[0], inputB.inputProof);
await tx.wait();
// Why Bob has FHE permissions to execute the operation in this case ?
// See `computeAPlusB()` in `FHEAdd.sol` for a detailed answer
tx = await contract.connect(bob).computeMax();
await tx.wait();
const encryptedMax = await contract.result();
const clearMax = await fhevm.userDecryptEuint(
FhevmType.euint8, // Specify the encrypted type
encryptedMax,
contractAddress, // The contract address
bob, // The user wallet
);
expect(clearMax).to.equal(a >= b ? a : b);
});
});
```
{% endtab %}
{% endtabs %}
# heads-or-tails
This example showcases the public decryption mechanism and its corresponding on-chain verification in the case of a single value. The core assertion is to guarantee that a single given cleartext is the cryptographically verifiable result of the decryption of a single original on-chain ciphertext.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="HeadsOrTails.sol" %}
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { FHE, ebool } from "@fhevm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
/**
* @title HeadsOrTails
* @notice Implements a simple Heads or Tails game demonstrating public, permissionless decryption
* using the FHE.makePubliclyDecryptable feature.
* @dev Inherits from ZamaEthereumConfig to access FHE functions like FHE.randEbool() and FHE.verifySignatures().
*/
contract HeadsOrTails is ZamaEthereumConfig {
constructor() {}
/**
* @notice Simple counter to assign a unique ID to each new game.
*/
uint256 private counter = 0;
/**
* @notice Defines the entire state for a single Heads or Tails game instance.
*/
struct Game {
/// @notice The address of the player who chose Heads.
address headsPlayer;
/// @notice The address of the player who chose Tails.
address tailsPlayer;
/// @notice The core encrypted result. This is a publicly decryptable ebool handle.
// true means Heads won; false means Tails won.
ebool encryptedHasHeadsWon;
/// @notice The clear address of the final winner, set after decryption and verification.
address winner;
}
/**
* @notice Mapping to store all game states, accessible by a unique game ID.
*/
mapping(uint256 gameId => Game game) public games;
/**
* @notice Emitted when a new game is started, providing the encrypted handle required for decryption.
* @param gameId The unique identifier for the game.
* @param headsPlayer The address choosing Heads.
* @param tailsPlayer The address choosing Tails.
* @param encryptedHasHeadsWon The encrypted handle (ciphertext) storing the result.
*/
event GameCreated(
uint256 indexed gameId,
address indexed headsPlayer,
address indexed tailsPlayer,
ebool encryptedHasHeadsWon
);
/**
* @notice Initiates a new Heads or Tails game, generates the result using FHE,
* and makes the result publicly available for decryption.
* @param headsPlayer The player address choosing Heads.
* @param tailsPlayer The player address choosing Tails.
*/
function headsOrTails(address headsPlayer, address tailsPlayer) external {
require(headsPlayer != address(0), "Heads player is address zero");
require(tailsPlayer != address(0), "Tails player is address zero");
require(headsPlayer != tailsPlayer, "Heads player and Tails player should be different");
// true: Heads
// false: Tails
ebool headsOrTailsResult = FHE.randEbool();
counter++;
// gameId > 0
uint256 gameId = counter;
games[gameId] = Game({
headsPlayer: headsPlayer,
tailsPlayer: tailsPlayer,
encryptedHasHeadsWon: headsOrTailsResult,
winner: address(0)
});
// We make the result publicly decryptable.
FHE.makePubliclyDecryptable(headsOrTailsResult);
// You can catch the event to get the gameId and the encryptedHasHeadsWon handle
// for further decryption requests, or create a view function.
emit GameCreated(gameId, headsPlayer, tailsPlayer, games[gameId].encryptedHasHeadsWon);
}
/**
* @notice Returns the number of games created so far.
* @return The number of games created.
*/
function getGamesCount() public view returns (uint256) {
return counter;
}
/**
* @notice Returns the encrypted ebool handle that stores the game result.
* @param gameId The ID of the game.
* @return The encrypted result (ebool handle).
*/
function hasHeadsWon(uint256 gameId) public view returns (ebool) {
return games[gameId].encryptedHasHeadsWon;
}
/**
* @notice Returns the address of the game winner.
* @param gameId The ID of the game.
* @return The winner's address (address(0) if not yet revealed).
*/
function getWinner(uint256 gameId) public view returns (address) {
require(games[gameId].winner != address(0), "Game winner not yet revealed");
return games[gameId].winner;
}
/**
* @notice Verifies the provided (decryption proof, ABI-encoded clear value) pair against the stored ciphertext,
* and then stores the winner of the game.
* @param gameId The ID of the game to settle.
* @param abiEncodedClearGameResult The ABI-encoded clear value (bool) associated to the `decryptionProof`.
* @param decryptionProof The proof that validates the decryption.
*/
function recordAndVerifyWinner(
uint256 gameId,
bytes memory abiEncodedClearGameResult,
bytes memory decryptionProof
) public {
require(games[gameId].winner == address(0), "Game winner already revealed");
// 1. FHE Verification: Build the list of ciphertexts (handles) and verify the proof.
// The verification checks that 'abiEncodedClearGameResult' is the true decryption
// of the 'encryptedHasHeadsWon' handle using the provided 'decryptionProof'.
// Creating the list of handles in the right order! In this case the order does not matter since the proof
// only involves 1 single handle.
bytes32[] memory cts = new bytes32[](1);
cts[0] = FHE.toBytes32(games[gameId].encryptedHasHeadsWon);
// This FHE call reverts the transaction if the decryption proof is invalid.
FHE.checkSignatures(cts, abiEncodedClearGameResult, decryptionProof);
// 2. Decode the clear result and determine the winner's address.
// In this very specific case, the function argument `abiEncodedClearGameResult` could have been a simple
// `bool` instead of an abi-encoded bool. In this case, we should have compute abi.encode on-chain
bool decodedClearGameResult = abi.decode(abiEncodedClearGameResult, (bool));
address winner = decodedClearGameResult ? games[gameId].headsPlayer : games[gameId].tailsPlayer;
// 3. Store the winner
games[gameId].winner = winner;
}
}
```
{% endtab %}
{% tab title="HeadsOrTails.ts" %}
```ts
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers as EthersT } from "ethers";
import { ethers, fhevm } from "hardhat";
import * as hre from "hardhat";
import { HeadsOrTails, HeadsOrTails__factory } from "../../../typechain-types";
import { Signers } from "../signers";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("HeadsOrTails")) as HeadsOrTails__factory;
const headsOrTails = (await factory.deploy()) as HeadsOrTails;
const headsOrTails_address = await headsOrTails.getAddress();
return { headsOrTails, headsOrTails_address };
}
describe("HeadsOrTails", function () {
let contract: HeadsOrTails;
let contractAddress: string;
let signers: Signers;
let playerA: HardhatEthersSigner;
let playerB: HardhatEthersSigner;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1], bob: ethSign프로젝트로 돌아가기