bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 42쪽
guide**](/protocol/solidity-guides/v0.10/docs/sdk-guides/initialization) to learn how to configure the Relayer SDK for your project.
🟨 Go to [**Input registration**](/protocol/solidity-guides/v0.10/docs/sdk-guides/input) to see how to register new encrypted inputs for your smart contracts.
🟨 Go to [**User decryption**](/protocol/solidity-guides/v0.10/docs/sdk-guides/user-decryption) to enable users to decrypt data with their own keys, once permissions have been granted via Access Control List(ACL).
🟨 Go to [**Public decryption**](/protocol/solidity-guides/v0.10/docs/sdk-guides/public-decryption) to learn how to decrypt outputs that are publicly accessible, either via HTTP or onchain Oracle.
🟨 Go to [**Solidity ACL Guide**](https://docs.zama.ai/protocol/solidity-guides/smart-contract/acl) for more detailed instructions about access control.
## Help center
Ask technical questions and discuss with the community.
* [Community forum](https://community.zama.ai/c/zama-protocol/15)
* [Discord channel](https://discord.com/invite/zama)
# User decryption
This document explains how to perform user decryption. User decryption is required when you want a user to access their private data without it being exposed to the blockchain.
User decryption in FHEVM enables the secure sharing or reuse of encrypted data under a new public key without exposing the plaintext.
This feature is essential for scenarios where encrypted data must be transferred between contracts, dApps, or users while maintaining its confidentiality.
## When to use user decryption
User decryption is particularly useful for **allowing individual users to securely access and decrypt their private data**, such as balances or counters, while maintaining data confidentiality.
## Overview
The user decryption process involves retrieving ciphertext from the blockchain and performing user-decryption on the client-side. In other words we take the data that has been encrypted by the KMS, decrypt it and encrypt it with the user's private key, so only he can access the information.
This ensures that the data remains encrypted under the blockchain’s FHE key but can be securely shared with a user by re-encrypting it under the user’s NaCl public key.
User decryption is facilitated by the **Relayer** and the **Key Management System (KMS)**. The workflow consists of the following:
1. Retrieving the ciphertext from the blockchain using a contract’s view function.
2. Re-encrypting the ciphertext client-side with the user’s public key, ensuring only the user can decrypt it.
## Step 1: retrieve the ciphertext
To retrieve the ciphertext that needs to be decrypted, you can implement a view function in your smart contract. Below is an example implementation:
```solidity
import "@fhevm/solidity/lib/FHE.sol";
contract ConfidentialERC20 {
...
function balanceOf(account address) public view returns (euint64) {
return balances[msg.sender];
}
...
}
```
Here, `balanceOf` allows retrieval of the user’s encrypted balance handle stored on the blockchain. Doing this will return the ciphertext handle, an identifier for the underlying ciphertext.
{% hint style="warning" %}
For the user to be able to user decrypt (also called re-encrypt) the ciphertext value the access control (ACL) needs to be set properly using the `FHE.allow(ciphertext, address)` function in the solidity contract holding the ciphertext. For more details on the topic please refer to [the ACL documentation](/protocol/solidity-guides/v0.10/docs/solidity-guides/acl).
{% endhint %}
## Step 2: decrypt the ciphertext
Using that ciphertext handle user decryption is performed client-side using the `@zama-fhe/relayer-sdk` library. The user needs to have created an instance object prior to that (for more context see [the relayer-sdk setup page](/protocol/solidity-guides/v0.10/docs/sdk-guides/initialization)).
```ts
// instance: [`FhevmInstance`] from `zama-fhe/relayer-sdk`
// signer: [`Signer`] from ethers (could a [`Wallet`])
// ciphertextHandle: [`string`]
// contractAddress: [`string`]
const keypair = instance.generateKeypair();
const handleContractPairs = [
{
handle: ciphertextHandle,
contractAddress: contractAddress,
},
];
const startTimeStamp = Math.floor(Date.now() / 1000).toString();
const durationDays = "10"; // String for consistency
const contractAddresses = [contractAddress];
const eip712 = instance.createEIP712(keypair.publicKey, contractAddresses, startTimeStamp, durationDays);
const signature = await signer.signTypedData(
eip712.domain,
{
UserDecryptRequestVerification: eip712.types.UserDecryptRequestVerification,
},
eip712.message,
);
const result = await instance.userDecrypt(
handleContractPairs,
keypair.privateKey,
keypair.publicKey,
signature.replace("0x", ""),
contractAddresses,
signer.address,
startTimeStamp,
durationDays,
);
const decryptedValue = result[ciphertextHandle];
```
# Build a web application
This document guides you through building a web application using the `@zama-fhe/relayer-sdk` library.
## Using directly the library
### Step 1: Setup the library
`@zama-fhe/relayer-sdk` consists of multiple files, including WASM files and WebWorkers, which can make packaging these components correctly in your setup cumbersome. To simplify this process, especially if you're developing a dApp with server-side rendering (SSR), we recommend using our CDN.
#### Using UMD CDN
Include this line at the top of your project.
```html
<script src="https://cdn.zama.ai/relayer-sdk-js/0.2.0/relayer-sdk-js.umd.cjs" type="text/javascript"></script>
```
In your project, you can use the bundle import if you install `@zama-fhe/relayer-sdk` package:
```javascript
import { initSDK, createInstance, SepoliaConfig } from "@zama-fhe/relayer-sdk/bundle";
```
#### Using ESM CDN
If you prefer You can also use the `@zama-fhe/relayer-sdk` as a ES module:
```html
<script type="module">
import { initSDK, createInstance, SepoliaConfig } from "https://cdn.zama.ai/relayer-sdk-js/0.2.0/relayer-sdk-js.js";
await initSDK();
const config = { ...SepoliaConfig, network: window.ethereum };
config.network = window.ethereum;
const instance = await createInstance(config);
</script>
```
#### Using npm package
Install the `@zama-fhe/relayer-sdk` library to your project:
```bash
# Using npm
npm install @zama-fhe/relayer-sdk
# Using Yarn
yarn add @zama-fhe/relayer-sdk
# Using pnpm
pnpm add @zama-fhe/relayer-sdk
```
`@zama-fhe/relayer-sdk` uses ESM format. You need to set the [type to "module" in your package.json](https://nodejs.org/api/packages.html#type). If your node project use `"type": "commonjs"` or no type, you can force the loading of the web version by using `import { createInstance } from '@zama-fhe/relayer-sdk/web';`
```javascript
import { initSDK, createInstance, SepoliaConfig } from "@zama-fhe/relayer-sdk";
```
### Step 2: Initialize your project
To use the library in your project, you need to load the WASM of [TFHE](https://www.npmjs.com/package/tfhe) first with `initSDK`.
```javascript
import { initSDK } from "@zama-fhe/relayer-sdk/bundle";
const init = async () => {
await initSDK(); // Load needed WASM
};
```
### Step 3: Create an instance
Once the WASM is loaded, you can now create an instance.
```javascript
import { initSDK, createInstance, SepoliaConfig } from "@zama-fhe/relayer-sdk/bundle";
const init = async () => {
await initSDK(); // Load FHE
const config = { ...SepoliaConfig, network: window.ethereum };
return createInstance(config);
};
init().then((instance) => {
console.log(instance);
});
```
You can now use your instance to [encrypt parameters](/protocol/solidity-guides/v0.10/docs/sdk-guides/input), perform [user decryptions](/protocol/solidity-guides/v0.10/docs/sdk-guides/user-decryption) or [public decryptions](/protocol/solidity-guides/v0.10/docs/sdk-guides/public-decryption).
# Common webpack errors
This document provides solutions for common Webpack errors encountered during the development process. Follow the steps below to resolve each issue.
## Can't resolve 'tfhe\_bg.wasm'
**Error message:** `Module not found: Error: Can't resolve 'tfhe_bg.wasm'`
**Cause:** In the codebase, there is a `new URL('tfhe_bg.wasm')` which triggers a resolve by Webpack.
**Possible solutions:** You can add a fallback for this file by adding a resolve configuration in your `webpack.config.js`:
```javascript
resolve: {
fallback: {
'tfhe_bg.wasm': require.resolve('tfhe/tfhe_bg.wasm'),
},
},
```
## Buffer not defined
**Error message:** `ReferenceError: Buffer is not defined`
**Cause:** This error occurs when the Node.js `Buffer` object is used in a browser environment where it is not natively available.
**Possible solutions:** To resolve this issue, you need to provide browser-compatible fallbacks for Node.js core modules. Install the necessary browserified npm packages and configure Webpack to use these fallbacks.
```javascript
resolve: {
fallback: {
buffer: require.resolve('buffer/'),
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream-browserify'),
path: require.resolve('path-browserify'),
},
},
```
## Issue with importing ESM version
**Error message:** Issues with importing ESM version
**Cause:** With a bundler such as Webpack or Rollup, imports will be replaced with the version mentioned in the `"browser"` field of the `package.json`. This can cause issues with typing.
**Possible solutions:**
* 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
**Error message:** Issues with bundling the library, especially with SSR frameworks.
**Cause:** The library may not bundle correctly with certain frameworks, leading to errors during the build or runtime process.
**Possible solutions:** Use the [prebundled version available](/protocol/solidity-guides/v0.10/docs/sdk-guides/webapp) with `@zama-fhe/relayer-sdk/bundle`. Embed the library with a `<script>` tag and initialize it as shown below:
```javascript
const start = async () => {
await window.fhevm.initSDK(); // load wasm needed
const config = { ...SepoliaConfig, network: window.ethereum };
config.network = window.ethereum;
const instance = window.fhevm.createInstance(config).then((instance) => {
console.log(instance);
});
};
```
# Overview
**Welcome to Solidity Guides!**
This section will guide you through writing confidential smart contracts in Solidity using the FHEVM library. With Fully Homomorphic Encryption(FHE), your contracts can operate directly on encrypted data without ever decrypting it onchain.
## Where to go next
If you’re new to the Zama Protocol, start with the [Litepaper](https://docs.zama.ai/protocol/zama-protocol-litepaper) or the [Protocol Overview](https://docs.zama.ai/protocol) to understand the foundations.
Otherwise:
🟨 Go to [**What is FHEVM**](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/overview) to learn about the core concepts and features.
🟨 Go to [**Quick Start Tutorial**](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial) to build and test your first confidential smart contract.
🟨 Go to [**Smart Contract Guides**](/protocol/solidity-guides/v0.10/docs/solidity-guides/configure) for details on encrypted types, supported operations, inputs, ACL, and decryption flows.
🟨 Go to [**Development Guides**](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat) to set up your local environment with Hardhat or Foundry and deploy FHEVM contracts.
🟨 Go to [**Migration Guide**](/protocol/solidity-guides/v0.10/docs/solidity-guides/migration) if you're upgrading from a previous version to v0.7.
## Help center
Ask technical questions and discuss with the community.
* [Community forum](https://community.zama.ai/c/fhevm/15)
* [Discord channel](https://discord.com/invite/zama)
# Table of contents
* [Overview](/protocol/solidity-guides/v0.10/docs/solidity-guides)
## Getting Started
* [What is FHEVM Solidity](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/overview)
* [Set up Hardhat](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/setup)
* [Quick start tutorial](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial)
* [1. Set up Hardhat](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/setup)
* [2. Write a simple contract](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/write_a_simple_contract)
* [3. Turn it into FHEVM](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/turn_it_into_fhevm)
* [4. Test the FHEVM contract](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/test_the_fhevm_contract)
## Smart Contract
* [Configuration](/protocol/solidity-guides/v0.10/docs/solidity-guides/configure)
* [Contract addresses](/protocol/solidity-guides/v0.10/docs/solidity-guides/contract_addresses)
* [Supported types](/protocol/solidity-guides/v0.10/docs/solidity-guides/types)
* [Operations on encrypted types](/protocol/solidity-guides/v0.10/docs/solidity-guides/operations)
* [Casting and trivial encryption](/protocol/solidity-guides/v0.10/docs/solidity-guides/operations/casting)
* [Generate random numbers](/protocol/solidity-guides/v0.10/docs/solidity-guides/operations/random)
* [Encrypted inputs](/protocol/solidity-guides/v0.10/docs/solidity-guides/inputs)
* [Access Control List](/protocol/solidity-guides/v0.10/docs/solidity-guides/acl)
* [ACL examples](/protocol/solidity-guides/v0.10/docs/solidity-guides/acl/acl_examples)
* [Reorgs handling](/protocol/solidity-guides/v0.10/docs/solidity-guides/acl/reorgs_handling)
* [Logics](https://github.com/zama-ai/fhevm/blob/release/0.10.x/docs/solidity-guides/README%20\(1\).md)
* [Branching](/protocol/solidity-guides/v0.10/docs/solidity-guides/logics/conditions)
* [Dealing with branches and conditions](/protocol/solidity-guides/v0.10/docs/solidity-guides/logics/loop)
* [Error handling](/protocol/solidity-guides/v0.10/docs/solidity-guides/logics/error_handling)
* [Decryption](/protocol/solidity-guides/v0.10/docs/solidity-guides/decryption/oracle)
## Development Guide
* [Hardhat plugin](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat)
* [Setup Hardhat](/protocol/solidity-guides/v0.10/docs/solidity-guides/getting-started/quick-start-tutorial/setup)
* [Write FHEVM tests in Hardhat](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat/write_test)
* [Deploy contracts and run tests](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat/run_test)
* [Write FHEVM-enabled Hardhat Tasks](/protocol/solidity-guides/v0.10/docs/solidity-guides/hardhat/write_task)
* [Foundry](/protocol/solidity-guides/v0.10/docs/solidity-guides/foundry)
* [HCU](/protocol/solidity-guides/v0.10/docs/solidity-guides/hcu)
* [Migrate to v0.9](/protocol/solidity-guides/v0.10/docs/solidity-guides/migration)
* [How to Transform Your Smart Contract into a FHEVM Smart Contract?](/protocol/solidity-guides/v0.10/docs/solidity-guides/transform_smart_contract_with_fhevm)
# Configuration
This document explains how to enable encrypted computations in your smart contract by setting up the `fhevm` environment. Learn how to integrate essential libraries, configure encryption, and add secure computation logic to your contracts.
## Core configuration setup
To utilize encrypted computations in Solidity contracts, you must configure the **FHE library** and **Oracle addresses**. The `fhevm` package simplifies this process with prebuilt configuration contracts, allowing you to focus on developing your contract’s logic without handling the underlying cryptographic setup.
This library and its associated contracts provide a standardized way to configure and interact with Zama's FHEVM (Fully Homomorphic Encryption Virtual Machine) infrastructure on different Ethereum networks. It supplies the necessary contract addresses for Zama's FHEVM components (`ACL`, `FHEVMExecutor`, `KMSVerifier`, `InputVerifier`) and the decryption oracle, enabling seamless integration for Solidity contracts that require FHEVM support.
## Key components configured automatically
1. **FHE library**: Sets up encryption parameters and cryptographic keys.
2. **Oracle**: Manages secure cryptographic operations such as public decryption.
3. **Network-specific settings**: Adapts to local testing, testnets (Sepolia for example), or mainnet deployment.
By inheriting these configuration contracts, you ensure seamless initialization and functionality across environments.
## ZamaConfig.sol
The `ZamaConfig` library exposes functions to retrieve FHEVM configuration structs and oracle addresses for supported networks (currently only the Sepolia testnet).
Under the hood, this library encapsulates the network-specific addresses of Zama's FHEVM infrastructure into a single struct (`FHEVMConfigStruct`).
## ZamaEthereumConfig
The `ZamaEthereumConfig` contract is designed to be inherited by a user contract. The constructor automatically sets up the FHEVM coprocessor and decryption oracle using the configuration provided by the library for the respective network. When a contract inherits from `ZamaEthereumConfig`, the constructor calls `FHE.setCoprocessor` with the appropriate addresses. This ensures that the inheriting contract is automatically wired to the correct FHEVM contracts and oracle for the target network, abstracting away manual address management and reducing the risk of misconfiguration.
**Example**
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
contract MyERC20 is ZamaEthereumConfig {
constructor() {
// Additional initialization logic if needed
}
}
```
## Using `isInitialized`
The `isInitialized` utility function checks whether an encrypted variable has been properly initialized, preventing unexpected behavior due to uninitialized values.
**Function signature**
```solidity
function isInitialized(T v) internal pure returns (bool)
```
**Purpose**
* Ensures encrypted variables are initialized before use.
* Prevents potential logic errors in contract execution.
**Example: Initialization Check for Encrypted Counter**
```solidity
require(FHE.isInitialized(counter), "Counter not initialized!");
```
## Summary
By leveraging prebuilt a configuration contract like `ZamaEthereumConfig` in `ZamaConfig.sol`, you can efficiently set up your smart contract for encrypted computations. These tools abstract the complexity of cryptographic initialization, allowing you to focus on building secure, confidential smart contracts.
# Table of all addresses
These are Sepolia addresses.
| Contract/Service | Address/Value |
| ---------------------------- | ------------------------------------------ |
| FHEVM\_EXECUTOR\_CONTRACT | 0x92C920834Ec8941d2C77D188936E1f7A6f49c127 |
| ACL\_CONTRACT | 0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D |
| HCU\_LIMIT\_CONTRACT | 0xa10998783c8CF88D886Bc30307e631D6686F0A22 |
| KMS\_VERIFIER\_CONTRACT | 0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A |
| INPUT\_VERIFIER\_CONTRACT | 0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0 |
| DECRYPTION\_ADDRESS | 0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478 |
| INPUT\_VERIFICATION\_ADDRESS | 0x483b9dE06E4E4C7D35CCf5837A1668487406D955 |
| RELAYER\_URL | `https://relayer.testnet.zama.org` |
| GATEWAY\_CHAIN\_ID | 10901 |
# Debugging with debug.decrypt\[XX]
This guide explains how to use the `debug.decrypt[XX]` functions for debugging encrypted data in mocked environments during development with FHEVM.
{% hint style="warning" %}
The `debug.decrypt프로젝트로 돌아가기