Skip to content

Commit

Permalink
Improve README + added comments on Guess random number game (#19)
Browse files Browse the repository at this point in the history
* adding nice visual to fhewordle

* feat: add fhewordle mock to the frontend

* change sample

* adding a guess random number game to the hardhat examples

* adding guess random number game

* added readme

* added readme

* added comments to guess random number game
  • Loading branch information
poppyseedDev authored Jan 13, 2025
1 parent b16af88 commit 71f25a4
Show file tree
Hide file tree
Showing 5 changed files with 365 additions and 167 deletions.
28 changes: 28 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
BSD 3-Clause License

Copyright (c) 2023, Zama

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
197 changes: 173 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,199 @@

This is an example dApp made with React.js to let users do transfers of a `ConfidentialERC20` token on fhEVM. It contains also a button to request the decryption of an encrypted secret value.

## How to use this repo

You can either deploy the dApp on the real fhEVM coprocessor on the Ethereum Sepolia testnet, or on a local Hardhat node (i.e a mocked corpocessor).
## Examples featured

### How to deploy on Sepolia
### Confidential Counter

First, before launching the React app, you must deploy the `ConfidentialERC20` smart contract and mint the first few tokens.
To do this, go to the `hardhat/` directory, and follow all the instructions from the [`README`](/hardhat/README.md) there to deploy and mint the first tokens with Alice's account, i.e until you are able to run the following command:
The Confidential Counter examples demonstrate progressively more complex uses of FHE operations:

```
npm run deploy-sepolia
```
1. **Basic Counter (Sample 1)**
- Simple encrypted counter using `euint8` type
- Basic increment operation using FHE addition
- Demonstrates minimal FHE setup and operations

> **Note:** Be careful to use your own private mnemonic key in this case, in the `.env` file (do not reuse the public values from `.env.example`!).
2. **Input Counter (Sample 2)**
- Accepts encrypted input values to increment by
- Shows how to handle encrypted inputs with proofs
- Demonstrates converting between encrypted types

After you succesfully run the Sepolia deployment script, go to the `frontend/` directory, and just run those two commands:
3. **Decryptable Counter (Sample 3)**
- Adds decryption capability via Gateway integration
- Shows how to request and handle decryption callbacks
- Maintains both encrypted and decrypted state

```
npm install
npm run dev
```
4. **Multi-User Counter (Sample 4)**
- Individual encrypted counters per user address
- Demonstrates access control with FHE
- Shows re-encryption for specific users
- Uses mapping for multiple encrypted values

This will launch the front-end of the dApp from a local Vite server, which will be available at the following URL: [`http://localhost:4173/`](http://localhost:4173/) . You can connect to the dApp with a Web3 wallet such as Metamask and start transferring tokens, reencrypt and read your balance, or request the decryption of the encrypted secret on Sepolia.
Each sample builds on the previous one to showcase different FHE capabilities while maintaining security and privacy of the counter values.

### How to use in Mocked mode
### GuessRandomNumberGame

First go to the `hardhat/` directory : define a new `.env` file - in mocked mode, simply doing a copy `cp .env.example .env` is doable, but you can also you your own private mnemonic - then install all packages with
`npm i`. Now you can launch the hardhat local node with:
**How the Game Works**

1. **Random Target Generation**: Contract generates an encrypted random number within `MAX_VALUE` range using TFHE.

2. **Player Participation**: Players submit encrypted guesses with ZK proofs. One guess per address per round.

3. **Minimum Players**: Game requires `MIN_PLAYERS` submissions before proceeding.

4. **Winner Determination**: Uses FHE operations to privately find the closest guess to target while maintaining confidentiality.

5. **Decryption & Results**: Target, winning guess, and winner's address are securely decrypted via Zama Gateway. Results announced through `WinnerDeclared` event.

6. **Game Reset**: Automatically clears state, generates new target, and prepares for next round.

The game showcases FHE capabilities for secure random number generation, private comparisons, and controlled decryption while maintaining player privacy throughout.

### FHEWordle

**How the Game Works**

1. **Game Setup**: A factory contract deploys unique game instances for each player using minimal proxies. Each game has:
- An encrypted target word (represented as encrypted letter indices 0-25)
- A player address who can submit guesses
- A relayer address who helps with FHE operations

2. **Word Submission**: The relayer submits the encrypted target word letters using `submitWord1`. The letters are stored as encrypted uint8 values.

3. **Player Guessing**: Players submit guesses by calling `guessWord1` with:
- A word encoded as a uint32 (each letter as index 0-25)
- A Merkle proof verifying the word is valid
- Limited to 5 guesses total

4. **Guess Feedback**: After each guess, players can request feedback via `getGuess` which returns:
- An encrypted equality mask showing exact letter matches (green)
- An encrypted letter presence mask showing letters in wrong positions (yellow)

5. **Winning**: Players can claim victory using `claimWin` if they get all letters correct. The contract verifies this using FHE operations.

6. **Word Revelation**: After game completion, the target word can be revealed using `revealWordAndStore`.

7. **Proof Verification**: The relayer can verify game outcomes using Merkle proofs via `checkProof`.

The game leverages FHE operations to keep the target word encrypted while still allowing comparison with guesses. This prevents players from seeing the word until the game is complete.


### Decentralized Identity

**How it works**

1. **Identity Management**: The system consists of four main contracts:
- `IdMapping`: Maps user addresses to unique IDs for identity tracking
- `PassportID`: Stores encrypted passport/identity data like name, birthdate
- `Diploma`: Manages encrypted educational credentials and degrees
- `EmployerClaim`: Generates verifiable claims about age and education

2. **Identity Registration**:
- Users first get a unique ID from `IdMapping` via `generateId()`
- Authorized registrars can register encrypted passport data using `PassportID.registerIdentity()`
- Educational institutions can register encrypted diploma data via `Diploma.registerDiploma()`

3. **Encrypted Data Storage**: All sensitive data is stored encrypted using FHE:
- Names, birthdates, and biometric data in `PassportID`
- University, degree type, and grades in `Diploma`
- Access controlled through TFHE permissions

4. **Claim Generation**:
- Users can generate verifiable claims about their identity/credentials
- `EmployerClaim` supports two types of claims:
- Adult verification (18+ age check)
- Degree verification (specific degree requirements)
- Claims preserve privacy by using encrypted comparisons

5. **Verification Process**:
- Claims are generated as encrypted boolean results
- Employers can verify claims without seeing actual data
- Combined verification checks both age and education requirements
- Results stored as encrypted verification status

The system leverages FHE operations to enable privacy-preserving identity and credential verification without exposing sensitive personal data.

### MyConfidentialERC20.sol

**How it works**

1. **Confidential Token**: A privacy-preserving ERC20 token implementation using Fully Homomorphic Encryption (FHE):
- Balances and allowances are stored as encrypted values
- Transfers and approvals operate on encrypted data
- Inherits from ConfidentialERC20Mintable for basic token functionality

2. **Key Features**:
- Encrypted balances using euint64 type
- Standard ERC20 functions (transfer, approve, etc.) with FHE
- Minting capability restricted to owner
- Built-in decryption request/callback mechanism

3. **Secret Value Demo**:
- Contains an encrypted SECRET value (set to 42)
- Demonstrates Gateway decryption flow:
- requestSecret() initiates decryption request
- callbackSecret() receives and stores decrypted value
- Shows basic FHE operations and Gateway integration

4. **Privacy Protection**:
- All token balances and transfers are encrypted
- Only transaction participants can view their own balances
- Uses TFHE library for homomorphic operations
- Integrates with Zama's FHE infrastructure

The contract showcases how to implement confidential tokens while maintaining ERC20 compatibility and leveraging FHE for privacy preservation.



## How to use this repo

You can either deploy the dApp on the real fhEVM coprocessor on the Ethereum Sepolia testnet, or on a local Hardhat node (i.e a mocked corpocessor).

### Sepolia Testnet Deployment
1. Deploy the contract:
```bash
cd hardhat/
cp .env.example .env # Or use custom mnemonic
npm install
npm run test # to check if everything works as it should
npm run deploy-sepolia
```
npx hardhat node
```
> **Note:** Use your own private mnemonic in `.env`
This will also launch a mocked instance of the coprocessor.
2. Launch frontend:
```bash
cd frontend/
cp .env.example .env # Or use custom mnemonic
npm install
npm run dev
```

You can then go to the `frontend/` directory, and just run those two commands:
Access at [`http://localhost:4173/`](http://localhost:4173/)

### Local Development (Mocked Mode)
1. Setup local node:
```bash
cd hardhat/
cp .env.example .env # Or use custom mnemonic
npm install
npx hardhat node
```

2. Launch frontend:
```bash
cd frontend/
cp .env.example .env # Or use custom mnemonic
npm install
npm run dev-mocked
```

The dApp will be available again at: [`http://localhost:4173/`](http://localhost:4173/) . You can connect to the dApp with a Web3 wallet such as Metamask and start transferring tokens, reencrypt and read your balance, or request the decryption of the encrypted. This time, the only difference is that it will ask you to connect to the Hardhat network instead of Sepolia, so make sure to have added the Hardhat network to your Metamask wallet in order to be able to use the dApp with the mocked coprocessor. You can find instructions to configure Metamask adequatly [here](https://support.chainstack.com/hc/en-us/articles/4408642503449-Using-MetaMask-with-a-Hardhat-node).
Access at [`http://localhost:4173/`](http://localhost:4173/)

#### Troubleshooting

**_Invalid nonce errors:_** This is a common issue everytime you restart your local Hardhat node and you want to reuse the same accounts in Metamask. You should remember to reset the nonce of the accounts you used the last time with Hardhat. To reset the account's transaction history and the nonce, open Metamask and select the Hardhat network, click on your account followed by `Settings -> Advanced -> Clear activity tab data`.
**_Invalid nonce errors:_**
For invalid nonce errors after restarting Hardhat node:
1. Open Metamask
2. Select Hardhat network
3. Go to `Settings` -> `Advanced` -> `Clear activity tab data`

69 changes: 3 additions & 66 deletions hardhat/README.md
Original file line number Diff line number Diff line change
@@ -1,68 +1,9 @@
# Hardhat Template [![Open in Gitpod][gitpod-badge]][gitpod] [![Github Actions][gha-badge]][gha] [![Hardhat][hardhat-badge]][hardhat] [![License: MIT][license-badge]][license]

[gitpod]: https://gitpod.io/#https://github.com/zama-ai/fhevm-hardhat-template
[gitpod-badge]: https://img.shields.io/badge/Gitpod-Open%20in%20Gitpod-FFB45B?logo=gitpod
[gha]: https://github.com/zama-ai/fhevm-hardhat-template/actions
[gha-badge]: https://github.com/zama-ai/fhevm-hardhat-template/actions/workflows/ci.yml/badge.svg
[hardhat]: https://hardhat.org/
[hardhat-badge]: https://img.shields.io/badge/Built%20with-Hardhat-FFDB1C.svg
[license]: https://opensource.org/licenses/MIT
[license-badge]: https://img.shields.io/badge/License-MIT-blue.svg

A Hardhat-based template for developing Solidity smart contracts, with sensible defaults.

- [Hardhat](https://github.com/nomiclabs/hardhat): compile, run and test smart contracts
- [TypeChain](https://github.com/ethereum-ts/TypeChain): generate TypeScript bindings for smart contracts
- [Ethers](https://github.com/ethers-io/ethers.js/): renowned Ethereum library and wallet implementation
- [Solhint](https://github.com/protofire/solhint): code linter
- [Solcover](https://github.com/sc-forks/solidity-coverage): code coverage
- [Prettier Plugin Solidity](https://github.com/prettier-solidity/prettier-plugin-solidity): code formatter
# FhEVM Hardhat contracts examples

## Getting Started

Click the [`Use this template`](https://github.com/zama-ai/fhevm-hardhat-template/generate) button at the top of the
page to create a new repository with this repo as the initial state.

## Features

This template builds upon the frameworks and libraries mentioned above, so for details about their specific features,
please consult their respective documentations.

For example, for Hardhat, you can refer to the [Hardhat Tutorial](https://hardhat.org/tutorial) and the
[Hardhat Docs](https://hardhat.org/docs). You might be in particular interested in reading the
[Testing Contracts](https://hardhat.org/tutorial/testing-contracts) section.

### Sensible Defaults

This template comes with sensible default configurations in the following files:

```text
├── .editorconfig
├── .eslintignore
├── .eslintrc.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.yml
├── .solcover.js
├── .solhint.json
└── hardhat.config.ts
```

### VSCode Integration

This template is IDE agnostic, but for the best user experience, you may want to use it in VSCode alongside Nomic
Foundation's [Solidity extension](https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity).

### GitHub Actions
## Featured contracts

This template comes with GitHub Actions pre-configured. Your contracts will be linted and tested on every push and pull
request made to the `main` branch.

Note though that to make this work, you must use your `INFURA_API_KEY` and your `MNEMONIC` as GitHub secrets.

You can edit the CI script in [.github/workflows/ci.yml](./.github/workflows/ci.yml).

## Usage
## Getting Started

### Pre Requisites

Expand Down Expand Up @@ -200,10 +141,6 @@ npx hardhat verify-deployed --address [CONFIDENTIAL_ERC20_ADDRESS] --contract co

Note that you should replace the address placeholder `[CONFIDENTIAL_ERC20_ADDRESS]` by the concrete address that is logged when you run the `npm run deploy-sepolia` deployment script.

### Syntax Highlighting

If you use VSCode, you can get Solidity syntax highlighting with the
[hardhat-solidity](https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity) extension.

## License

Expand Down
Loading

0 comments on commit 71f25a4

Please sign in to comment.