bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 52쪽
andEuint64(); // 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 FHE.randEbool();
}
```
## **Bounded random numbers**
To generate random numbers within a specific range, you can specify an **upper bound**. The specified upper bound must be a power of 2. The random number will be in the range `[0, upperBound - 1]`.
```solidity
// Generate random numbers with upper bounds
euint8 r8 = FHE.randEuint8(32); // Random number between 0-31
euint16 r16 = FHE.randEuint16(512); // Random number between 0-511
euint32 r32 = FHE.randEuint32(65536); // Random number between 0-65535
```
### **Example: Random number with upper bound**
```solidity
function randomBoundedNumber(uint16 upperBound) public returns (euint16) {
return FHE.randEuint16(upperBound);
}
```
## **Security Considerations**
* **Cryptographic security**:\
The random numbers are generated using a cryptographically secure pseudo-random number generator (CSPRNG) and remain encrypted until explicitly decrypted.
* **Gas consumption**:\
Each call to a random number generation function consumes gas. Developers should optimize the use of these functions, especially in gas-sensitive contracts.
* **Privacy guarantee**:\
Random values are fully encrypted, ensuring they cannot be accessed or predicted by unauthorized parties.
# protocol-contracts
# Deployment guide for testing
This guide explains all the steps needed to deploy a test instance of the full protocol. This is not the real deployment process, and is intended only for end-to-end testing of governance.
## Fund 2 accounts on both chains
Fill both `DEPLOYER_PRIVATE_KEY` and `PROTOCOL_DEPLOYER_PRIVATE_KEY` values inside the `.env` contained in this directory (you can start by copying the `.env.example`).
Those 2 private keys *must* be different.
Make sure to fund those 2 accounts on both Ethereum Sepolia Testnet and Gateway Testnet networks.
## Deploy an Aragon DAO on Sepolia
Go to `https://app.aragon.org/`\[<https://app.aragon.org/>] and use the front-end to deploy a DAO on sepolia. *Important:* the account connected to the Aragon front-end and deploying this DAO must be the one corresponding to `DEPLOYER_PRIVATE_KEY`.
Once deployed, copy the address of the deployed DAO contract inside the `.env`: this should be the `DAO_ADDRESS` value.
## Deploy the Zama token and OFT
## Deploy Gateway contracts
# feesBurner
After filling all values of the `.env` file until the `ZAMA_ERC20_ADDRESS` variable (i.e all variables except from `PROTOCOL_FEES_BURNER_ADDRESS`), run this command to deploy first the `ProtocolFeesBurner` contract on Ethereum testnet:
## Deployment
### Setup
Copy the environment file: `cp .env.example .env`.
Then fill all the environment variables till `ZAMA_ERC20_ADDRESS` for the wanted networks (`MAINNET` or `TESTNET` RPC urls).
Install the NPM packages: `npm i`
### Automated Deployment (Recommended)
Run the following hardhat task to deploy ProtocolFeesBurner on Ethereum and FeesSenderToBurner on Gateway:
```bash
npx hardhat deploy:feesBurner --preset <mainnet|testnet> --verify <boolean>
```
To verify the ProtocolFeesBurner on Etherscan and FeesSenderToBurner on BlockScout, set this flag: `--verify true`.
### Manual Deployment of FeesBurner
#### ProtocolFeesBurner Deployment
Deploy the ProtocolFeesBurner contract on Ethereum
```bash
npx hardhat deploy --tags ProtocolFeesBurner --network ethereum-testnet
```
Then fill the `PROTOCOL_FEES_BURNER_ADDRESS` env variable with the address of your deployment.
#### FeesSenderToBurner Deployment
```bash
npx hardhat deploy --tags FeesSenderToBurner --network gateway-testnet
```
#### Verification
You can verify the contracts on Etherscan with the following tasks:
```bash
npx hardhat --network ethereum-testnet task:verifyProtocolFeesBurner --protocol-fees-burner <PROCOTOL_FEES_BURNER_ADDRESS>
```
```bash
npx hardhat --network gateway-testnet task:verifyFeesSenderToBurner --fees-sender-to-burner <FEES_SENDER_TO_BURNER_ADDRESS>
```
# Governance OApp
1/ Fill the `.env` file (see `.env.example`), use a `PRIVATE_KEY` from an account funded on both chains.
2/ Deploy the `GovernanceOAppSender` contract by running:
```bash
npx hardhat lz:deploy
```
And select `ethereum-testnet` network then enter the `GovernanceOAppSender` script.
3/ Deploy the `GovernanceOAppReceiver` contract by running:
```bash
npx hardhat lz:deploy
```
And select `gateway-testnet` network then enter the `GovernanceOAppReceiver` script.
4/ Wire contracts:
```bash
npx hardhat lz:oapp:wire --oapp-config layerzero.config.testnet.ts
```
5/ Verify contracts:
```bash
pnpm verify:etherscan:ethereum:testnet
pnpm verify:etherscan:gateway:testnet
```
# PauserSetWrapper
This project contains the PauserSetWrapper contract, which allows pausers from a PauserSet contract to call specific functions on target contracts.
## Prerequisites
```bash
cp .env.example .env
```
Then fill the `PRIVATE_KEY` and `SEPOLIA_RPC_URL` in `.env` with your own values. Fill the `CONTRACT_TARGET`, `FUNCTION_SIGNATURE` and `PAUSER_SET` with the values of the target contract, function signature, and pauser set contract.
## Deployment
```shell
npx hardhat deploy --network <ethereum-testnet|ethereum-mainnet>
```
## Verification
After deployment, verify the contract on Etherscan:
```shell
npx hardhat task:verifyPauserSetWrapper --address <deployed-address> --network <ethereum-testnet|ethereum-mainnet>
```
## Testing
Run the test suite:
```shell
npx hardhat test
```
# AdminModule for the Safe MultiSig wallet to be used on Gateway
## Deploy Multisig Safe Wallet with only the deployer as owner
Be sure to start with an `.env` - or copy paste the `.env.example.deploy` and fill its values (not to be confused with `.env.example.test` to be used to run tests in hardhat only!) - with just those filled variables:
```
PRIVATE_KEY=
RPC_URL_ZAMA_GATEWAY_TESTNET=
BLOCKSCOUT_API=https://xxxxxxxxxxxx.xyz/api # don't forget the /api suffix at the end
```
Then run:
```
npx hardhat compile
npx hardhat task:deploySafe --network gateway-testnet
```
This will deploy `SafeL2` singleton contract, as well as `SafeProxyFactory` and `SafeL2Proxy`. The `SafeL2Proxy` is actually the multisig wallet which will become later the owner of `GatewayConfig`.
Then, after waiting for around 1 minute for the blockscout indexing to take into consideration newly deployed contracts, run:
```
npx hardhat task:verifySafe --network gateway-testnet
```
This will verify on Blockscout the 3 previously deployed contracts.
## Deploy, verify and enable the AdminModule
Add in your `.env` a value for the `ADMIN_ADDRESS`, which should be the address of an already deployed `GovernanceOAppReceiver` contract.
Deploy then the AdminModule with:
```
npx hardhat task:deployAdminModule --network gateway-testnet
```
And, after waiting for around 1 minute for the blockscout indexing, verify it with:
```
npx hardhat task:verifyAdminModule --network gateway-testnet
```
Finally, enable the safe module with:
```
npx hardhat task:enableAdminModule --network gateway-testnet
```
## Accept ownership of GatewayConfig contract
This step supposes that the original owner of GatewayConfig already called the `transferOwnership` function of `GatewayConfig` with the Safe proxy address as a new owner. Since `GatewayConfig` inherits from `Ownable2StepUpgradeable`, the Safe wallet still need to call `acceptOwnership` to effectively become the owner. This can be done using:
```
npx hardhat task:acceptGatewayConfigOwnership --network gateway-testnet
```
## Change owners and threshold of the Safe proxy
This can be done in the 3 following steps, in order to be careful and limit risk of errors.
# Zama token quickstart
## Step 1 : Initial setup
```bash
cp .env.example .env
```
Then fill the `PRIVATE_KEY` and `SEPOLIA_RPC_URL` in `.env` with your own values. The values of `INITIAL_SUPPLY_RECEIVER` (account receiving initially minted supply of 1 billion tokens) and `INITIAL_ADMIN` (first admin role, responsible of adding minters and other admins) should also be filled. For easy testing purpose, they could be both set to be the address of the account corresponding to `PRIVATE_KEY` (i.e the deployer). Also, if you want to do Step 5 (Etherscan verification) which is optional but recommended for easier debugging, get an Etherscan free API key in order to set the value of `ETHERSCAN_API`.
## Step 2 : Add Gateway Testnet to your Metamask wallet (optional)
For better DevX, you can add the Gateway Testnet network to your Metamask wallet.
## Step 3 : Funding deployer wallet on both chains
**Important:** Make sure the wallet address corresponding to your `PRIVATE_KEY` is funded on *both* chains corresponding to this OFT, meaning on both Ethereum Sepolia and Gateway Testnet.
## Automated Deployment
The deployment of the `ZamaERC20` and `ZamaOFTAdapter` on Ethereum Sepolia as well as the deployment of the `ZamaOFT` on Gateway Testnet and the wiring of both contracts can be done automatically by running the following Hardhat task:
```bash
npx hardhat deploy:token --preset testnet
```
The task automatically:
* Confirms `.env` is populated (Step 1) and that required environment variables are set.
* Deploys `ZamaERC20` to `ethereum-testnet` using the appropriate deploy script tags.
* Automatically captures the deployed `ZamaERC20` address and sets the `oftAdapter.tokenAddress` key in the Hardhat runtime configuration for the layerzero deployment of the `ZamaOFTAdapter`.
* Deploys `ZamaOFTAdapter` to `ethereum-testnet` with the correct token address configuration.
* Deploys `ZamaOFT` to `gateway-testnet` with the matching deploy script tag.
* Wires both contracts together using LayerZero's `lz:oapp:wire` task.
Add `--verify true` if you want to automatically run the Etherscan verification commands:
```bash
npx hardhat deploy:token --preset testnet --verify true
```
You can still follow the manual instructions below if you prefer.
## Step 4 : Deploy ZamaERC20, ZamaOFTAdapter and ZamaOFT
First, deploy the ZamaERC20 token, which is an ERC20 implementation from OpenZeppelin with few extensions (such as ERC20Permit and the transferAndCall-related ERC1363). Run this command:
```bash
pnpm i
npx hardhat lz:deploy
```
In the instructions of `lz:deploy`, choose both networks (or choose just ethereum-testnet, since gateway-testnet will be filtered out in the deployment script of the ERC20). Then enter `ZamaERC20` when asked for the deploy script tag. The ERC20 token will be deployed on Ethereum testnet and 1 billion tokens will be minted initially for the `INITIAL_SUPPLY_RECEIVER` account.
Please carefully note the ZamaERC20 contract address which has been logged during the run of the previous script. In your `hardhat.config.ts` file, add the following configuration to the `ethereum-testnet` you want to deploy the OFTAdapter to:
```typescript
oftAdapter: {
tokenAddress: '0x0', // Replace `0x0` with the address of the ERC20 token you want to adapt to the OFT functionality.
}
```
After updating your hardhat.config.ts file accordingly, second step is to deploy the ZamaOFTAdapter to the Ethereum testnet by running again:
```bash
npx hardhat lz:deploy
```
You can still select either both networks or alternatively uniquely the `ethereum-testnet` network (Gateway Testnet network will be filtered out because its config does not contain and `oftAdapter` field). But this time, enter `ZamaOFTAdapter` when asked for the deploy script tag. This will deploy the OFTAdapter contract on Ethereum Sepolia testnet.
Finally, third deployment step is to deploy the `ZamaOFT` contract on the Gateway Testnet. Again, you should run:
```bash
npx hardhat lz:deploy
```
You can still select either both networks or alternatively uniquely the `gateway-testnet` network this time. Now enter `ZamaOFT` when requested for the deploy script tag. This will deploy the `ZamaOFT` contract on Gateway Testnet.
## Step 5 : Etherscan verification (Optional)
In order verify the two contracts (`ZamaERC20` and `ZamaOFTAdapter`) on Etherscan for the Ethereum Sepolia network, use this command (don't worry if the following scripts return you an error or an invalid explorer URL link - see the note at the end of this step):
```bash
pnpm verify:etherscan:ethereum:sepolia
```
And to verify the `ZamaOFT` contract deployed on the Gateway Testnet network run:
```bash
pnpm verify:etherscan:gateway:testnet
```
**Note:** Due to a bug in the `verify-contract` task, sometimes those scripts will log an error and/or return a wrong URL for block explorer link, but most of the times, despite those errors, if you check the actual results by searching for corresponding contracts addresses on the block explorer, you will notice that the contracts will actually be succesfully verified after running those commands (i.e <https://sepolia.etherscan.io/> for Ethereum testnet and on the Gateway Testnet block explorer).
## Step 6 : Wire contracts
```bash
npx hardhat lz:oapp:wire --oapp-config layerzero.config.testnet.ts
```
And follow straightforward instructions to wire the `ZamaOFTAdapter` contract on Ethereum testnet with the `ZamaOFT` on Gateway Testnet.
## Step 7 : Cross-chain transfer
Two NPM scripts are available to send ZAMA tokens between Ethereum Sepolia and Gateway Testnet:
* `npm run zama:oft:send:ethToGateway -- <address> <amount>`
* `npm run zama:oft:send:gatewayToEth -- <address> <amount>`
The provided address is verified to be a proper Ethereum address, then tokens are sent using `lz:oft:send` task.
If you want to send tokens from/to other chains, you can directly use `lz:oft:send`, as described in the following section.
For example you can send `1.5` ZAMA token from Ethereum Sepolia to Gateway Testnet from the deployer wallet to a custom receiver address by running this command and following instructions:
```bash
npx hardhat lz:oft:send --src-eid 40161 --dst-eid 40424 --amount 1.5 --to <RECEIVER_ADDRESS>
```
**Note** In the OFTAdapter case here, contrarily to the OFT case, 2 transactions are sent in previous script instead of 1, because the sender must first approve the corresponding amount of the ERC20 token to the OFTAdapter (i.e calling approve method on the ERC20 method and passing the OFTAdapter address and correct amount as parameters), before locking them to the OFTAdapter contract in a second `send` transaction on OFTAdapter (reminder: in the OFT case, initiating a token transfer happens by directly burning an amount of the OFT contract by calling the `send` method of the OFT contract).
Once these transactions are sent, wait around 2 minutes and check the receiver's account on the Gateway Testnet block explorer that the receiver indeed received `1.5` ZAMA token on Gateway Testnet by clicking on `Token Holdings` there.
You could then also send back the tokens from Gateway Testnet to Ethereum Sepolia chain, by swapping the values of `--src-eid` and `--dst-eid` flags from previous command.
## Step 8 : Administrative tasks
After the contracts are deployed and wired you can manage permissions and ownership without writing custom scripts. The project exposes dedicated Hardhat tasks grouped by contract:
* **Role lifecycle on `ZamaERC20`:** Every supported role has its own grant/revoke command (`zama:erc20:grant:minter_role`, `zama:erc20:revoke:pausing_minter_role`, etc.) plus a `zama:erc20:renounce:*` variant that lets the currently connected signer drop its role. Use these to add minters, pause controllers, or new admins safely from the CLI.
* **`ZamaOFTAdapter` administration:** Set a new delegate on `ZamaOFTAdapter` with `zama:oftadapter:setDelegate --address <new_delegate>` and hand off overall control with `zama:oftadapter:transferOwnership --address <new_owner>`.
* **`ZamaOFT` administration:** Mirror the same actions on the `ZamaOFT` contract using `zama:oft:setDelegate --address <new_delegate>` and `zama:oft:transferOwnership --address <new_owner>`.
Always pass the correct `--network` flag so Hardhat connects to the chain that hosts the relevant deployment and make sure the signer you use already holds the corresponding privileges.
By default, these tasks will load the contract address of the task from environment variables:
* `ZAMAOFT_CONTRACT_ADDRESS` for `zama:oft:*`
* `ZAMAERC20_CONTRACT_ADDRESS` for `zama:erc20:*`
* `ZAMAOFTADAPTER_CONTRACT_ADDRESS` for `zama:oftadapter:*`
Two optional parameters are available in the tasks: `--from-deployment` and `--contract-address`, they are mutually exclusive.
* `--from-deployment` will fetch the contract address from the available deployments for the network the task is run upon. Here is an example granting the MINTER\_ROLE from the ZamaERC20 deployment on the ethereum-testnet
```bash
npx hardhat zama:erc20:grant:minter_role --address <NEW_MINTER_ADDRESS> --from-deployment true --network ethereum-testnet
```
* `--contract-address` will use the provided address as the contract address. Here is an example granting the MINTER\_ROLE from the ZamaERC20 deployment on the ethereum-testnet
```bash
npx hardhat zama:erc20:grant:minter_role --address <NEW_MINTER_ADDRESS> --contract-address <ZAMAERC20_CONTRACT_ADDRESS> --network ethereum-testnet
```
# sdk
# FHEVM Gateway SDK for Rust
A Rust SDK for interacting with Fully Homomorphic Encryption Virtual Machine (FHEVM) networks. This SDK simplifies the process of creating encrypted inputs, generating EIP-712 signatures, and handling decryption operations for the Gateway.
## Features
* **Encrypted Input Creation**: Generate encrypted inputs with zero-knowledge proofs
* **Multiple Data Types**: Support for various encrypted types (ebool, euint8-256, eaddress)
* **Decryption Operations**: Handle both public and user-authorized decryption
* **EIP-712 Support**: Generate and verify typed signatures with fluent builder pattern
* **Chain Support**: Compatible with multiple EVM blockchains
* **Builder Pattern**: Intuitive API design for complex operations
* **Multiple Values**: Process multiple encrypted values in single operations
## Disclaimer
This library requires (for now) a private access to kms repository.
## Installation
Add to your `Cargo.toml`:
```toml
[dependencies]
gateway-sdk = { path = "path/to/gateway-sdk" }
```
## Quick Start
```rust
use gateway_sdk::{FhevmSdkBuilder, Result};
use alloy::primitives::address;
use std::path::PathBuf;
fn main() -> Result<()> {
// Initialize SDK
let sdk = FhevmSdkBuilder::new()
.with_keys_directory(PathBuf::from("./keys"))
.with_gateway_chain_id(43113)
.with_host_chain_id(11155111)
.with_decryption_contract("0x1234567890123456789012345678901234567bbb")
.with_input_verification_contract("0x1234567890123456789012345678901234567aaa")
.with_acl_contract("0x0987654321098765432109876543210987654321")
.build()?;
// Create encrypted input
let mut builder = sdk.create_input_builder()?;
builder.add_u64(42)?;
builder.add_bool(true)?;
let encrypted = builder.encrypt_and_prove_for(
address!("0x7777777777777777777777777777777777777777"),
address!("0x8888888888888888888888888888888888888888")
)?;
// Generate EIP-712 signature for user decryption
let signature_result = sdk
.eip712_builder()
.with_public_key("2000000000000000a554e431f47ef7b1dd1b72a43432b06213a959953ec93785f2c699af9bc6f331")
.with_contract("0x7777777777777777777777777777777777777777")?
.with_validity_period(1748252823, 30)
.with_private_key("7136d8dc72f873124f4eded25f3525a20f6cee4296564c76b44f1d582c57640f")
.with_verification(true)
.generate_and_sign()?; // ← Recommended method
println!("Encrypted {} values", encrypted.handles.len());
println!("Signature verified: {}", signature_result.is_verified());
Ok(())
}
```
## Learn by Example
Run the minimal examples t프로젝트로 돌아가기