Zama 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 50쪽

oyed 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\_task 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 CounterDeployement = taskArguments.address ? { address: taskArguments.address } : await deployments.get("Counter"); console.log(`Counter: ${CounterDeployement.address}`); const counterContract = await ethers.getContractAt("Counter", CounterDeployement.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 CounterDeployement = taskArguments.address // ? { address: taskArguments.address } // : await deployments.get("Counter"); // console.log(`Counter: ${CounterDeployement.address}`); // const counterContract = await ethers.getContractAt("Counter", CounterDeployement.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 CounterDeployement = taskArguments.address // ? { address: taskArguments.address } // : await deployments.get("Counter"); // console.log(`Counter: ${CounterDeployement.address}`); // const counterContract = await ethers.getContractAt("Counter", CounterDeployement.address); // const clearCount = await counterContract.getCount(); ``` With the FHEVM equivalent: ```ts const FHECounterDeployement = taskArguments.address ? { address: taskArguments.address } : await deployments.get("FHECounter"); console.log(`FHECounter: ${FHECounterDeployement.address}`); const fheCounterContract = await ethers.getContractAt("FHECounter", FHECounterDeployement.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, FHECounterDeployement.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 %} # write\_test In this section, you'll find everything you need to set up a new [Hardhat](https://hardhat.org) project and start developing FHEVM smart contracts from scratch using the [FHEVM Hardhat Plugin](https://www.npmjs.com/package/@fhevm/hardhat-plugin) ### Enabling the FHEVM Hardhat Plugin in your Hardhat project Like any Hardhat plugin, the [FHEVM Hardhat Plugin](https://www.npmjs.com/package/@fhevm/hardhat-plugin) must be enabled by adding the following `import` statement to your `hardhat.config.ts` file: ```typescript import "@fhevm/hardhat-plugin"; ``` {% hint style="warning" %} Without this import, the Hardhat FHEVM API will **not** be available in your Hardhat runtime environment (HRE). {% endhint %} ### Accessing the Hardhat FHEVM API The plugin extends the standard [Hardhat Runtime Environment](https://hardhat.org/hardhat-runner/docs/advanced/hardhat-runtime-environment) (or `hre` in short) with the new `fhevm` Hardhat module. You can access it in either of the following ways: ```typescript import { fhevm } from "hardhat"; ``` or ```typescript import * as hre from "hardhat"; // Then access: hre.fhevm ``` ### Encrypting Values Using the Hardhat FHEVM API Suppose the FHEVM smart contract you want to test has a function called `foo` that takes an encrypted `uint32` value as input. The Solidity function `foo` should be declared as follows: ```solidity function foo(externalEunit32 value, bytes calldata memory inputProof); ``` Where: * `externalEunit32 value` : is a `bytes32` representing the encrypted `uint32` * `bytes calldata memory inputProof` : is a `bytes` array representing the zero-knowledge proof of knowledge that validates the encryption To compute these arguments in TypeScript, you need: * The **address of the target smart contract** * The **signer’s address** (i.e., the account sending the transaction) {% stepper %} {% step %} **Create a new encryted input** ```ts // use the `fhevm` API module from the Hardhat Runtime Environment const input = fhevm.createEncryptedInput(contractAddress, signers.alice.address); ``` {% endstep %} {% step %} **Add the value you want to encrypt.** ```ts input.add32(12345); ``` {% endstep %} {% step %} **Perform local encryption.** ```ts const encryptedInputs = await input.encrypt(); ``` {% endstep %} {% step %} **Call the Solidity function** ```ts const externalUint32Value = encryptedInputs.handles[0]; const inputProof = encryptedInputs.proof; const tx = await input.foo(externalUint32Value, inputProof); await tx.wait(); ``` {% endstep %} {% endstepper %} #### Encryption examples * [Basic encryption examples](https://docs.zama.ai/protocol/examples/basic/encryption) * [FHECounter](https://docs.zama.ai/protocol/examples#an-fhe-counter) ### Decrypting values using the Hardhat FHEVM API Suppose user **Alice** wants to decrypt a `euint32` value that is stored in a smart contract exposing the following Solidity `view` function: ```solidity function getEncryptedUint32Value() public view returns (euint32) { returns _encryptedUint32Value; } ``` {% hint style="warning" %} For simplicity, we assume that both Alice’s account and the target smart contract already have the necessary FHE permissions to decrypt this value. For a detailed explanation of how FHE permissions work, see the [`initializeUint32()`](https://docs.zama.ai/protocol/examples/basic/decryption/fhe-decrypt-single-value#tab-decryptsinglevalue.sol) function in [DecryptSingleValue.sol](https://docs.zama.ai/protocol/examples/basic/decryption/fhe-decrypt-single-value#tab-decryptsinglevalue.sol). {% endhint %} {% stepper %} {% step %} **Retrieve the encrypted value (a `bytes32` handle) from the smart contract:** ```ts const encryptedUint32Value = await contract.getEncryptedUint32Value(); ``` {% endstep %} {% step %} **Perform the decryption using the FHEVM API:** ```ts const clearUint32Value = await fhevm.userDecryptEuint( FhevmType.euint32, // Encrypted type (must match the Solidity type) encryptedUint32Value, // bytes32 handle Alice wants to decrypt contractAddress, // Target contract address signers.alice, // Alice’s wallet ); ``` {% hint style="warning" %} If either the target smart contract or the user does **NOT** have FHE permissions, then the decryption call will fail! {% endhint %} {% endstep %} {% endstepper %} #### Supported Decryption Types Use the appropriate function for each encrypted data type: | Type | Function | | ---------- | -------------------------------- | | `euintXXX` | `fhevm.userDecryptEuint(...)` | | `ebool` | `fhevm.userDecryptEbool(...)` | | `eaddress` | `fhevm.userDecryptEaddress(...)` | #### Decryption examples * [Basic decryption examples](https://docs.zama.ai/protocol/examples/basic/decryption) * [FHECounter](https://docs.zama.ai/protocol/examples#an-fhe-counter) # logics # Branching in FHE This document explains how to implement conditional logic (if/else branching) when working with encrypted values in FHEVM. Unlike typical Solidity programming, working with Fully Homomorphic Encryption (FHE) requires specialized methods to handle conditions on encrypted data. This document covers encrypted branching and how to move from an encrypted condition to a non-encrypted business logic in your smart contract. ## What is confidential branching? In FHEVM, when you perform [comparison operations](/protocol/solidity-guides/v0.10/docs/solidity-guides/operations#comparison-operations), the result is an encrypted boolean (`ebool`). Since encrypted booleans do not support standard boolean operations like `if` statements or logical operators, conditional logic must be implemented using specialized methods. To facilitate conditional assignments, FHEVM provides the `FHE.select` function, which acts as a ternary operator for encrypted values. ## **Using `FHE.select` for conditional logic** The `FHE.select` function enables branching logic by selecting one of two encrypted values based on an encrypted condition (`ebool`). It works as follows: ```solidity FHE.select(condition, valueIfTrue, valueIfFalse); ``` * **`condition`**: An encrypted boolean (`ebool`) resulting from a comparison. * **`valueIfTrue`**: The encrypted value to return if the condition is true. * **`valueIfFalse`**: The encrypted value to return if the condition is false. ## **Example: Auction Bidding Logic** Here's an example of using conditional logic to update the highest winning number in a guessing game: ```solidity function bid(externalEuint64 encryptedValue, bytes calldata inputProof) external onlyBeforeEnd { // Convert the encrypted input to an encrypted 64-bit integer euint64 bid = FHE.asEuint64(encryptedValue, inputProof); // Compare the current highest bid with the new bid ebool isAbove = FHE.lt(highestBid, bid); // Update the highest bid if the new bid is greater highestBid = FHE.select(isAbove, bid, highestBid); // Allow the contract to use the updated highest bid ciphertext FHE.allowThis(highestBid); } ``` {% hint style="info" %} This is a simplified example to demonstrate the functionality. {% endhint %} ### How Does It Work? * **Comparison**: * The `FHE.lt` function compares `highestBid` and `bid`, returning an `ebool` (`isAbove`) that indicates whether the new bid is higher. * **Selection**: * The `FHE.select` function updates `highestBid` to either the new bid or the previous highest bid, based on the encrypted condition `isAbove`. * **Permission Handling**: * After updating `highestBid`, the contract reauthorizes itself to manipulate the updated ciphertext using `FHE.allowThis`. ## Key Considerations * **Value change behavior:** Each time `FHE.select` assigns a value, a new ciphertext is created, even if the underlying plaintext value remains unchanged. This behavior is inherent to FHE and ensures data confidentiality, but developers should account for it when designing their smart contracts. * **Gas consumption:** Using `FHE.select` and other encrypted operations incurs additional gas costs compared to traditional Solidity logic. Optimize your code to minimize unnecessary operations. * **Access control:** Always use appropriate ACL functions (e.g., `FHE.allowThis`, `FHE.allow`) to ensure the updated ciphertexts are authorized for use in future computations or transactions. *** ## How to branch to a non-confidential path? So far, this section only covered how to do branching using encrypted variables. However, there may be many cases where the "public" contract logic will depend on the outcome from a encrypted path. To do so, there are only one way to branch from an encrypted path to a non-encrypted path: it requires an off-chain public decryption. Hence, any contract logic that requires moving from an encrypted input to a non-encrypted path always requires an async contract logic. ## **Example: Auction Bidding Logic: Item Release** Going back to our previous example with the auction bidding logic. Let's assume that the winner of the auction can receive some prize, which is not confidential. ```solidity bool public isPrizeDistributed; eaddress internal highestBidder; euint64 internal highestBid; function bid(externalEuint64 encryptedValue, bytes calldata inputProof) external onlyBeforeEnd { // Convert the encrypted input to an encrypted 64-bit integer euint64 bid = FHE.asEuint64(encryptedValue, inputProof); // Compare the current highest bid with the new bid ebool isAbove = FHE.lt(highestBid, bid); // Update the highest bid if the new bid is greater highestBid = FHE.select(isAbove, bid, highestBid); // Update the highest bidder address if the new bid is greater highestBidder = FHE.select(isAbove, FHE.asEaddress(msg.sender), currentBidder)); // Allow the contract to use the highest bidder address FHE.allowThis(highestBidder); // Allow the contract to use the updated highest bid ciphertext FHE.allowThis(highestBid); } function revealWinner() external onlyAfterEnd { FHE.makePubliclyDecryptable(highestBidder); } function transferPrize(address auctionWinner, bytes calldata decryptionProof) external { require(!isPrizeDistributed, "Prize has already been distributed"); bytes32[] memory cts = new bytes32[](1); cts[0] = FHE.toBytes32(highestBidder); bytes memory cleartexts = abi.encode(auctionWinner); // This FHE call reverts the transaction if: // - the decryption proof is invalid. // - the provided cleartext (auctionWinner) does not match the cleartext value // that results from the off-chain decryption of the ciphertext (highestBidder). // - the decryption proof does not correspond to the specific pairing of // the ciphertext (highestBidder) and the cleartext (auctionWinner). FHE.checkSignatures(cts, cleartexts, decryptionProof); isPrizeDistributed = true; // Business logic to transfer the prize to the auction winner } ``` {% hint style="info" %} This is a simplified example to demonstrate the functionality. {% endhint %} As you can see the in the above example, the path to move from an encrypted condition to a decrypted business logic must be async and requires an off-chain public decryption to reveal the result of the logic using encrypted variables. ## Summary * **`FHE.select`** is a powerful tool for conditional logic on encrypted values. * Encrypted booleans (`ebool`) and values maintain confidentiality, enabling privacy-preserving logic. * Developers should account for gas costs and ciphertext behavior when designing conditional operations. # Error handling This document explains how to handle errors effectively in FHEVM smart contracts. Since transactions involving encrypted data do not automatically revert when conditions are not met, developers need alternative mechanisms to communicate errors to users. ## **Challenges in error handling** In the context of encrypted data: 1. **No automatic reversion**: Transactions do not rev
프로젝트로 돌아가기