bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 37쪽
ng-using-homomorphic-encryption) - October 2023
* [On-chain Blind Auctions Using Homomorphic Encryption and the FHEVM](https://www.zama.ai/post/on-chain-blind-auctions-using-homomorphic-encryption) - July 2023
* [Confidential ERC-20 Tokens Using Homomorphic Encryption and the FHEVM](https://www.zama.ai/post/confidential-erc-20-tokens-using-homomorphic-encryption) - June 2023
* [Using asynchronous decryption in Solidity contracts with FHEVM](https://www.zama.ai/post/video-tutorial-using-asynchronous-decryption-in-solidity-contracts-with-FHEVM) - April 2024
* [Accelerate your code testing and get code coverage using FHEVM mocks](https://www.zama.ai/post/video-tutorial-accelerate-your-code-testing-and-get-code-coverage-using-fhevm-mocks) - January 2024
* [Use the CMUX operator on fhevm](https://www.youtube.com/watch?v=7icM0EOSvU0) - October 2023
* [\[Video tutorial\] How to Write Confidential Smart Contracts Using fhevm](https://www.zama.ai/post/video-tutorial-how-to-write-confidential-smart-contracts-using-zamas-fhevm) - October 2023
* [Workshop during ETHcc: Homomorphic Encryption in the EVM](https://www.youtube.com/watch?v=eivfVykPP8U) - July 2023
# openzeppelin
This section contains comprehensive guides and examples for using [OpenZeppelin's confidential smart contracts library](https://github.com/OpenZeppelin/openzeppelin-confidential-contracts) with FHEVM. OpenZeppelin's confidential contracts library provides a secure, audited foundation for building privacy-preserving applications on fully homomorphic encryption (FHE) enabled blockchains.
The library includes implementations of popular standards like ERC20, ERC721, and ERC1155, adapted for confidential computing with FHEVM, ensuring your applications maintain privacy while leveraging battle-tested security patterns.
### Getting Started
This guide will help you set up a development environment for working with OpenZeppelin's confidential contracts and FHEVM.
#### Prerequisites
Before you begin, ensure you have the following installed:
* **Node.js** >= 20
* **Hardhat** ^2.24
* **Access to an FHEVM-enabled network** and the Zama gateway/relayer
#### Project Setup
1. **Clone the FHEVM Hardhat template repository:**
```bash
git clone https://github.com/zama-ai/fhevm-hardhat-template conf-token
cd conf-token
```
2. **Install project dependencies:**
```bash
npm ci
```
3. **Install OpenZeppelin's confidential contracts library:**
```bash
npm i @openzeppelin/confidential-contracts
```
4. **Compile the contracts:**
```bash
npm run compile
```
5. **Run the test suite:**
```bash
npm test
```
### Available Guides
Explore the following guides to learn how to implement confidential contracts using OpenZeppelin's library:
* [**ERC7984 Standard**](/protocol/solidity-guides/v0.10/docs/examples/openzeppelin/erc7984) - Learn about the ERC7984 standard for confidential tokens
* [**ERC7984 Tutorial**](/protocol/solidity-guides/v0.10/docs/examples/openzeppelin/erc7984-tutorial) - Step-by-step tutorial for implementing ERC7984 tokens
* [**ERC7984 to ERC20 Wrapper**](/protocol/solidity-guides/v0.10/docs/examples/openzeppelin/erc7984erc20wrappermock) - Convert between confidential and public token standards
* [**Swap ERC7984 to ERC20**](/protocol/solidity-guides/v0.10/docs/examples/openzeppelin/swaperc7984toerc20) - Implement cross-standard token swapping
* [**Swap ERC7984 to ERC7984**](/protocol/solidity-guides/v0.10/docs/examples/openzeppelin/swaperc7984toerc7984) - Confidential token-to-token swapping
* [**Vesting Wallet**](/protocol/solidity-guides/v0.10/docs/examples/openzeppelin/vesting-wallet) - Implement confidential token vesting mechanisms
# ERC7984ERC20WrapperMock
This example demonstrates how to wrap between the ERC20 token into a ERC7984 token using OpenZeppelin's smart contract library powered by ZAMA's FHEVM.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="ERC7984ERC20WrapperExample.sol" %}
{% endtab %}
{% tab %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.27;
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {ERC7984ERC20Wrapper, ERC7984} from "@openzeppelin/confidential-contracts/token/ERC7984/extensions/ERC7984ERC20Wrapper.sol";
contract ERC7984ERC20WrapperExample is ERC7984ERC20Wrapper, ZamaEthereumConfig {
constructor(
IERC20 token,
string memory name,
string memory symbol,
string memory uri
) ERC7984ERC20Wrapper(token) ERC7984(name, symbol, uri) {}
}
```
{% endtab %}
{% endtabs %}
# erc7984-tutorial
This tutorial explains how to create a confidential fungible token using Fully Homomorphic Encryption (FHE) and the OpenZeppelin smart contract library. By following this guide, you will learn how to build a token where balances and transactions remain encrypted while maintaining full functionality.
### Why FHE for confidential tokens?
Confidential tokens make sense in many real-world scenarios:
* **Privacy**: Users can transact without revealing their exact balances or transaction amounts
* **Regulatory Compliance**: Maintains privacy while allowing for selective disclosure when needed
* **Business Intelligence**: Companies can keep their token holdings private from competitors
* **Personal Privacy**: Individuals can participate in DeFi without exposing their financial position
* **Audit Trail**: All transactions are still recorded on-chain, just in encrypted form
FHE enables these benefits by allowing computations on encrypted data without decryption, ensuring privacy while maintaining the security and transparency of blockchain.
## Project Setup
Before starting this tutorial, ensure you have:
1. Installed the FHEVM hardhat template
2. Set up the OpenZeppelin confidential contracts library
For help with these steps, refer to the following tutorial:
* [Setting up OpenZeppelin confidential contracts](https://github.com/zama-ai/fhevm/blob/release/0.10.x/docs/examples/openzeppelin/openzeppelin/README.md)
### Understanding the architecture
Our confidential token will inherit from several key contracts:
1. **`ERC7984`** - OpenZeppelin's base for confidential tokens
2. **`Ownable2Step`** - Access control for minting and administrative functions
3. **`ZamaEthereumConfig`** - FHE configuration for the Ethereum mainnet or Ethereum Sepolia testnet networks
### The base smart contract
Let's create our confidential token contract in `contracts/ERC7984Example.sol`. This contract will demonstrate the core functionality of ERC7984 tokens.
A few key points about this implementation:
* The contract mints an initial supply with a clear (non-encrypted) amount during deployment
* The initial mint is done once during construction, establishing the token's total supply
* All subsequent transfers will be fully encrypted, preserving privacy
* The contract inherits from ERC7984 for confidential token functionality and Ownable2Step for secure access control
While this example uses a clear initial mint for simplicity, in production you may want to consider:
* Using encrypted minting for complete privacy from genesis
* Implementing a more sophisticated minting schedule
* Overriding some privacy assumptions
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {FHE, externalEuint64, euint64} from "@fhevm/solidity/lib/FHE.sol";
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";
import {ERC7984} from "@openzeppelin/confidential-contracts/token/ERC7984.sol";
contract ERC7984Example is ZamaEthereumConfig, ERC7984, Ownable2Step {
constructor(
address owner,
uint64 amount,
string memory name_,
string memory symbol_,
string memory tokenURI_
) ERC7984(name_, symbol_, tokenURI_) Ownable(owner) {
euint64 encryptedAmount = FHE.asEuint64(amount);
_mint(owner, encryptedAmount);
}
}
```
### Test workflow
Now let's test the token transfer process. We'll create a test that:
1. Encrypts a transfer amount
2. Sends tokens from owner to recipient
3. Verifies the transfer was successful by checking balance handles
Create a new file `test/ERC7984Example.test.ts` with the following test:
```ts
import { expect } from 'chai';
import { ethers, fhevm } from 'hardhat';
describe('ERC7984Example', function () {
let token: any;
let owner: any;
let recipient: any;
let other: any;
const INITIAL_AMOUNT = 1000;
const TRANSFER_AMOUNT = 100;
beforeEach(async function () {
[owner, recipient, other] = await ethers.getSigners();
// Deploy ERC7984Example contract
token = await ethers.deployContract('ERC7984Example', [
owner.address,
INITIAL_AMOUNT,
'Confidential Token',
'CTKN',
'https://example.com/token'
]);
});
describe('Confidential Transfer Process', function () {
it('should transfer tokens from owner to recipient', async function () {
// Create encrypted input for transfer amount
const encryptedInput = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(TRANSFER_AMOUNT)
.encrypt();
// Perform the confidential transfer
await expect(token
.connect(owner)
['confidentialTransfer(address,bytes32,bytes)'](
recipient.address,
encryptedInput.handles[0],
encryptedInput.inputProof
)).to.not.be.reverted;
// Check that both addresses have balance handles (without decryption for now)
const recipientBalanceHandle = await token.confidentialBalanceOf(recipient.address);
const ownerBalanceHandle = await token.confidentialBalanceOf(owner.address);
expect(recipientBalanceHandle).to.not.be.undefined;
expect(ownerBalanceHandle).to.not.be.undefined;
});
});
});
```
To run the tests, use:
```bash
npx hardhat test test/ERC7984Example.test.ts
```
### Advanced features and extensions
The basic ERC7984Example contract provides core functionality, but you can extend it with additional features. For example:
#### Minting functions
**Visible Mint** - Allows the owner to mint tokens with a clear amount:
```solidity
function mint(address to, uint64 amount) external onlyOwner {
_mint(to, FHE.asEuint64(amount));
}
```
* **When to use**: Prefer this for public/tokenomics-driven mints where transparency is desired (e.g., scheduled emissions).
* **Privacy caveat**: The minted amount is visible in calldata and events; use `confidentialMint` for privacy.
* **Access control**: Consider replacing `onlyOwner` with role-based access via `AccessControl` (e.g., `MINTER_ROLE`) for multi-signer workflows.
* **Supply caps**: If you need a hard cap, add a check before `_mint` and enforce it consistently for both visible and confidential flows.
**Confidential Mint** - Allows minting with encrypted amounts for enhanced privacy:
```solidity
function confidentialMint(
address to,
externalEuint64 encryptedAmount,
bytes calldata inputProof
) external onlyOwner returns (euint64 transferred) {
return _mint(to, FHE.fromExternal(encryptedAmount, inputProof));
}
```
* **Inputs**: `encryptedAmount` and `inputProof` are produced off-chain with the SDK. Always validate and revert on malformed inputs.
* **Gas considerations**: Confidential operations cost more gas; batch mints sparingly and prefer fewer larger mints to reduce overhead.
* **Auditing**: While amounts stay private, you still get a verifiable audit trail of mints (timestamps, sender, recipient).
* **Example (Hardhat SDK)**:
```ts
const enc = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(1_000)
.encrypt();
await token.confidentialMint(recipient.address, enc.handles[0], enc.inputProof);
```
#### Burning functions
**Visible Burn** - Allows the owner to burn tokens with a clear amount:
```solidity
function burn(address from, uint64 amount) external onlyOwner {
_burn(from, FHE.asEuint64(amount));
}
```
**Confidential Burn** - Allows burning with encrypted amounts:
```solidity
function confidentialBurn(
address from,
externalEuint64 encryptedAmount,
bytes calldata inputProof
) external onlyOwner returns (euint64 transferred) {
return _burn(from, FHE.fromExternal(encryptedAmount, inputProof));
}
```
* **Authorization**: Burning from arbitrary accounts is powerful; consider stronger controls (roles, multisig, timelocks) or user-consented burns.
* **Event strategy**: Decide whether to emit custom events revealing intent (not amounts) for better observability and offchain indexing.
* **Error surfaces**: Expect balance/allowance-like failures if encrypted amount exceeds balance; test both success and revert paths.
* **Example (Hardhat SDK)**:
```ts
const enc = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(250)
.encrypt();
await token.confidentialBurn(holder.address, enc.handles[0], enc.inputProof);
```
#### Total supply visibility
If you want the owner to be able to view the total supply (useful for administrative purposes):
```solidity
function _update(address from, address to, euint64 amount) internal virtual override returns (euint64 transferred) {
transferred = super._update(from, to, amount);
FHE.allow(confidentialTotalSupply(), owner());
}
```
* **What this does**: Grants the `owner` permission to decrypt the latest total supply handle after every state-changing update.
* **Operational model**: The owner can call `confidentialTotalSupply()` and use their off-chain key material to decrypt the returned handle.
* **Security considerations**:
* If ownership changes, ensure only the new owner can decrypt going forward. With `Ownable2Step`, this function will automatically allow the current `owner()`.
* Be mindful of compliance: granting supply visibility may be considered privileged access; document who holds the key and why.
* **Alternatives**: If you want organization-wide access, grant via a dedicated admin contract that holds decryption authority instead of a single EOA.
# erc7984
This example demonstrates how to create a confidential token using OpenZeppelin's smart contract library powered by ZAMA's FHEVM.
{% hint style="info" %}
To run this example correctly, make sure you clone the [fhevm-hardhat-template](https://github.com/zama-ai/fhevm-hardhat-template) and that the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="ERC7984Example.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {FHE, externalEuint64, euint64} from "@fhevm/solidity/lib/FHE.sol";
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";
import {ERC7984} from "@openzeppelin/confidential-contracts/token/ERC7984.sol";
contract ERC7984Example is ZamaEthereumConfig, ERC7984, Ownable2Step {
constructor(
address owner,
uint64 amount,
string memory name_,
string memory symbol_,
string memory tokenURI_
) ERC7984(name_, symbol_, tokenURI_) Ownable(owner) {
euint64 encryptedAmount = FHE.asEuint64(amount);
_mint(owner, encryptedAmount);
}
}
```
{% endtab %}
{% tab title="ERC7984Example.test.ts" %}
```ts
import { expect } from 'chai';
import { ethers, fhevm } from 'hardhat';
describe('ERC7984Example', function () {
let token: any;
let owner: any;
let recipient: any;
let other: any;
const INITIAL_AMOUNT = 1000;
const TRANSFER_AMOUNT = 100;
beforeEach(async function () {
[owner, recipient, other] = await ethers.getSigners();
// Deploy ERC7984Example contract
token = await ethers.deployContract('ERC7984Example', [
owner.address,
INITIAL_AMOUNT,
'Confidential Token',
'CTKN',
'https://example.com/token'
]);
});
describe('Initialization', function () {
it('should set the correct name', async function () {
expect(await token.name()).to.equal('Confidential Token');
});
it('should set the correct symbol', async function () {
expect(await token.symbol()).to.equal('CTKN');
});
it('should set the correct token URI', async function () {
expect(await token.tokenURI()).to.equal('https://example.com/token');
});
it('should mint initial amount to owner', async function () {
// Verify that the owner has a balance (without decryption for now)
const balanceHandle = await token.confidentialBalanceOf(owner.address);
expect(balanceHandle).to.not.be.undefined;
});
});
describe('Transfer Process', function () {
it('should transfer tokens from owner to recipient', async function () {
// Create encrypted input for transfer amount
const encryptedInput = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(TRANSFER_AMOUNT)
.encrypt();
// Perform the transfer
await expect(token
.connect(owner)
['confidentialTransfer(address,bytes32,bytes)'](
recipient.address,
encryptedInput.handles[0],
encryptedInput.inputProof
)).to.not.be.reverted;
// Check that both addresses have balance handles (without decryption for now)
const recipientBalanceHandle = await token.confidentialBalanceOf(recipient.address);
const ownerBalanceHandle = await token.confidentialBalanceOf(owner.address);
expect(recipientBalanceHandle).to.not.be.undefined;
expect(ownerBalanceHandle).to.not.be.undefined;
});
it('should allow recipient to transfer received tokens', async function () {
// First transfer from owner to recipient
const encryptedInput1 = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(TRANSFER_AMOUNT)
.encrypt();
await expect(token
.connect(owner)
['confidentialTransfer(address,bytes32,bytes)'](
recipient.address,
encryptedInput1.handles[0],
encryptedInput1.inputProof
)).to.not.be.reverted;
// Second transfer from recipient to other
const encryptedInput2 = await fhevm
.createEncryptedInput(await token.getAddress(), recipient.address)
.add64(50) // Transfer half of what recipient received
.encrypt();
await expect(token
.connect(recipient)
['confidentialTransfer(address,bytes32,bytes)'](
other.address,
encryptedInput2.handles[0],
encryptedInput2.inputProof
)).to.not.be.reverted;
// Check that all addresses have balance handles (without decryption for now)
const otherBalanceHandle = await token.confidentialBalanceOf(other.address);
const recipientBalanceHandle = await token.confidentialBalanceOf(recipient.address);
expect(otherBalanceHandle).to.not.be.undefined;
expect(recipientBalanceHandle).to.not.be.undefined;
});
it('should revert when trying to transfer more than balance', async function () {
const excessiveAmount = INITIAL_AMOUNT + 100;
const encryptedInput = await fhevm
.createEncryptedInput(await token.getAddress(), recipient.address)
.add64(excessiveAmount)
.encrypt();
await expect(
token
.connect(recipient)
['confidentialTransfer(address,bytes32,bytes)'](
other.address,
encryptedInput.handles[0],
encryptedInput.inputProof
)
).to.be.revertedWithCustomError(token, 'ERC7984ZeroBalance')
.withArgs(recipient.address);
});
it('should revert when transferring to zero address', async function () {
const encryptedInput = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(TRANSFER_AMOUNT)
.encrypt();
await expect(
token
.connect(owner)
['confidentialTransfer(address,bytes32,bytes)'](
ethers.ZeroAddress,
encryptedInput.handles[0],
encryptedInput.inputProof
)
).to.be.revertedWithCustomError(token, 'ERC7984InvalidReceiver')
.withArgs(ethers.ZeroAddress);
});
});
});
```
{% endtab %}
{% tab titl프로젝트로 돌아가기