docs: rename TFHE.sol to FHE.sol in the docs (#756)

* docs: rename tfhe to fhe

* docs: renaming all function names in the docs and library names

* docs: update all mentions of TFHE

* docs: tfhe-rs stays the same

* docs: tfhe-rs stays the same

* docs: rename repo

* docs: fix renaming after merge conflicts

* docs: resolve issues
This commit is contained in:
Aurora Poppyseed
2025-05-12 11:17:58 +02:00
committed by GitHub
parent 851c4683a6
commit ade634a945
31 changed files with 277 additions and 277 deletions

View File

@@ -4,4 +4,4 @@
If you find a security related bug in HTTPZ, we kindly ask you for responsible disclosure and for giving us appropriate time to react, analyze and develop a fix to mitigate the found security vulnerability.
To report the vulnerability please open a draft [GitHub security advisory](https://github.com/zama-ai/fhevm/security/advisories/new)
To report the vulnerability please open a draft [GitHub security advisory](https://github.com/zama-ai/fhevm-solidity/security/advisories/new)

View File

@@ -10,16 +10,16 @@ This document gives a preview of the upcoming features of fhevm. In addition to
## Operations
| Name | Function name | Type | ETA |
| --------------------- | ------------------ | ------------------ | ----------- |
| Signed Integers | `eintX` | | Coming soon |
| Add w/ overflow check | `TFHE.safeAdd` | Binary, Decryption | Coming soon |
| Sub w/ overflow check | `TFHE.safeSub` | Binary, Decryption | Coming soon |
| Mul w/ overflow check | `TFHE.safeMul` | Binary, Decryption | Coming soon |
| Random signed int | `TFHE.randEintX()` | Random | - |
| Div | `TFHE.div` | Binary | - |
| Rem | `TFHE.rem` | Binary | - |
| Set inclusion | `TFHE.isIn()` | Binary | - |
| Name | Function name | Type | ETA |
| --------------------- | ----------------- | ------------------ | ----------- |
| Signed Integers | `eintX` | | Coming soon |
| Add w/ overflow check | `FHE.safeAdd` | Binary, Decryption | Coming soon |
| Sub w/ overflow check | `FHE.safeSub` | Binary, Decryption | Coming soon |
| Mul w/ overflow check | `FHE.safeMul` | Binary, Decryption | Coming soon |
| Random signed int | `FHE.randEintX()` | Random | - |
| Div | `FHE.div` | Binary | - |
| Rem | `FHE.rem` | Binary | - |
| Set inclusion | `FHE.isIn()` | Binary | - |
{% hint style="info" %}
Random encrypted integers that are generated fully on-chain. Currently, implemented as a mockup by using a PRNG in the plain. Not for use in production!

View File

@@ -108,7 +108,7 @@ Once the WASM is loaded, you can now create an instance. An instance receives an
import { initFhevm, createInstance } from "@fhevm/sdk/bundle";
const init = async () => {
await initFhevm(); // Load TFHE
await initFhevm(); // Load FHE
return createInstance({
kmsContractAddress: "0x9D6891A6240D6130c54ae243d8005063D05fE14b",
aclContractAddress: "0xFee8407e2f5e3Ee68ad77cAE98c434e637f516e5",

View File

@@ -45,7 +45,7 @@ resolve: {
**Possible solutions:**
- If you encounter issues with typing, you can use this [tsconfig.json](https://github.com/zama-ai/fhevmjs-react-template/blob/main/tsconfig.json) using TypeScript 5.
- If you encounter issues with typing, you can use this [tsconfig.json](https://github.com/zama-ai/fhevm-react-template/blob/main/tsconfig.json) using TypeScript 5.
- If you encounter any other issue, you can force import of the browser package.
## Use bundled version

View File

@@ -27,12 +27,12 @@ Let's break down the contract.
```solidity
pragma solidity ^0.8.24;
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import "fhevm/config/ZamaFHEVMConfig.sol";
import "fhevm-contracts/contracts/token/ERC20/extensions/ConfidentialERC20Mintable.sol";
```
- **`TFHE.sol`**: The core Solidity library of fhevm. It enables encrypted data type like `euint64`, secures encrypted operations, such as addition and comparison and allows access control.
- **`FHE.sol`**: The core Solidity library of fhevm. It enables encrypted data type like `euint64`, secures encrypted operations, such as addition and comparison and allows access control.
- **`SepoliaZamaFHEVMConfig`**: A configuration contract that automatically sets up the required configurations for real-time encrypted operations on the Sepolia testnet.
- **`ConfidentialERC20Mintable.sol`** : The confidential smart contract that allows for full ERC20 compatibility with FHE encryption.

View File

@@ -33,7 +33,7 @@ Copy the following code in the `MyConfidentialERC20.sol` that you just created:
pragma solidity ^0.8.24;
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import "fhevm/config/ZamaFHEVMConfig.sol";
contract MyConfidentialERC20 is SepoliaZamaFHEVMConfig {}
@@ -45,7 +45,7 @@ It should appear as follows:
Remix automatically saves any changes as you type. Upon saving, it imports the following libraries:
- **`TFHE.sol`**: The core Solidity library of fhevm. It enables encrypted data type like `euint64`, secures encrypted operations, such as addition and comparison and allows access control.
- **`FHE.sol`**: The core Solidity library of fhevm. It enables encrypted data type like `euint64`, secures encrypted operations, such as addition and comparison and allows access control.
- **`SepoliaZamaFHEVMConfig`**: A configuration contract that automatically sets up the required configurations for real-time encrypted operations on the Sepolia testnet.
### Step 2.2 Enhancing the functionality
@@ -77,7 +77,7 @@ To use `ConfidentialERC20Mintable` contract, simply update your `MyConfidentialE
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import "fhevm/config/ZamaFHEVMConfig.sol";
import "fhevm-contracts/contracts/token/ERC20/extensions/ConfidentialERC20Mintable.sol";

View File

@@ -6,7 +6,7 @@ fhevm is a suite of solutions that enables confidential smart contracts on the E
### For dApp developers
The fhevm Protocol provides a **`TFHE` Solidity library** for building confidential smart contracts, a **fhevm SDK** to enable frontend FHE interactions, and a range of developer tools, examples, and templates to streamline the usage for developers. 
The fhevm Protocol provides a **`FHE` Solidity library** for building confidential smart contracts, a **fhevm SDK** to enable frontend FHE interactions, and a range of developer tools, examples, and templates to streamline the usage for developers. 
#### Smart contract development
@@ -14,7 +14,7 @@ The fhevm Protocol provides a **`TFHE` Solidity library** for building confident
#### Frontend development
<table><thead><tr><th width="252">Repository</th><th>Description</th></tr></thead><tbody><tr><td><a href="https://github.com/zama-ai/fhevmjs/">@fhevm/sdk</a></td><td>JavaScript library for clientside FHE, enabling encryption, decryption, and data handling.</td></tr><tr><td><a href="https://github.com/zama-ai/fhevm-react-template">fhevm-react-template</a></td><td>React.js template to quickly spin up FHEenabled dApps.</td></tr><tr><td><a href="https://github.com/zama-ai/fhevm-next-template">fhevm-next-template</a></td><td>Next.js template for integrating FHE in serverside rendered or hybrid web apps.</td></tr><tr><td><a href="https://github.com/zama-ai/fhevm-vue-template">fhevm-vue-template</a></td><td>Vue.js template for creating privacypreserving dApps with encrypted data</td></tr></tbody></table>
<table><thead><tr><th width="252">Repository</th><th>Description</th></tr></thead><tbody><tr><td><a href="https://github.com/zama-ai/fhevm-js/">@fhevm/sdk</a></td><td>JavaScript library for clientside FHE, enabling encryption, decryption, and data handling.</td></tr><tr><td><a href="https://github.com/zama-ai/fhevm-react-template">fhevm-react-template</a></td><td>React.js template to quickly spin up FHEenabled dApps.</td></tr><tr><td><a href="https://github.com/zama-ai/fhevm-next-template">fhevm-next-template</a></td><td>Next.js template for integrating FHE in serverside rendered or hybrid web apps.</td></tr><tr><td><a href="https://github.com/zama-ai/fhevm-vue-template">fhevm-vue-template</a></td><td>Vue.js template for creating privacypreserving dApps with encrypted data</td></tr></tbody></table>
#### Examples & Resources

View File

@@ -2,7 +2,7 @@
This document provides an overview of the `@fhevm/sdk` library, detailing its initialization, instance creation, input handling, encryption, and re-encryption processes.
[@fhevm/sdk](https://github.com/zama-ai/fhevmjs/) is designed to assist in creating encrypted inputs and retrieving re-encryption data off-chain through a gateway. The library works with any fhevm Coprocessors.
[@fhevm/sdk](https://github.com/zama-ai/fhevm-js/) is designed to assist in creating encrypted inputs and retrieving re-encryption data off-chain through a gateway. The library works with any fhevm Coprocessors.
## Init (browser)

View File

@@ -1,10 +1,10 @@
# Smart contracts - fhevm API
This document provides an overview of the functions available in the `TFHE` Solidity library. The TFHE library provides functionality for working with encrypted types and performing operations on them. It implements fully homomorphic encryption (FHE) operations in Solidity.
This document provides an overview of the functions available in the `FHE` Solidity library. The FHE library provides functionality for working with encrypted types and performing operations on them. It implements fully homomorphic encryption (FHE) operations in Solidity.
## Overview
The `TFHE` Solidity library provides essential functionality for working with encrypted data types and performing fully homomorphic encryption (FHE) operations in smart contracts. It is designed to streamline the developer experience while maintaining flexibility and performance.
The `FHE` Solidity library provides essential functionality for working with encrypted data types and performing fully homomorphic encryption (FHE) operations in smart contracts. It is designed to streamline the developer experience while maintaining flexibility and performance.
### **Core Functionality**
@@ -52,10 +52,10 @@ The library ensures that all operations on encrypted data follow the constraints
### Casting Types
- **Casting between encrypted types**: `TFHE.asEbool` converts encrypted integers to encrypted booleans
- **Casting to encrypted types**: `TFHE.asEuintX` converts plaintext values to encrypted types
- **Casting to encrypted addresses**: `TFHE.asEaddress` converts plaintext addresses to encrypted addresses
- **Casting to encrypted bytes**: `TFHE.asEbytesX` converts plaintext bytes to encrypted bytes
- **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
- **Casting to encrypted bytes**: `FHE.asEbytesX` converts plaintext bytes to encrypted bytes
#### `asEuint`
@@ -114,7 +114,7 @@ function sub(T a, T b) internal returns (T)
function mul(T a, T b) internal returns (T)
```
- Arithmetic: `TFHE.add`, `TFHE.sub`, `TFHE.mul`, `TFHE.min`, `TFHE.max`, `TFHE.neg`, `TFHE.div`, `TFHE.rem`
- 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
#### Arithmetic operations (`add`, `sub`, `mul`, `div`, `rem`)
@@ -168,11 +168,11 @@ More information about the behavior of these operators can be found at the [TFHE
### Bitwise operations
- Bitwise: `TFHE.and`, `TFHE.or`, `TFHE.xor`, `TFHE.not`, `TFHE.shl`, `TFHE.shr`, `TFHE.rotl`, `TFHE.rotr`
- Bitwise: `FHE.and`, `FHE.or`, `FHE.xor`, `FHE.not`, `FHE.shl`, `FHE.shr`, `FHE.rotl`, `FHE.rotr`
#### Bitwise operations (`AND`, `OR`, `XOR`)
Unlike other binary operations, bitwise operations do not natively accept a mix of ciphertext and plaintext inputs. To ease developer experience, the `TFHE` library adds function overloads for these operations. Such overloads implicitely do a trivial encryption before actually calling the operation function, as shown in the examples below.
Unlike other binary operations, bitwise operations do not natively accept a mix of ciphertext and plaintext inputs. To ease developer experience, the `FHE` library adds function overloads for these operations. Such overloads implicitely do a trivial encryption before actually calling the operation function, as shown in the examples below.
Available for euint\* types:
@@ -268,7 +268,7 @@ This operator takes three inputs. The first input `b` is of type `ebool` and the
```solidity
// if (b == true) return val1 else return val2
function select(ebool b, euint8 val1, euint8 val2) internal view returns (euint8) {
return TFHE.select(b, val1, val2);
return FHE.select(b, val1, val2);
}
```
@@ -282,12 +282,12 @@ That can only be done during transactions and not on an `eth_call` RPC method, b
```solidity
// Generate a random encrypted unsigned integer `r`.
euint32 r = TFHE.randEuint32();
euint32 r = FHE.randEuint32();
```
## Access control functions
The `TFHE` library provides a robust set of access control functions for managing permissions on encrypted values. These functions ensure that encrypted data can only be accessed or manipulated by authorized accounts or contracts.
The `FHE` library provides a robust set of access control functions for managing permissions on encrypted values. These functions ensure that encrypted data can only be accessed or manipulated by authorized accounts or contracts.
### Permission management
@@ -313,16 +313,16 @@ The `allow` and `allowTransient` functions enable fine-grained control over who
```solidity
// Store an encrypted value.
euint32 r = TFHE.asEuint32(94);
euint32 r = FHE.asEuint32(94);
// Grant permanent access to the current contract.
TFHE.allowThis(r);
FHE.allowThis(r);
// Grant permanent access to the caller.
TFHE.allow(r, msg.sender);
FHE.allow(r, msg.sender);
// Grant temporary access to an external account.
TFHE.allowTransient(r, 0x1234567890abcdef1234567890abcdef12345678);
FHE.allowTransient(r, 0x1234567890abcdef1234567890abcdef12345678);
```
### Permission checks
@@ -351,13 +351,13 @@ These functions help ensure that only authorized accounts or contracts can acces
```solidity
// Store an encrypted value.
euint32 r = TFHE.asEuint32(94);
euint32 r = FHE.asEuint32(94);
// Verify if the current contract is allowed to access the value.
bool isContractAllowed = TFHE.isAllowed(r, address(this)); // returns true
bool isContractAllowed = FHE.isAllowed(r, address(this)); // returns true
// Verify if the caller has access to the value.
bool isCallerAllowed = TFHE.isSenderAllowed(r); // depends on msg.sender
bool isCallerAllowed = FHE.isSenderAllowed(r); // depends on msg.sender
```
## Storage Management
@@ -380,7 +380,7 @@ function finalize() public {
// Perform operations...
// Clean up transient storage.
TFHE.cleanTransientStorage();
FHE.cleanTransientStorage();
}
```

View File

@@ -33,7 +33,7 @@ Access the essential libraries for building and integrating FHE-enabled applicat
| **Repository** | **Description** |
| ------------------------------------------------------------ | --------------------------------------------------------------- |
| [fhevm-solidity](https://github.com/zama-ai/fhevm-solidity/) | Solidity library for FHE operations |
| [@fhevm/sdk](https://github.com/zama-ai/fhevmjs/) | JavaScript library for client-side FHE |
| [@fhevm/sdk](https://github.com/zama-ai/fhevm-js/) | JavaScript library for client-side FHE |
| [fhevm-backend](https://github.com/zama-ai/fhevm-backend) | Rust backend and go-ethereum modules for native and coprocessor |
## **Core implementations**

View File

@@ -19,18 +19,18 @@ Encrypted data in fhevm is entirely confidential, meaning that without proper ac
### Types of access
- **Permanent allowance**:
- Configured using `TFHE.allow(ciphertext, address)`.
- Configured using `FHE.allow(ciphertext, address)`.
- Grants long-term access to the ciphertext for a specific address.
- Stored in a dedicated contract for persistent storage.
- **Transient allowance**:
- Configured using `TFHE.allowTransient(ciphertext, address)`.
- Configured using `FHE.allowTransient(ciphertext, address)`.
- Grants access to the ciphertext only for the duration of the current transaction.
- Stored in transient storage, reducing gas costs.
- Ideal for temporary operations like passing ciphertexts to external functions.
**Syntactic sugar**:
- `TFHE.allowThis(ciphertext)` is shorthand for `TFHE.allow(ciphertext, address(this))`. It authorizes the current contract to reuse a ciphertext handle in future transactions.
- `FHE.allowThis(ciphertext)` is shorthand for `FHE.allow(ciphertext, address(this))`. It authorizes the current contract to reuse a ciphertext handle in future transactions.
### Transient vs. permanent allowance

View File

@@ -10,21 +10,21 @@ The ACL system allows you to define two types of permissions for accessing ciphe
### Permanent allowance
- **Function**: `TFHE.allow(ciphertext, address)`
- **Function**: `FHE.allow(ciphertext, address)`
- **Purpose**: Grants persistent access to a ciphertext for a specific address.
- **Storage**: Permissions are saved in a dedicated ACL contract, making them available across transactions.
### Transient allowance
- **Function**: `TFHE.allowTransient(ciphertext, address)`
- **Function**: `FHE.allowTransient(ciphertext, address)`
- **Purpose**: Grants temporary access for the duration of a single transaction.
- **Storage**: Permissions are stored in transient storage to save gas costs.
- **Use Case**: Ideal for passing encrypted values between functions or contracts during a transaction.
### Syntactic sugar
- **Function**: `TFHE.allowThis(ciphertext)`
- **Equivalent To**: `TFHE.allow(ciphertext, address(this))`
- **Function**: `FHE.allowThis(ciphertext)`
- **Equivalent To**: `FHE.allow(ciphertext, address(this))`
- **Purpose**: Simplifies granting permanent access to the current contract for managing ciphertexts.
---
@@ -32,7 +32,7 @@ The ACL system allows you to define two types of permissions for accessing ciphe
### Example: granting permissions in a multi-contract setup
```solidity
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import { SepoliaZamaFHEVMConfig } from "fhevm/config/ZamaFHEVMConfig.sol";
contract SecretGiver is SepoliaZamaFHEVMConfig {
@@ -44,10 +44,10 @@ contract SecretGiver is SepoliaZamaFHEVMConfig {
function giveMySecret() public {
// Create my secret - asEuint16 gives automatically transient allowance for the resulting handle (note: an onchain trivial encryption is not secret)
euint16 mySecret = TFHE.asEuint16(42);
euint16 mySecret = FHE.asEuint16(42);
// Allow temporarily the SecretStore contract to manipulate `mySecret`
TFHE.allowTransient(mySecret, address(secretStore));
FHE.allowTransient(mySecret, address(secretStore));
// Call `secretStore` with `mySecret`
secretStore.storeSecret(mySecret);
@@ -61,16 +61,16 @@ contract SecretStore is SepoliaZamaFHEVMConfig {
function storeSecret(euint16 callerSecret) public {
// Verify that the caller has also access to this ciphertext
require(TFHE.isSenderAllowed(callerSecret), "The caller is not authorized to access this secret.");
require(FHE.isSenderAllowed(callerSecret), "The caller is not authorized to access this secret.");
// do some FHE computation (result is automatically put in the ACL transient storage)
euint16 computationResult = TFHE.add(callerSecret, 3);
euint16 computationResult = FHE.add(callerSecret, 3);
// then store the resulting ciphertext handle in the contract storage
secretResult = computationResult;
// Make the temporary allowance for this ciphertext permanent to let the contract able to reuse it at a later stage or request a decryption of it
TFHE.allowThis(secretResult); // this is strictly equivalent to `TFHE.allow(secretResult, address(this));``
FHE.allowThis(secretResult); // this is strictly equivalent to `FHE.allow(secretResult, address(this));``
}
}
```
@@ -82,21 +82,21 @@ contract SecretStore is SepoliaZamaFHEVMConfig {
Some functions automatically grant transient allowances to the calling contract, simplifying workflow. These include:
- **Type Conversion**:
- `TFHE.asEuintXX()`, `TFHE.asEbool()`, `TFHE.asEaddress()`
- `FHE.asEuintXX()`, `FHE.asEbool()`, `FHE.asEaddress()`
- **Random Value Generation**:
- `TFHE.randXX()`
- `FHE.randXX()`
- **Computation Results**:
- `TFHE.add()`, `TFHE.select()`
- `FHE.add()`, `FHE.select()`
### Example: random value generation
```solidity
function randomize() public {
// Generate a random encrypted value with transient allowance
euint64 random = TFHE.randEuint64();
euint64 random = FHE.randEuint64();
// Convert the transient allowance into a permanent one
TFHE.allowThis(random);
FHE.allowThis(random);
}
```
@@ -119,7 +119,7 @@ Consider an **Encrypted ERC20 token**. An attacker controlling two accounts, **A
This type of attack allows the attacker to infer private balances without explicit access.
To prevent this, always use the `TFHE.isSenderAllowed()` function to verify that the sender has legitimate access to the encrypted amount being transferred.
To prevent this, always use the `FHE.isSenderAllowed()` function to verify that the sender has legitimate access to the encrypted amount being transferred.
---
@@ -128,10 +128,10 @@ To prevent this, always use the `TFHE.isSenderAllowed()` function to verify that
```solidity
function transfer(address to, euint64 encryptedAmount, bytes calldata inputProof) public {
// Ensure the sender is authorized to access the encrypted amount
require(TFHE.isSenderAllowed(encryptedAmount), "Unauthorized access to encrypted amount.");
require(FHE.isSenderAllowed(encryptedAmount), "Unauthorized access to encrypted amount.");
// Proceed with further logic
euint64 amount = TFHE.asEuint64(encryptedAmount);
euint64 amount = FHE.asEuint64(encryptedAmount);
...
}
```
@@ -148,21 +148,21 @@ Due to the reencryption mechanism, a user signs a public key associated with a s
```solidity
function transfer(address to, euint64 encryptedAmount) public {
require(TFHE.isSenderAllowed(encryptedAmount), "The caller is not authorized to access this encrypted amount.");
euint64 amount = TFHE.asEuint64(encryptedAmount);
ebool canTransfer = TFHE.le(amount, balances[msg.sender]);
require(FHE.isSenderAllowed(encryptedAmount), "The caller is not authorized to access this encrypted amount.");
euint64 amount = FHE.asEuint64(encryptedAmount);
ebool canTransfer = FHE.le(amount, balances[msg.sender]);
euint64 newBalanceTo = TFHE.add(balances[to], TFHE.select(canTransfer, amount, TFHE.asEuint64(0)));
euint64 newBalanceTo = FHE.add(balances[to], FHE.select(canTransfer, amount, FHE.asEuint64(0)));
balances[to] = newBalanceTo;
// Allow this new balance for both the contract and the owner.
TFHE.allowThis(newBalanceTo);
TFHE.allow(newBalanceTo, to);
FHE.allowThis(newBalanceTo);
FHE.allow(newBalanceTo, to);
euint64 newBalanceFrom = TFHE.sub(balances[from], TFHE.select(canTransfer, amount, TFHE.asEuint64(0)));
euint64 newBalanceFrom = FHE.sub(balances[from], FHE.select(canTransfer, amount, FHE.asEuint64(0)));
balances[from] = newBalanceFrom;
// Allow this new balance for both the contract and the owner.
TFHE.allowThis(newBalanceFrom);
TFHE.allow(newBalanceFrom, from);
FHE.allowThis(newBalanceFrom);
FHE.allow(newBalanceFrom, from);
}
```

View File

@@ -8,7 +8,7 @@ This system relies on three key types:&#x20;
- The **private key:** used for decryption and securely managed by the Key Management System or KMS
- The **evaluation key:** enabling encrypted computations performed by the coprocessor.
The fhevm leverages Zama's TFHE library, integrating seamlessly with blockchain environments to address transparency, composability, and scalability challenges. Its hybrid architecture combines:
The fhevm leverages Zama's FHE library, integrating seamlessly with blockchain environments to address transparency, composability, and scalability challenges. Its hybrid architecture combines:
- **On-chain smart contracts** for encrypted state management and access controls.
- **Off-chain coprocessors** for resource-intensive FHE computations.

View File

@@ -6,11 +6,11 @@ This document gives a detailed explanantion of each component of fhevm and illus
The fhevm architecture is built around four primary components, each contributing to the system's functionality and performance. These components work together to enable the development and execution of private, composable smart contracts on EVM-compatible blockchains. Below is an overview of these components and their responsibilities:
| [**fhevm Smart Contracts**](fhevm-components.md#fhevm-smart-contracts) | Smart contracts deployed on the blockchain to manage encrypted data and interactions. | Includes the Access Control List (ACL) contract, `TFHE.sol` Solidity library, `Gateway.sol` and other FHE-enabled smart contracts. |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| [**Gateway**](fhevm-components.md#gateway) | An off-chain service that bridges the blockchain with the cryptographic systems like KMS and coprocessor. | Acts as an intermediary to forward the necessary requests and results between the blockchain, the KMS, and users. |
| [**Coprocessor**](fhevm-components.md#coprocessor) | An off-chain computational engine designed to execute resource-intensive FHE operations. | Executes symbolic FHE operations, manages ciphertext storage, and ensures efficient computation handling. |
| [**Key Management System (KMS)**](fhevm-components.md#key-management-system-kms) | A decentralized cryptographic service that securely manages FHE keys and validates operations. | Manages the global FHE key (public, private, evaluation), performs threshold decryption, and validates ZKPoKs. |
| [**fhevm Smart Contracts**](fhevm-components.md#fhevm-smart-contracts) | Smart contracts deployed on the blockchain to manage encrypted data and interactions. | Includes the Access Control List (ACL) contract, `FHE.sol` Solidity library, `Gateway.sol` and other FHE-enabled smart contracts. |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| [**Gateway**](fhevm-components.md#gateway) | An off-chain service that bridges the blockchain with the cryptographic systems like KMS and coprocessor. | Acts as an intermediary to forward the necessary requests and results between the blockchain, the KMS, and users. |
| [**Coprocessor**](fhevm-components.md#coprocessor) | An off-chain computational engine designed to execute resource-intensive FHE operations. | Executes symbolic FHE operations, manages ciphertext storage, and ensures efficient computation handling. |
| [**Key Management System (KMS)**](fhevm-components.md#key-management-system-kms) | A decentralized cryptographic service that securely manages FHE keys and validates operations. | Manages the global FHE key (public, private, evaluation), performs threshold decryption, and validates ZKPoKs. |
<figure><img src="../../.gitbook/assets/architecture.png" alt="FHE Keys Overview"><figcaption><p>High level overview of the fhevm Architecture</p></figcaption></figure>
@@ -21,11 +21,11 @@ As a developer working with fhevm, your workflow typically involves two key elem
1. **Frontend development**:\
You create a frontend interface for users to interact with your confidential application. This includes encrypting inputs using the public FHE key and submitting them to the blockchain.
2. **Smart contract development**:\
You write Solidity contracts deployed on the same blockchain as the fhevm smart contracts. These contracts leverage the `TFHE.sol` library to perform operations on encrypted data. Below, we explore the major components involved.
You write Solidity contracts deployed on the same blockchain as the fhevm smart contracts. These contracts leverage the `FHE.sol` library to perform operations on encrypted data. Below, we explore the major components involved.
## **fhevm smart contracts**
fhevm smart contracts include the Access Control List (ACL) contract, `TFHE.sol` library, and related FHE-enabled contracts.
fhevm smart contracts include the Access Control List (ACL) contract, `FHE.sol` library, and related FHE-enabled contracts.
### **Symbolic execution in Solidity**

View File

@@ -1,6 +1,6 @@
# asEbool, asEuintXX, asEaddress and asEbytesXX operations
This documentation covers the `asEbool`, `asEuintXX`, `asEaddress` and `asEbytesXX` operations provided by the TFHE library for working with encrypted data in the fhevm. These operations are essential for converting between plaintext and encrypted types, as well as handling encrypted inputs.
This documentation covers the `asEbool`, `asEuintXX`, `asEaddress` and `asEbytesXX` operations provided by the FHE library for working with encrypted data in the fhevm. These operations are essential for converting between plaintext and encrypted types, as well as handling encrypted inputs.
The operations can be categorized into three main use cases:
@@ -14,7 +14,7 @@ Trivial encryption simply put is a plain text in a format of a ciphertext.
### Overview
Trivial encryption is the process of converting plaintext values into encrypted types (ciphertexts) compatible with TFHE operators. Although the data is in ciphertext format, it remains publicly visible on-chain, making it useful for operations between public and private values.
Trivial encryption is the process of converting plaintext values into encrypted types (ciphertexts) compatible with FHE operators. Although the data is in ciphertext format, it remains publicly visible on-chain, making it useful for operations between public and private values.
This type of casting involves converting plaintext (unencrypted) values into their encrypted equivalents, such as:
@@ -28,17 +28,17 @@ This type of casting involves converting plaintext (unencrypted) values into the
#### **Example**
```solidity
euint64 value64 = TFHE.asEuint64(7262); // Trivial encrypt a uint64
ebool valueBool = TFHE.asEbool(true); // Trivial encrypt a boolean
euint64 value64 = FHE.asEuint64(7262); // Trivial encrypt a uint64
ebool valueBool = FHE.asEbool(true); // Trivial encrypt a boolean
```
### Trivial encryption of `ebytesXX` types
The `TFHE.padToBytesXX` functions facilitate this trivial encryption process for byte arrays, ensuring compatibility with `ebytesXX` types. These functions:
The `FHE.padToBytesXX` functions facilitate this trivial encryption process for byte arrays, ensuring compatibility with `ebytesXX` types. These functions:
- Pad the provided byte array to the appropriate length (`64`, `128`, or `256` bytes).
- Prevent runtime errors caused by improperly sized input data.
- Work seamlessly with `TFHE.asEbytesXX` for trivial encryption.
- Work seamlessly with `FHE.asEbytesXX` for trivial encryption.
> **Important**: Trivial encryption does NOT provide any privacy guarantees. The input data remains fully visible on the blockchain. Only use trivial encryption when working with public values that need to interact with actual encrypted data.
@@ -47,9 +47,9 @@ The `TFHE.padToBytesXX` functions facilitate this trivial encryption process for
1. **Pad Input Data**:
Use the `padToBytesXX` functions to ensure your byte array matches the size requirements.
2. **Encrypt the Padded Data**:
Use `TFHE.asEbytesXX` to encrypt the padded byte array into the corresponding encrypted type.
Use `FHE.asEbytesXX` to encrypt the padded byte array into the corresponding encrypted type.
3. **Grant Access**:
Use `TFHE.allowThis` and `TFHE.allow`optionally, if you want to persist allowance for those variables for later use.
Use `FHE.allowThis` and `FHE.allow`optionally, if you want to persist allowance for those variables for later use.
### Example: Trivial Encryption with `ebytesXX`
@@ -58,31 +58,31 @@ Below is an example demonstrating how to encrypt and manage `ebytes64`, `ebytes1
```solidity
function trivialEncrypt() public {
// Encrypt a 64-byte array
ebytes64 yBytes64 = TFHE.asEbytes64(
TFHE.padToBytes64(
ebytes64 yBytes64 = FHE.asEbytes64(
FHE.padToBytes64(
hex"19d179e0cc7e816dc944582ed4f5652f5951900098fc2e0a15a7ea4dc8cfa4e3b6c54beea5ee95e56b728762f659347ce1d4aa1b05fcc5"
)
);
TFHE.allowThis(yBytes64);
TFHE.allow(yBytes64, msg.sender);
FHE.allowThis(yBytes64);
FHE.allow(yBytes64, msg.sender);
// Encrypt a 128-byte array
ebytes128 yBytes128 = TFHE.asEbytes128(
TFHE.padToBytes128(
ebytes128 yBytes128 = FHE.asEbytes128(
FHE.padToBytes128(
hex"13e7819123de6e2870c7e83bb764508e22d7c3ab8a5aee6bdfb26355ef0d3f1977d651b83bf5f78634fa360aa14debdc3daa6a587b5c2fb1710ab4d6677e62a8577f2d9fecc190ad8b11c9f0a5ec3138b27da1f055437af8c90a9495dad230"
)
);
TFHE.allowThis(yBytes128);
TFHE.allow(yBytes128, msg.sender);
FHE.allowThis(yBytes128);
FHE.allow(yBytes128, msg.sender);
// Encrypt a 256-byte array
ebytes256 yBytes256 = TFHE.asEbytes256(
TFHE.padToBytes256(
ebytes256 yBytes256 = FHE.asEbytes256(
FHE.padToBytes256(
hex"d179e0cc7e816dc944582ed4f5652f5951900098fc2e0a15a7ea4dc8cfa4e3b6c54beea5ee95e56b728762f659347ce1d4aa1b05fcc513e7819123de6e2870c7e83bb764508e22d7c3ab8a5aee6bdfb26355ef0d3f1977d651b83bf5f78634fa360aa14debdc3daa6a587b5c2fb1710ab4d6677e62a8577f2d9fecc190ad8b11c9f0a5ec3138b27da1f055437af8c90a9495dad230"
)
);
TFHE.allowThis(yBytes256);
TFHE.allow(yBytes256, msg.sender);
FHE.allowThis(yBytes256);
FHE.allow(yBytes256, msg.sender);
}
```
@@ -102,11 +102,11 @@ Casting between encrypted types is often required when working with operations t
The table below summarizes the available casting functions:
| From type | To type | Function |
| --------- | -------- | ---------------- |
| `euintX` | `euintX` | `TFHE.asEuintXX` |
| `ebool` | `euintX` | `TFHE.asEuintXX` |
| `euintX` | `ebool` | `TFHE.asEboolXX` |
| From type | To type | Function |
| --------- | -------- | --------------- |
| `euintX` | `euintX` | `FHE.asEuintXX` |
| `ebool` | `euintX` | `FHE.asEuintXX` |
| `euintX` | `ebool` | `FHE.asEboolXX` |
{% hint style="info" %}
Casting between encrypted types is efficient and often necessary when handling data with differing precision requirements.
@@ -116,8 +116,8 @@ Casting between encrypted types is efficient and often necessary when handling d
```solidity
// Casting between encrypted types
euint32 value32 = TFHE.asEuint32(value64); // Cast to euint32
ebool valueBool = TFHE.asEbool(value32); // Cast to ebool
euint32 value32 = FHE.asEuint32(value64); // Cast to euint32
ebool valueBool = FHE.asEbool(value32); // Cast to ebool
```
## 3. Encrypted input
@@ -131,7 +131,7 @@ Encrypted inputs is in depth explained in the following section: [encrypted inpu
#### Example
```solidity
euint64 encryptedValue = TFHE.asEuint64(einputHandle, inputProof); // Interpret einputHandle as euint64
euint64 encryptedValue = FHE.asEuint64(einputHandle, inputProof); // Interpret einputHandle as euint64
```
#### Details
@@ -145,15 +145,15 @@ For more information, see the [Encrypetd inputs documentation](./inputs.md)
## Overall operation summary
| Casting Type | Function | Input Type | Output Type |
| ------------------------ | ----------------------- | ----------------------- | ----------- |
| Trivial encryption | `TFHE.asEuintXX(x)` | `uintX` | `euintX` |
| | `TFHE.asEbool(x)` | `bool` | `ebool` |
| | `TFHE.asEbytesXX(x)` | `bytesXX` | `ebytesXX` |
| | `TFHE.asEaddress(x)` | `address` | `eaddress` |
| Conversion between types | `TFHE.asEuintXX(x)` | `euintXX`/`ebool` | `euintYY` |
| | `TFHE.asEbool(x)` | `euintXX` | `ebool` |
| Encrypted input | `TFHE.asEuintXX(x, y)` | `einput`, `bytes` proof | `euintX` |
| | `TFHE.asEbool(x, y)` | `einput`,`bytes` proof | `ebool` |
| | `TFHE.asEbytesXX(x, y)` | `einput`,`bytes` proof | `ebytesXX` |
| | `TFHE.asEaddress(x, y)` | `einput`, `bytes` proof | `eaddress` |
| Casting Type | Function | Input Type | Output Type |
| ------------------------ | ---------------------- | ----------------------- | ----------- |
| Trivial encryption | `FHE.asEuintXX(x)` | `uintX` | `euintX` |
| | `FHE.asEbool(x)` | `bool` | `ebool` |
| | `FHE.asEbytesXX(x)` | `bytesXX` | `ebytesXX` |
| | `FHE.asEaddress(x)` | `address` | `eaddress` |
| Conversion between types | `FHE.asEuintXX(x)` | `euintXX`/`ebool` | `euintYY` |
| | `FHE.asEbool(x)` | `euintXX` | `ebool` |
| Encrypted input | `FHE.asEuintXX(x, y)` | `einput`, `bytes` proof | `euintX` |
| | `FHE.asEbool(x, y)` | `einput`,`bytes` proof | `ebool` |
| | `FHE.asEbytesXX(x, y)` | `einput`,`bytes` proof | `ebytesXX` |
| | `FHE.asEaddress(x, y)` | `einput`, `bytes` proof | `eaddress` |

View File

@@ -6,14 +6,14 @@ This document explains how to implement conditional logic (if/else branching) wh
In fhevm, when you perform [comparison operations](../references/functions.md#comparison-operation-eq-ne-ge-gt-le-lt), 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 `TFHE.select` function, which acts as a ternary operator for encrypted values.
To facilitate conditional assignments, fhevm provides the `FHE.select` function, which acts as a ternary operator for encrypted values.
## **Using `TFHE.select` for conditional logic**
## **Using `FHE.select` for conditional logic**
The `TFHE.select` function enables branching logic by selecting one of two encrypted values based on an encrypted condition (`ebool`). It works as follows:
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
TFHE.select(condition, valueIfTrue, valueIfFalse);
FHE.select(condition, valueIfTrue, valueIfFalse);
```
- **`condition`**: An encrypted boolean (`ebool`) resulting from a comparison.
@@ -27,16 +27,16 @@ Here's an example of using conditional logic to update the highest winning numbe
```solidity
function bid(einput encryptedValue, bytes calldata inputProof) external onlyBeforeEnd {
// Convert the encrypted input to an encrypted 64-bit integer
euint64 bid = TFHE.asEuint64(encryptedValue, inputProof);
euint64 bid = FHE.asEuint64(encryptedValue, inputProof);
// Compare the current highest bid with the new bid
ebool isAbove = TFHE.lt(highestBid, bid);
ebool isAbove = FHE.lt(highestBid, bid);
// Update the highest bid if the new bid is greater
highestBid = TFHE.select(isAbove, bid, highestBid);
highestBid = FHE.select(isAbove, bid, highestBid);
// Allow the contract to use the updated highest bid ciphertext
TFHE.allowThis(highestBid);
FHE.allowThis(highestBid);
}
```
@@ -47,23 +47,23 @@ This is a simplified example to demonstrate the functionality. For a complete im
### **How It Works**
- **Comparison**:
- The `TFHE.lt` function compares `highestBid` and `bid`, returning an `ebool` (`isAbove`) that indicates whether the new bid is higher.
- The `FHE.lt` function compares `highestBid` and `bid`, returning an `ebool` (`isAbove`) that indicates whether the new bid is higher.
- **Selection**:
- The `TFHE.select` function updates `highestBid` to either the new bid or the previous highest bid, based on the encrypted condition `isAbove`.
- 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 `TFHE.allowThis`.
- After updating `highestBid`, the contract reauthorizes itself to manipulate the updated ciphertext using `FHE.allowThis`.
## **Key Considerations**
- **Value change behavior:** Each time `TFHE.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.
- &#x20;**Gas consumption:** Using `TFHE.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., `TFHE.allowThis`, `TFHE.allow`) to ensure the updated ciphertexts are authorized for use in future computations or transactions.
- **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.
- &#x20;**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.
---
## **Summary**
- **`TFHE.select`** is a powerful tool for conditional logic on encrypted values.
- **`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.

View File

@@ -4,11 +4,11 @@ This document explains how to enable encrypted computations in your smart contra
## Core configuration setup
To utilize encrypted computations in Solidity contracts, you must configure the **TFHE library** and **Gateway addresses**. The `fhevm` package simplifies this process with prebuilt configuration contracts, allowing you to focus on developing your contracts logic without handling the underlying cryptographic setup.
To utilize encrypted computations in Solidity contracts, you must configure the **FHE library** and **Gateway addresses**. The `fhevm` package simplifies this process with prebuilt configuration contracts, allowing you to focus on developing your contracts logic without handling the underlying cryptographic setup.
## Key components configured automatically
1. **TFHE library**: Sets up encryption parameters and cryptographic keys.
1. **FHE library**: Sets up encryption parameters and cryptographic keys.
2. **Gateway**: Manages secure cryptographic operations, including reencryption and decryption.
3. **Network-specific settings**: Adapts to local testing, testnets (Sepolia for example), or mainnet deployment.
@@ -64,7 +64,7 @@ import { SepoliaZamaGatewayConfig } from "fhevm/config/ZamaGatewayConfig.sol";
**Example: Configuring the gateway with Sepolia settings**
```solidity
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import { SepoliaZamaFHEVMConfig } from "fhevm/config/ZamaFHEVMConfig.sol";
import { SepoliaZamaGatewayConfig } from "fhevm/config/ZamaGatewayConfig.sol";
import "fhevm/gateway/GatewayCaller.sol";
@@ -94,7 +94,7 @@ function isInitialized(T v) internal pure returns (bool)
**Example: Initialization Check for Encrypted Counter**
```solidity
require(TFHE.isInitialized(counter), "Counter not initialized!");
require(FHE.isInitialized(counter), "Counter not initialized!");
```
## Summary

View File

@@ -1,6 +1,6 @@
# fhevm-contracts
This guide explains how to use the [fhevm Contracts standard library](https://github.com/zama-ai/fhevm-contracts/tree/main). This library provides secure, extensible, and pre-tested Solidity templates designed for developing smart contracts on fhevm using the TFHE library.
This guide explains how to use the [fhevm Contracts standard library](https://github.com/zama-ai/fhevm-contracts/tree/main). This library provides secure, extensible, and pre-tested Solidity templates designed for developing smart contracts on fhevm using the FHE library.
## Overview

View File

@@ -94,7 +94,7 @@ Re-encryption enables encrypted data to be securely shared or reused under a dif
#### Client-side implementation
Re-encryption is initiated on the client side via the **Gateway service** using the [`@fhevm/sdk`](https://github.com/zama-ai/fhevmjs/) library. Heres the general workflow:
Re-encryption is initiated on the client side via the **Gateway service** using the [`@fhevm/sdk`](https://github.com/zama-ai/fhevm-js/) library. Heres the general workflow:
1. **Retrieve the ciphertext**:
- The dApp calls a view function (e.g., `balanceOf`) on the smart contract to get the handle of the ciphertext to be re-encrypted.

View File

@@ -24,7 +24,7 @@ Heres an example of how to request decryption in a contract:
```solidity
pragma solidity ^0.8.24;
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import { SepoliaZamaFHEVMConfig } from "fhevm/config/ZamaFHEVMConfig.sol";
import { SepoliaZamaGatewayConfig } from "fhevm/config/ZamaGatewayConfig.sol";
import "fhevm/gateway/GatewayCaller.sol";
@@ -34,8 +34,8 @@ contract TestAsyncDecrypt is SepoliaZamaFHEVMConfig, SepoliaZamaGatewayConfig, G
bool public yBool;
constructor() {
xBool = TFHE.asEbool(true);
TFHE.allowThis(xBool);
xBool = FHE.asEbool(true);
FHE.allowThis(xBool);
}
function requestBool() public {

View File

@@ -108,7 +108,7 @@ For example, see this snippet where we add two `uint256`s during the request cal
```solidity
pragma solidity ^0.8.24;
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
import { SepoliaZamaFHEVMConfig } from "fhevm/config/ZamaFHEVMConfig.sol";
import { SepoliaZamaGatewayConfig } from "fhevm/config/ZamaGatewayConfig.sol";
import "fhevm/gateway/GatewayCaller.sol";
@@ -118,8 +118,8 @@ contract TestAsyncDecrypt is SepoliaZamaFHEVMConfig, SepoliaZamaGatewayConfig, G
uint32 public yUint32;
constructor() {
xUint32 = TFHE.asEuint32(32);
TFHE.allowThis(xUint32);
xUint32 = FHE.asEuint32(32);
FHE.allowThis(xUint32);
}
function requestUint32(uint32 input1, uint32 input2) public {

View File

@@ -28,7 +28,7 @@ Re-encryption is facilitated by the **Gateway** and the **Key Management System
To retrieve the ciphertext that needs to be re-encrypted, you can implement a view function in your smart contract. Below is an example implementation:
```solidity
import "fhevm/lib/TFHE.sol";
import "fhevm/lib/FHE.sol";
contract ConfidentialERC20 {
...

View File

@@ -33,8 +33,8 @@ euint8 internal NO_ERROR;
euint8 internal NOT_ENOUGH_FUNDS;
constructor() {
NO_ERROR = TFHE.asEuint8(0); // Code 0: No error
NOT_ENOUGH_FUNDS = TFHE.asEuint8(1); // Code 1: Insufficient funds
NO_ERROR = FHE.asEuint8(0); // Code 0: No error
NOT_ENOUGH_FUNDS = FHE.asEuint8(1); // Code 1: Insufficient funds
}
// Store the last error for each address
@@ -61,19 +61,19 @@ function setLastError(euint8 error, address addr) private {
*/
function _transfer(address from, address to, euint32 amount) internal {
// Check if the sender has enough balance to transfer
ebool canTransfer = TFHE.le(amount, balances[from]);
ebool canTransfer = FHE.le(amount, balances[from]);
// Log the error state: NO_ERROR or NOT_ENOUGH_FUNDS
setLastError(TFHE.select(canTransfer, NO_ERROR, NOT_ENOUGH_FUNDS), msg.sender);
setLastError(FHE.select(canTransfer, NO_ERROR, NOT_ENOUGH_FUNDS), msg.sender);
// Perform the transfer operation conditionally
balances[to] = TFHE.add(balances[to], TFHE.select(canTransfer, amount, TFHE.asEuint32(0)));
TFHE.allowThis(balances[to]);
TFHE.allow(balances[to], to);
balances[to] = FHE.add(balances[to], FHE.select(canTransfer, amount, FHE.asEuint32(0)));
FHE.allowThis(balances[to]);
FHE.allow(balances[to], to);
balances[from] = TFHE.sub(balances[from], TFHE.select(canTransfer, amount, TFHE.asEuint32(0)));
TFHE.allowThis(balances[from]);
TFHE.allow(balances[from], from);
balances[from] = FHE.sub(balances[from], FHE.select(canTransfer, amount, FHE.asEuint32(0)));
FHE.allowThis(balances[from]);
FHE.allow(balances[from], from);
}
```
@@ -86,7 +86,7 @@ function _transfer(address from, address to, euint32 amount) internal {
- Use the `setLastError` function to log the latest error for a specific address along with the current timestamp.
- Emit the `ErrorChanged` event to notify external systems (e.g., dApps) about the error state change.
3. **Conditional updates**:
- Use the `TFHE.select` function to update balances and log errors based on the transfer condition (`canTransfer`).
- Use the `FHE.select` function to update balances and log errors based on the transfer condition (`canTransfer`).
4. **Frontend integration**:
- The dApp can query `_lastErrors` for a users most recent error and display appropriate feedback, such as "Insufficient funds" or "Transaction successful."

View File

@@ -78,7 +78,7 @@ In this example:
## Validating encrypted inputs
Smart contracts process encrypted inputs by verifying them against the associated zero-knowledge proof. This is done using the `TFHE.asEuintXX`, `TFHE.asEbool`, or `TFHE.asEaddress` functions, which validate the input and convert it into the appropriate encrypted type.
Smart contracts process encrypted inputs by verifying them against the associated zero-knowledge proof. This is done using the `FHE.asEuintXX`, `FHE.asEbool`, or `FHE.asEaddress` functions, which validate the input and convert it into the appropriate encrypted type.
### Example validation that goes along the client-Side implementation
@@ -91,14 +91,14 @@ This example demonstrates a function that performs multiple encrypted operations
bytes calldata inputProof
) public {
// Validate and convert the encrypted inputs
euint64 amount = TFHE.asEuint64(encryptedAmount, inputProof);
ebool toggleFlag = TFHE.asEbool(encryptedToggle, inputProof);
euint64 amount = FHE.asEuint64(encryptedAmount, inputProof);
ebool toggleFlag = FHE.asEbool(encryptedToggle, inputProof);
// Update the user's encrypted balance
balances[msg.sender] = TFHE.add(balances[msg.sender], amount);
balances[msg.sender] = FHE.add(balances[msg.sender], amount);
// Toggle the user's encrypted flag
userFlags[msg.sender] = TFHE.not(toggleFlag);
userFlags[msg.sender] = FHE.not(toggleFlag);
}
// Function to retrieve a user's encrypted balance
@@ -124,7 +124,7 @@ function transfer(
bytes calldata inputProof
) public {
// Verify the provided encrypted amount and convert it into an encrypted uint64
euint64 amount = TFHE.asEuint64(encryptedAmount, inputProof);
euint64 amount = FHE.asEuint64(encryptedAmount, inputProof);
// Function logic here, such as transferring funds
...
@@ -134,7 +134,7 @@ function transfer(
### How validation works
1. **Input verification**:\
The `TFHE.asEuintXX` function ensures that the input is a valid ciphertext with a corresponding ZKPoK.
The `FHE.asEuintXX` function ensures that the input is a valid ciphertext with a corresponding ZKPoK.
2. **Type conversion**:\
The function transforms the `einput` into the appropriate encrypted type (`euintXX`, `ebool`, etc.) for further operations within the contract.

View File

@@ -30,10 +30,10 @@ For more information see [use of encrypted types](types.md).
fhevm provides functions to cast between encrypted types:
- **Casting between encrypted types**: `TFHE.asEbool` converts encrypted integers to encrypted booleans
- **Casting to encrypted types**: `TFHE.asEuintX` converts plaintext values to encrypted types
- **Casting to encrypted addresses**: `TFHE.asEaddress` converts plaintext addresses to encrypted addresses
- **Casting to encrypted bytes**: `TFHE.asEbytesX` converts plaintext bytes to encrypted bytes
- **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
- **Casting to encrypted bytes**: `FHE.asEbytesX` converts plaintext bytes to encrypted bytes
For more information see [use of encrypted types](types.md).
@@ -41,11 +41,11 @@ For more information see [use of encrypted types](types.md).
fhevm enables symbolic execution of encrypted operations, supporting:
- **Arithmetic:** `TFHE.add`, `TFHE.sub`, `TFHE.mul`, `TFHE.min`, `TFHE.max`, `TFHE.neg`, `TFHE.div`, `TFHE.rem`
- **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:** `TFHE.and`, `TFHE.or`, `TFHE.xor`, `TFHE.not`, `TFHE.shl`, `TFHE.shr`, `TFHE.rotl`, `TFHE.rotr`
- **Comparison:** `TFHE.eq`, `TFHE.ne`, `TFHE.lt`, `TFHE.le`, `TFHE.gt`, `TFHE.ge`
- **Advanced:** `TFHE.select` for branching on encrypted conditions, `TFHE.randEuintX` for on-chain randomness.
- **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](operations.md).&#x20;
@@ -57,8 +57,8 @@ For more information on random number generation, see [Generate Random Encrypted
fhevm enforces access control with a blockchain-based Access Control List (ACL):
- **Persistent access**: `TFHE.allow`, `TFHE.allowThis` grants permanent permissions for ciphertexts.
- **Transient access**: `TFHE.allowTransient` provides temporary access for specific transactions.
- **Validation**: `TFHE.isSenderAllowed` ensures that only authorized entities can interact with ciphertexts.
- **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.
For more information see [ACL](acl).

View File

@@ -7,27 +7,27 @@ This document explains how to handle branches, loops or conditions when working
❌ In FHE, it is not possible to break a loop based on an encrypted condition. For example, this would not work:
```solidity
euint8 maxValue = TFHE.asEuint(6); // Could be a value between 0 and 10
euint8 x = TFHE.asEuint(0);
euint8 maxValue = FHE.asEuint(6); // Could be a value between 0 and 10
euint8 x = FHE.asEuint(0);
// some code
while(TFHE.lt(x, maxValue)){
x = TFHE.add(x, 2);
while(FHE.lt(x, maxValue)){
x = FHE.add(x, 2);
}
```
If your code logic requires looping on an encrypted boolean condition, we highly suggest to try to replace it by a finite loop with an appropriate constant maximum number of steps and use `TFHE.select` inside the loop.
If your code logic requires looping on an encrypted boolean condition, we highly suggest to try to replace it by a finite loop with an appropriate constant maximum number of steps and use `FHE.select` inside the loop.
## Suggested approach
✅ For example, the previous code could maybe be replaced by the following snippet:
```solidity
euint8 maxValue = TFHE.asEuint(6); // Could be a value between 0 and 10
euint8 maxValue = FHE.asEuint(6); // Could be a value between 0 and 10
euint8 x;
// some code
for (uint32 i = 0; i < 10; i++) {
euint8 toAdd = TFHE.select(TFHE.lt(x, maxValue), 2, 0);
x = TFHE.add(x, toAdd);
euint8 toAdd = FHE.select(FHE.lt(x, maxValue), 2, 0);
x = FHE.add(x, toAdd);
}
```
@@ -37,7 +37,7 @@ In this snippet, we perform 10 iterations, adding 4 to `x` in each iteration as
### Obfuscate branching
The previous paragraph emphasized that branch logic should rely as much as possible on `TFHE.select` instead of decryptions. It hides effectively which branch has been executed.
The previous paragraph emphasized that branch logic should rely as much as possible on `FHE.select` instead of decryptions. It hides effectively which branch has been executed.
However, this is sometimes not enough. Enhancing the privacy of smart contracts often requires revisiting your application's logic.
@@ -49,22 +49,22 @@ For example, if implementing a simple AMM for two encrypted ERC20 tokens based o
// typically either encryptedAmountAIn or encryptedAmountBIn is an encrypted null value
// ideally, the user already owns some amounts of both tokens and has pre-approved the AMM on both tokens
function swapTokensForTokens(einput encryptedAmountAIn, einput encryptedAmountBIn, bytes calldata inputProof) external {
euint32 encryptedAmountA = TFHE.asEuint32(encryptedAmountAIn, inputProof); // even if amount is null, do a transfer to obfuscate trade direction
euint32 encryptedAmountB = TFHE.asEuint32(encryptedAmountBIn, inputProof); // even if amount is null, do a transfer to obfuscate trade direction
euint32 encryptedAmountA = FHE.asEuint32(encryptedAmountAIn, inputProof); // even if amount is null, do a transfer to obfuscate trade direction
euint32 encryptedAmountB = FHE.asEuint32(encryptedAmountBIn, inputProof); // even if amount is null, do a transfer to obfuscate trade direction
// send tokens from user to AMM contract
TFHE.allowTransient(encryptedAmountA, tokenA);
FHE.allowTransient(encryptedAmountA, tokenA);
IConfidentialERC20(tokenA).transferFrom(msg.sender, address(this), encryptedAmountA);
TFHE.allowTransient(encryptedAmountB, tokenB);
FHE.allowTransient(encryptedAmountB, tokenB);
IConfidentialERC20(tokenB).transferFrom(msg.sender, address(this), encryptedAmountB);
// send tokens from AMM contract to user
// Price of tokenA in tokenB is constant and equal to 1, so we just swap the encrypted amounts here
TFHE.allowTransient(encryptedAmountB, tokenA);
FHE.allowTransient(encryptedAmountB, tokenA);
IConfidentialERC20(tokenA).transfer(msg.sender, encryptedAmountB);
TFHE.allowTransient(encryptedAmountA, tokenB);
FHE.allowTransient(encryptedAmountA, tokenB);
IConfidentialERC20(tokenB).transferFrom(msg.sender, address(this), encryptedAmountA);
}
```
@@ -88,11 +88,11 @@ euint32 x;
euint32[] encArray;
function setXwithEncryptedIndex(einput encryptedIndex, bytes calldata inputProof) public {
euint32 index = TFHE.asEuint32(encryptedIndex, inputProof);
euint32 index = FHE.asEuint32(encryptedIndex, inputProof);
for (uint32 i = 0; i < encArray.length; i++) {
ebool isEqual = TFHE.eq(index, i);
x = TFHE.select(isEqual, encArray[i], x);
ebool isEqual = FHE.eq(index, i);
x = FHE.select(isEqual, encArray[i], x);
}
TFHE.allowThis(x);
FHE.allowThis(x);
}
```

View File

@@ -1,6 +1,6 @@
# Operations on encrypted types
This document outlines the operations supported on encrypted types in the `TFHE` library, enabling arithmetic, bitwise, comparison, and more on Fully Homomorphic Encryption (FHE) ciphertexts.
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
@@ -8,35 +8,35 @@ The following arithmetic operations are supported for encrypted integers (`euint
| Name | Function name | Symbol | Type |
| ---------------------------- | ------------- | ------ | ------ |
| Add | `TFHE.add` | `+` | Binary |
| Subtract | `TFHE.sub` | `-` | Binary |
| Multiply | `TFHE.mul` | `*` | Binary |
| Divide (plaintext divisor) | `TFHE.div` | | Binary |
| Reminder (plaintext divisor) | `TFHE.rem` | | Binary |
| Negation | `TFHE.neg` | `-` | Unary |
| Min | `TFHE.min` | | Binary |
| Max | `TFHE.max` | | Binary |
| 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 (TFHE.div) and remainder (TFHE.rem) operations are currently supported only with plaintext divisors.
Division (FHE.div) and remainder (FHE.rem) operations are currently supported only with plaintext divisors.
{% endhint %}
## Bitwise operations
The TFHE library also supports bitwise operations, including shifts and rotations:
The FHE library also supports bitwise operations, including shifts and rotations:
| Name | Function name | Symbol | Type |
| ------------ | ------------- | ------ | ------ |
| Bitwise AND | `TFHE.and` | `&` | Binary |
| Bitwise OR | `TFHE.or` | `\|` | Binary |
| Bitwise XOR | `TFHE.xor` | `^` | Binary |
| Bitwise NOT | `TFHE.not` | `~` | Unary |
| Shift Right | `TFHE.shr` | | Binary |
| Shift Left | `TFHE.shl` | | Binary |
| Rotate Right | `TFHE.rotr` | | Binary |
| Rotate Left | `TFHE.rotl` | | Binary |
| 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 `TFHE.shr` and `TFHE.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, `TFHE.shr(euint64 x, 70)` is equivalent to `TFHE.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.
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
@@ -44,40 +44,40 @@ Encrypted integers can be compared using the following functions:
| Name | Function name | Symbol | Type |
| --------------------- | ------------- | ------ | ------ |
| Equal | `TFHE.eq` | | Binary |
| Not equal | `TFHE.ne` | | Binary |
| Greater than or equal | `TFHE.ge` | | Binary |
| Greater than | `TFHE.gt` | | Binary |
| Less than or equal | `TFHE.le` | | Binary |
| Less than | `TFHE.lt` | | Binary |
| 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 `TFHE.select` function is a ternary operation that selects one of two encrypted values based on an encrypted condition:
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 | `TFHE.select` | | Ternary |
| 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>TFHE.randEuintX()</code></td><td></td><td>Random</td></tr></tbody></table>
<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></tr></tbody></table>
For more details, refer to the [Random Encrypted Numbers](random.md) document.
## Overload operators
The `TFHE` library supports operator overloading for encrypted integers (e.g., `+`, `-`, `*`, `&`) using the Solidity [`using for`](https://docs.soliditylang.org/en/v0.8.22/contracts.html#using-for) syntax. These overloaded operators currently perform unchecked operations, meaning they do not include overflow checks.
The `FHE` library supports operator overloading for encrypted integers (e.g., `+`, `-`, `*`, `&`) using the Solidity [`using for`](https://docs.soliditylang.org/en/v0.8.22/contracts.html#using-for) syntax. These overloaded operators currently perform unchecked operations, meaning they do not include overflow checks.
**Example**\
Overloaded operators make code more concise:
```solidity
euint64 a = TFHE.asEuint64(42);
euint64 b = TFHE.asEuint64(58);
euint64 sum = a + b; // Calls TFHE.add under the hood
euint64 a = FHE.asEuint64(42);
euint64 b = FHE.asEuint64(58);
euint64 sum = a + b; // Calls FHE.add under the hood
```
## Best Practices
@@ -92,28 +92,28 @@ Choose the smallest encrypted type that can accommodate your data to optimize ga
```solidity
// Bad: Using euint256 for small numbers wastes gas
euint64 age = TFHE.euint256(25); // age will never exceed 255
euint64 percentage = TFHE.euint256(75); // percentage is 0-100
euint64 age = FHE.euint256(25); // age will never exceed 255
euint64 percentage = FHE.euint256(75); // percentage is 0-100
```
✅ Instead, use the smallest appropriate type:
```solidity
// Good: Using appropriate sized types
euint8 age = TFHE.asEuint8(25); // age fits in 8 bits
euint8 percentage = TFHE.asEuint8(75); // percentage fits in 8 bits
euint8 age = FHE.asEuint8(25); // age fits in 8 bits
euint8 percentage = FHE.asEuint8(75); // percentage fits in 8 bits
```
### Use scalar operands when possible to save gas
Some TFHE operators exist in two versions : one where all operands are ciphertexts handles, and another where one of the operands is an unencrypted scalar. Whenever possible, use the scalar operand version, as this will save a lot of gas.
Some FHE operators exist in two versions: one where all operands are ciphertexts handles, and another where one of the operands is an unencrypted scalar. Whenever possible, use the scalar operand version, as this will save a lot of gas.
❌ For example, this snippet cost way more in gas:
```solidity
euint32 x;
...
x = TFHE.add(x,TFHE.asEuint(42));
x = FHE.add(x,FHE.asEuint(42));
```
✅ Than this one:
@@ -121,39 +121,39 @@ x = TFHE.add(x,TFHE.asEuint(42));
```solidity
euint32 x;
// ...
x = TFHE.add(x,42);
x = FHE.add(x,42);
```
Despite both leading to the same encrypted result!
### Beware of overflows of TFHE arithmetic operators
### Beware of overflows of FHE arithmetic operators
TFHE arithmetic operators can overflow. Do not forget to take into account such a possibility when implementing fhevm smart contracts.
FHE arithmetic operators can overflow. Do not forget to take into account such a possibility when implementing fhevm smart contracts.
❌ For example, if you wanted to create a mint function for an encrypted ERC20 token with an encrypted `totalSupply` state variable, this code is vulnerable to overflows:
```solidity
function mint(einput encryptedAmount, bytes calldata inputProof) public {
euint32 mintedAmount = TFHE.asEuint32(encryptedAmount, inputProof);
totalSupply = TFHE.add(totalSupply, mintedAmount);
balances[msg.sender] = TFHE.add(balances[msg.sender], mintedAmount);
TFHE.allowThis(balances[msg.sender]);
TFHE.allow(balances[msg.sender], msg.sender);
euint32 mintedAmount = FHE.asEuint32(encryptedAmount, inputProof);
totalSupply = FHE.add(totalSupply, mintedAmount);
balances[msg.sender] = FHE.add(balances[msg.sender], mintedAmount);
FHE.allowThis(balances[msg.sender]);
FHE.allow(balances[msg.sender], msg.sender);
}
```
✅ But you can fix this issue by using `TFHE.select` to cancel the mint in case of an overflow:
✅ But you can fix this issue by using `FHE.select` to cancel the mint in case of an overflow:
```solidity
function mint(einput encryptedAmount, bytes calldata inputProof) public {
euint32 mintedAmount = TFHE.asEuint32(encryptedAmount, inputProof);
euint32 tempTotalSupply = TFHE.add(totalSupply, mintedAmount);
ebool isOverflow = TFHE.lt(tempTotalSupply, totalSupply);
totalSupply = TFHE.select(isOverflow, totalSupply, tempTotalSupply);
euint32 tempBalanceOf = TFHE.add(balances[msg.sender], mintedAmount);
balances[msg.sender] = TFHE.select(isOverflow, balances[msg.sender], tempBalanceOf);
TFHE.allowThis(balances[msg.sender]);
TFHE.allow(balances[msg.sender], msg.sender);
euint32 mintedAmount = FHE.asEuint32(encryptedAmount, inputProof);
euint32 tempTotalSupply = FHE.add(totalSupply, mintedAmount);
ebool isOverflow = FHE.lt(tempTotalSupply, totalSupply);
totalSupply = FHE.select(isOverflow, totalSupply, tempTotalSupply);
euint32 tempBalanceOf = FHE.add(balances[msg.sender], mintedAmount);
balances[msg.sender] = FHE.select(isOverflow, balances[msg.sender], tempBalanceOf);
FHE.allowThis(balances[msg.sender]);
FHE.allow(balances[msg.sender], msg.sender);
}
```

View File

@@ -1,6 +1,6 @@
# Generate random numbers
This document explains how to generate cryptographically secure random encrypted numbers fully on-chain using the `TFHE` library in fhevm. These numbers are encrypted and remain confidential, enabling privacy-preserving smart contract logic.
This document explains how to generate cryptographically secure random encrypted numbers fully on-chain using the `FHE` library in fhevm. These numbers are encrypted and remain confidential, enabling privacy-preserving smart contract logic.
## **Key notes on random number generation**
@@ -13,24 +13,24 @@ Random number generation must be performed during transactions, as it requires t
## **Basic usage**
The `TFHE` library allows you to generate random encrypted numbers of various bit sizes. Below is a list of supported types and their usage:
The `FHE` library allows you to generate random encrypted numbers of various bit sizes. Below is a list of supported types and their usage:
```solidity
// Generate random encrypted numbers
ebool rb = TFHE.randEbool(); // Random encrypted boolean
euint8 r8 = TFHE.randEuint8(); // Random 8-bit number
euint16 r16 = TFHE.randEuint16(); // Random 16-bit number
euint32 r32 = TFHE.randEuint32(); // Random 32-bit number
euint64 r64 = TFHE.randEuint64(); // Random 64-bit number
euint128 r128 = TFHE.randEuint128(); // Random 128-bit number
euint256 r256 = TFHE.randEuint256(); // Random 256-bit number
ebool rb = FHE.randEbool(); // Random encrypted boolean
euint8 r8 = FHE.randEuint8(); // Random 8-bit number
euint16 r16 = FHE.randEuint16(); // Random 16-bit number
euint32 r32 = FHE.randEuint32(); // Random 32-bit number
euint64 r64 = FHE.randEuint64(); // Random 64-bit number
euint128 r128 = FHE.randEuint128(); // Random 128-bit number
euint256 r256 = FHE.randEuint256(); // Random 256-bit number
```
### **Example: Random Boolean**
```solidity
function randomBoolean() public returns (ebool) {
return TFHE.randEbool();
return FHE.randEbool();
}
```
@@ -40,16 +40,16 @@ To generate random numbers within a specific range, you can specify an **upper b
```solidity
// Generate random numbers with upper bounds
euint8 r8 = TFHE.randEuint8(100); // Random number between 0-99
euint16 r16 = TFHE.randEuint16(1000); // Random number between 0-999
euint32 r32 = TFHE.randEuint32(1000000); // Random number between 0-999999
euint8 r8 = FHE.randEuint8(100); // Random number between 0-99
euint16 r16 = FHE.randEuint16(1000); // Random number between 0-999
euint32 r32 = FHE.randEuint32(1000000); // Random number between 0-999999
```
### **Example: Random bumber with upper bound**
```solidity
function randomBoundedNumber(uint16 upperBound) public returns (euint16) {
return TFHE.randEuint16(upperBound);
return FHE.randEuint16(upperBound);
}
```
@@ -59,16 +59,16 @@ To generate larger random values, you can use encrypted bytes. These are ideal f
```solidity
// Generate random encrypted bytes
ebytes64 rb64 = TFHE.randEbytes64(); // 64 bytes (512 bits)
ebytes128 rb128 = TFHE.randEbytes128(); // 128 bytes (1024 bits)
ebytes256 rb256 = TFHE.randEbytes256(); // 256 bytes (2048 bits)
ebytes64 rb64 = FHE.randEbytes64(); // 64 bytes (512 bits)
ebytes128 rb128 = FHE.randEbytes128(); // 128 bytes (1024 bits)
ebytes256 rb256 = FHE.randEbytes256(); // 256 bytes (2048 bits)
```
### **Example: Random Bytes**
```solidity
function randomBytes256() public returns (ebytes256) {
return TFHE.randEbytes256();
return FHE.randEbytes256();
}
```

View File

@@ -1,26 +1,26 @@
# Supported types
This document introduces the encrypted integer types provided by the `TFHE` library in fhevm and explains their usage, including casting, state variable declarations, and type-specific considerations.
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 `TFHE` 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.
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 Soliditys 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 `TFHE` library will support encrypted integers with overflow checking, but with the trade-off of exposing limited information about the operands.
- 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 `TFHE` library. These will allow reversible arithmetic operations but may reveal some information about the input values.
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 `TFHE` library currently supports the following encrypted types:
The `FHE` library currently supports the following encrypted types:
| Type | Supported |
| ----------- | --------------------- |

View File

@@ -4,4 +4,4 @@ This guide explains how to use Foundry with fhevm for developing smart contracts
While a Foundry template is currently in development, we strongly recommend using the [Hardhat template](https://github.com/zama-ai/fhevm-hardhat-template) for now, as it provides a fully tested and supported development environment for fhevm smart contracts.
However, you could still use Foundry with the mocked version of the fhevm, but please be aware that this approach is **NOT** recommended, since the mocked version is not fully equivalent to the real fhevm node's implementation (see warning in hardhat). In order to do this, you will need to rename your `TFHE.sol` imports from `fhevm/lib/TFHE.sol` to `fhevm/mocks/TFHE.sol` in your solidity source files.
However, you could still use Foundry with the mocked version of the fhevm, but please be aware that this approach is **NOT** recommended, since the mocked version is not fully equivalent to the real fhevm node's implementation (see warning in hardhat). In order to do this, you will need to rename your `FHE.sol` imports from `fhevm/lib/FHE.sol` to `fhevm/mocks/FHE.sol` in your solidity source files.

View File

@@ -2,7 +2,7 @@
## Solidity smart contracts templates - `fhevm-contracts`
The [fhevm-contracts repository](https://github.com/zama-ai/fhevm-contracts) provides a comprehensive collection of secure, pre-tested Solidity templates optimized for fhevm development. These templates leverage the TFHE library to enable encrypted computations while maintaining security and extensibility.
The [fhevm-contracts repository](https://github.com/zama-ai/fhevm-contracts) provides a comprehensive collection of secure, pre-tested Solidity templates optimized for fhevm development. These templates leverage the FHE library to enable encrypted computations while maintaining security and extensibility.
The library includes templates for common use cases like tokens and governance, allowing developers to quickly build confidential smart contracts with battle-tested components. For detailed implementation guidance and best practices, refer to the [contracts standard library guide](../smart_contracts/contracts.md).