bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 38쪽
e="ERC7984Example.fixture.ts" %}
```ts
import { ethers } from "hardhat";
import type { ERC7984Example } from "../../types";
import type { ERC7984Example__factory } from "../../types";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
export async function deployERC7984ExampleFixture(owner: HardhatEthersSigner) {
// Deploy ERC7984Example with initial supply
const ERC7984ExampleFactory = (await ethers.getContractFactory(
"ERC7984Example",
)) as ERC7984Example__factory;
const ERC7984Example = (await ERC7984ExampleFactory.deploy(
owner.address, // Owner address
1000, // Initial amount
"Confidential Token",
"CTKN",
"https://example.com/token",
)) as ERC7984Example;
const ERC7984ExampleAddress = await ERC7984Example.getAddress();
return {
ERC7984Example,
ERC7984ExampleAddress,
};
}
```
{% endtab %}
{% endtabs %}
# swapERC7984ToERC20
This example demonstrates how to swap between a confidential token - the ERC7984 and the ERC20 tokens 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="SwapERC7984ToERC20.sol" %}
{% endtab %}
{% tab %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import {FHE, externalEuint64, euint64} from "@fhevm/solidity/lib/FHE.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC7984} from "@openzeppelin/confidential-contracts/interfaces/IERC7984.sol";
contract SwapERC7984ToERC20 {
error SwapERC7984ToERC20InvalidGatewayRequest(uint256 requestId);
mapping(uint256 requestId => address) private _receivers;
IERC7984 private _fromToken;
IERC20 private _toToken;
constructor(IERC7984 fromToken, IERC20 toToken) {
_fromToken = fromToken;
_toToken = toToken;
}
function SwapERC7984ToERC20(externalEuint64 encryptedInput, bytes memory inputProof) public {
euint64 amount = FHE.fromExternal(encryptedInput, inputProof);
FHE.allowTransient(amount, address(_fromToken));
euint64 amountTransferred = _fromToken.confidentialTransferFrom(msg.sender, address(this), amount);
bytes32[] memory cts = new bytes32[](1);
cts[0] = euint64.unwrap(amountTransferred);
uint256 requestID = FHE.requestDecryption(cts, this.finalizeSwap.selector);
// register who is getting the tokens
_receivers[requestID] = msg.sender;
}
function finalizeSwap(uint256 requestID, uint64 amount, bytes[] memory signatures) public virtual {
FHE.checkSignatures(requestID, signatures);
address to = _receivers[requestID];
require(to != address(0), SwapERC7984ToERC20InvalidGatewayRequest(requestID));
delete _receivers[requestID];
if (amount != 0) {
SafeERC20.safeTransfer(_toToken, to, amount);
}
}
}
```
{% endtab %}
{% endtabs %}
# swapERC7984ToERC7984
This example demonstrates how to swap between a confidential token - the ERC7984 and the ERC20 tokens 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="SwapERC7984ToERC20.sol" %}
{% endtab %}
{% tab %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.27;
import {FHE, externalEuint64, euint64} from "@fhevm/solidity/lib/FHE.sol";
import {IERC7984} from "@openzeppelin/confidential-contracts/interfaces/IERC7984.sol";
contract SwapERC7984ToERC7984 {
function swapConfidentialForConfidential(
IERC7984 fromToken,
IERC7984 toToken,
externalEuint64 amountInput,
bytes calldata inputProof
) public virtual {
require(fromToken.isOperator(msg.sender, address(this)));
euint64 amount = FHE.fromExternal(amountInput, inputProof);
FHE.allowTransient(amount, address(fromToken));
euint64 amountTransferred = fromToken.confidentialTransferFrom(msg.sender, address(this), amount);
FHE.allowTransient(amountTransferred, address(toToken));
toToken.confidentialTransfer(msg.sender, amountTransferred);
}
}
```
{% endtab %}
{% endtabs %}
# vesting-wallet
This example demonstrates how to create a vesting wallet using OpenZeppelin's smart contract library powered by ZAMA's FHEVM.
`VestingWalletConfidential` receives `ERC7984` tokens and releases them to the beneficiary according to a confidential, linear vesting schedule.
{% 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="VestingWalletExample.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import {FHE, ebool, euint64, euint128} from "@fhevm/solidity/lib/FHE.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol";
import {IERC7984} from "../interfaces/IERC7984.sol";
/**
* @title VestingWalletExample
* @dev A simple example demonstrating how to create a vesting wallet for ERC7984 tokens
*
* This contract shows how to create a vesting wallet that receives ERC7984 tokens
* and releases them to the beneficiary according to a confidential, linear vesting schedule.
*
* This is a non-upgradeable version for demonstration purposes.
*/
contract VestingWalletExample is Ownable, ReentrancyGuardTransient, ZamaEthereumConfig {
mapping(address token => euint128) private _tokenReleased;
uint64 private _start;
uint64 private _duration;
/// @dev Emitted when releasable vested tokens are released.
event VestingWalletConfidentialTokenReleased(address indexed token, euint64 amount);
constructor(
address beneficiary,
uint48 startTimestamp,
uint48 durationSeconds
) Ownable(beneficiary) {
_start = startTimestamp;
_duration = durationSeconds;
}
/// @dev Timestamp at which the vesting starts.
function start() public view virtual returns (uint64) {
return _start;
}
/// @dev Duration of the vesting in seconds.
function duration() public view virtual returns (uint64) {
return _duration;
}
/// @dev Timestamp at which the vesting ends.
function end() public view virtual returns (uint64) {
return start() + duration();
}
/// @dev Amount of token already released
function released(address token) public view virtual returns (euint128) {
return _tokenReleased[token];
}
/**
* @dev Getter for the amount of releasable `token` tokens. `token` should be the address of an
* {IERC7984} contract.
*/
function releasable(address token) public virtual returns (euint64) {
euint128 vestedAmount_ = vestedAmount(token, uint48(block.timestamp));
euint128 releasedAmount = released(token);
ebool success = FHE.ge(vestedAmount_, releasedAmount);
return FHE.select(success, FHE.asEuint64(FHE.sub(vestedAmount_, releasedAmount)), FHE.asEuint64(0));
}
/**
* @dev Release the tokens that have already vested.
*
* Emits a {VestingWalletConfidentialTokenReleased} event.
*/
function release(address token) public virtual nonReentrant {
euint64 amount = releasable(token);
FHE.allowTransient(amount, token);
euint64 amountSent = IERC7984(token).confidentialTransfer(owner(), amount);
// This could overflow if the total supply is resent `type(uint128).max/type(uint64).max` times. This is an accepted risk.
euint128 newReleasedAmount = FHE.add(released(token), amountSent);
FHE.allow(newReleasedAmount, owner());
FHE.allowThis(newReleasedAmount);
_tokenReleased[token] = newReleasedAmount;
emit VestingWalletConfidentialTokenReleased(token, amountSent);
}
/**
* @dev Calculates the amount of tokens that have been vested at the given timestamp.
* Default implementation is a linear vesting curve.
*/
function vestedAmount(address token, uint48 timestamp) public virtual returns (euint128) {
return _vestingSchedule(FHE.add(released(token), IERC7984(token).confidentialBalanceOf(address(this))), timestamp);
}
/// @dev This returns the amount vested, as a function of time, for an asset given its total historical allocation.
function _vestingSchedule(euint128 totalAllocation, uint48 timestamp) internal virtual returns (euint128) {
if (timestamp < start()) {
return euint128.wrap(0);
} else if (timestamp >= end()) {
return totalAllocation;
} else {
return FHE.div(FHE.mul(totalAllocation, (timestamp - start())), duration());
}
}
}
```
{% endtab %}
{% tab title="VestingWalletExample.test.ts" %}
```typescript
import { expect } from 'chai';
import { ethers, fhevm } from 'hardhat';
import { time } from '@nomicfoundation/hardhat-network-helpers';
describe('VestingWalletExample', function () {
let vestingWallet: any;
let token: any;
let owner: any;
let beneficiary: any;
let other: any;
const VESTING_AMOUNT = 1000;
const VESTING_DURATION = 60 * 60; // 1 hour in seconds
beforeEach(async function () {
const accounts = await ethers.getSigners();
[owner, beneficiary, other] = accounts;
// Deploy ERC7984 mock token
token = await ethers.deployContract('$ERC7984Mock', [
'TestToken',
'TT',
'https://example.com/metadata'
]);
// Get current time and set vesting to start in 1 minute
const currentTime = await time.latest();
const startTime = currentTime + 60;
// Deploy and initialize vesting wallet in one step
vestingWallet = await ethers.deployContract('VestingWalletExample', [
beneficiary.address,
startTime,
VESTING_DURATION
]);
// Mint tokens to the vesting wallet
const encryptedInput = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(VESTING_AMOUNT)
.encrypt();
await (token as any)
.connect(owner)
['$_mint(address,bytes32,bytes)'](
vestingWallet.target,
encryptedInput.handles[0],
encryptedInput.inputProof
);
});
describe('Vesting Schedule', function () {
it('should not release tokens before vesting starts', async function () {
// Just verify the contract can be called without FHEVM decryption for now
await expect(vestingWallet.connect(beneficiary).release(await token.getAddress()))
.to.not.be.reverted;
});
it('should release half the tokens at midpoint', async function () {
const currentTime = await time.latest();
const startTime = currentTime + 60;
const midpoint = startTime + (VESTING_DURATION / 2);
await time.increaseTo(midpoint);
// Just verify the contract can be called without FHEVM decryption for now
await expect(vestingWallet.connect(beneficiary).release(await token.getAddress()))
.to.not.be.reverted;
});
it('should release all tokens after vesting ends', async function () {
const currentTime = await time.latest();
const startTime = currentTime + 60;
const endTime = startTime + VESTING_DURATION + 1000;
await time.increaseTo(endTime);
// Just verify the contract can be called without FHEVM decryption for now
await expect(vestingWallet.connect(beneficiary).release(await token.getAddress()))
.to.not.be.reverted;
});
});
});
```
{% endtab %}
{% tab title="VestingWalletExample.fixture.ts" %}
```typescript
import { ethers } from 'hardhat';
import { time } from '@nomicfoundation/hardhat-network-helpers';
export async function deployVestingWalletExampleFixture() {
const [owner, beneficiary] = await ethers.getSigners();
// Deploy ERC7984 mock token
const token = await ethers.deployContract('ERC7984Example', [
'TestToken',
'TT',
'https://example.com/metadata'
]);
// Get current time and set vesting to start in 1 minute
const currentTime = await time.latest();
const startTime = currentTime + 60;
const duration = 60 * 60; // 1 hour
// Deploy and initialize vesting wallet in one step
const vestingWallet = await ethers.deployContract('VestingWalletExample', [
beneficiary.address,
startTime,
duration
]);
return { vestingWallet, token, owner, beneficiary, startTime, duration };
}
export async function deployVestingWalletWithTokensFixture() {
const { vestingWallet, token, owner, beneficiary, startTime, duration } = await deployVestingWalletExampleFixture();
// Import fhevm for token minting
const { fhevm } = await import('hardhat');
// Mint tokens to the vesting wallet
const encryptedInput = await fhevm
.createEncryptedInput(await token.getAddress(), owner.address)
.add64(1000) // 1000 tokens
.encrypt();
await (token as any)
.connect(owner)
['$_mint(address,bytes32,bytes)'](
vestingWallet.target,
encryptedInput.handles[0],
encryptedInput.inputProof
);
return { vestingWallet, token, owner, beneficiary, startTime, duration, vestingAmount: 1000 };
}
```
{% endtab %}
{% endtabs %}
# metrics
# FHEVM Metrics
This document lists and describes metrics supported by FHEVM services. Intention is for it to help operators monitor these services, configure alarms based on the metrics, and act on those in case of issues.
We also recommend alarm thresholds for each metric, where applicable. Thresholds suggested are conservative and can be adjusted based on the operator's environment and requirements.
Note that recommendations assume a smoke test that runs transactions/requests at a rate of approximately 1 per 30 seconds. These include verify proofs, FHE computation, ACL updates and decryptions.
## coprocessor
### transaction-sender
#### Metric Name: `coprocessor_txn_sender_verify_proof_success_counter`
* **Type**: Counter
* **Description**: Counts the number of successful verify or reject proof transactions in the transaction-sender.
* **Alarm**: If the counter is a flat line over a period of time.
* **Recommendation**: 0 for more than 1 minute, i.e. `increase(counter[1m]) == 0`.
#### Metric Name: `coprocessor_txn_sender_verify_proof_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed verify or reject proof transactions in the transaction-sender.
* **Alarm**: If the counter increases over a period of time.
* **Recommendation**: more than 60 failures in 1 minute, i.e. `increase(counter[1m]) > 60`.
#### Metric Name: `coprocessor_txn_sender_add_ciphertext_material_success_counter`
* **Type**: Counter
* **Description**: Counts the number of successful add ciphertext material transactions in the transaction-sender.
* **Alarm**: If the counter is a flat line over a period of time.
* **Recommendation**: 0 for more than 1 minute, i.e. `increase(counter[1m]) == 0`.
#### Metric Name: `coprocessor_txn_sender_add_ciphertext_material_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed add ciphertext material transactions in the transaction-sender.
* **Alarm**: If the counter increases over a period of time.
* **Recommendation**: more than 60 failures in 1 minute, i.e. `increase(counter[1m]) > 60`.
#### Metric Name: `coprocessor_txn_sender_allow_handle_success_counter`
* **Type**: Counter
* **Description**: Counts the number of successful allow handle transactions in the transaction-sender.
* **Alarm**: If the counter is a flat line over a period of time.
* **Recommendation**: 0 for more than 1 minute, i.e. `increase(counter[1m]) == 0`.
#### Metric Name: `coprocessor_txn_sender_allow_handle_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed allow handle transactions in the transaction-sender.
* **Alarm**: If the counter increases over a period of time.
* **Recommendation**: more than 60 failures in 1 minute, i.e. `increase(counter[1m]) > 60`.
#### Metric Name: `coprocessor_allow_handle_unsent_gauge`
* **Type**: Gauge
* **Description**: Tracks the number of unsent allow handle transactions in the transaction-sender.
* **Alarm**: If the gauge value exceeds a predefined threshold.
* **Recommendation**: more than 100 unsent over 2 minutes, i.e. `min_over_time(gauge[2m]) > 100`.
#### Metric Name: `coprocessor_add_ciphertext_material_unsent_gauge`
* **Type**: Gauge
* **Description**: Tracks the number of unsent add ciphertext material transactions in the transaction-sender.
* **Alarm**: If the gauge value exceeds a predefined threshold.
* **Recommendation**: more than 100 unsent over 2 minutes, i.e. `min_over_time(gauge[2m]) > 100`.
#### Metric Name: `coprocessor_verify_proof_resp_unsent_txn_gauge`
* **Type**: Gauge
* **Description**: Tracks the number of unsent verify proof response transactions in the transaction-sender.
* **Alarm**: If the gauge value exceeds a predefined threshold.
* **Recommendation**: more than 100 unsent over 2 minutes, i.e. `min_over_time(gauge[2m]) > 100`.
#### Metric Name: `coprocessor_verify_proof_pending_gauge`
* **Type**: Gauge
* **Description**: Tracks the number of pending verify proofs (pending on the zkproof-worker).
* **Alarm**: If the gauge value exceeds a predefined threshold.
* **Recommendation**: more than 100 pending over 2 minutes, i.e. `min_over_time(gauge[2m]) > 100`.
### gw-listener
#### Metric Name: `coprocessor_gw_listener_verify_proof_success_counter`
* **Type**: Counter
* **Description**: Counts the number of successful verify proof request events in GW listener.
* **Alarm**: If the counter is a flat line over a period of time.
* **Recommendation**: 0 for more than 1 minute, i.e. `increase(counter[1m]) == 0`.
#### Metric Name: `coprocessor_gw_listener_verify_proof_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed verify proof request events in GW listener.
* **Alarm**: If the counter increases over a period of time.
* **Recommendation**: more than 60 failures in 1 minute, i.e. `increase(counter[1m]) > 60`.
#### Metric Name: `coprocessor_gw_listener_get_block_num_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed get block number requests in GW listener.
* **Alarm**: If the counter increases over a period of time.
* **Recommendation**: more than 60 failures in 1 minute, i.e. `increase(counter[1m]) > 60`.
#### Metric Name: `coprocessor_gw_listener_get_logs_success_counter`
* **Type**: Counter
* **Description**: Counts the number of successful get logs requests in GW listener.
* **Alarm**: If the counter is a flat line over a period of time.
#### Metric Name: `coprocessor_gw_listener_get_logs_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed get logs requests in GW listener.
* **Alarm**: If the counter increases over a period of time.
* **Recommendation**: 0 for more than 1 minute, i.e. `increase(counter[1m]) == 0`.
#### Metric Name: `coprocessor_gw_listener_activate_crs_success_counter`
* **Type**: Counter
* **Description**: Counts the number of successful activate CRS requests in GW listener.
* **Alarm**: N/A - no alarm needed as activate CRS is an infrequent event.
#### Metric Name: `coprocessor_gw_listener_activate_crs_fail_counter`
* **Type**: Counter
* **Description**: Counts the number of failed activate CRS requests in GW listener.
* **Alarm**: If the counter increases from 0. Activate CRS is an important event that should not fail.
* **Recommendation**: alarm on any failures over a 1 minute period, i.e. `increase(counter[1m]) > 0`.
#### Metric Name: `coprocessor_gw_listener_crs_digest_mismatch_counter`
* **Type**: Counter
* **Description**: Counts the number of CRS digest mismatches in GW listener.
* **Alarm**: If the counter increases from 0. CRS digest mismatch is not something that is supposed to happen in normal circu프로젝트로 돌아가기