Smart Contract Examples
Production-ready FHE smart contract templates. Copy, modify, and deploy these examples to build your own confidential applications.
Contract Examples
Choose an example to view the complete smart contract implementation
FHE Counter - Basic Example
Simple counter contract with encrypted state from Zama documentation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "fhevm/lib/TFHE.sol";
import "fhevm/abstracts/EIP712WithModifier.sol";
/// @title Counter
/// @notice A simple counter contract with encrypted state
/// @dev From Zama FHEVM documentation examples
contract Counter is EIP712WithModifier {
euint32 private _count;
address public owner;
event CounterUpdated(address indexed user);
constructor() EIP712WithModifier("Counter", "1") {
owner = msg.sender;
_count = TFHE.asEuint32(0);
}
/// @notice Increment the counter by an encrypted amount
/// @param encryptedAmount The encrypted amount to add
function increment(bytes calldata encryptedAmount)
external
onlySignedPublicKey
{
euint32 amount = TFHE.asEuint32(encryptedAmount);
_count = TFHE.add(_count, amount);
emit CounterUpdated(msg.sender);
}
/// @notice Get the encrypted counter value
/// @return The encrypted counter value
function getCounter() external view returns (bytes memory) {
return TFHE.reencrypt(_count, msg.sender);
}
/// @notice Get decrypted counter value (only owner)
/// @return The decrypted counter value
function getCounterDecrypted() external view returns (uint32) {
require(msg.sender == owner, "Only owner can decrypt");
return TFHE.decrypt(_count);
}
/// @notice Subtract from the counter
/// @param encryptedAmount The encrypted amount to subtract
function decrement(bytes calldata encryptedAmount)
external
onlySignedPublicKey
{
euint32 amount = TFHE.asEuint32(encryptedAmount);
_count = TFHE.sub(_count, amount);
emit CounterUpdated(msg.sender);
}
/// @notice Reset counter to zero (only owner)
function reset() external {
require(msg.sender == owner, "Only owner can reset");
_count = TFHE.asEuint32(0);
emit CounterUpdated(msg.sender);
}
}Key Features
Encrypted State
Counter value remains encrypted on-chain
TFHE Operations
Uses TFHE.add() and TFHE.sub() for encrypted math
Reencryption
Uses TFHE.reencrypt() for secure value access
Owner-only Decryption
Authorized decryption with TFHE.decrypt()
Quick Deploy
# Install Zama FHEVM dependencies
npm install @zama-fhe/relayer-sdk
# Compile FHE contracts
npx hardhat compile
# Deploy to Zama Devnet
npx hardhat run scripts/deploy.js --network fhevmTestnet
# Connect your wallet to Zama Devnet
Chain ID: 8009, RPC: https://devnet.zama.ai
Documentation
Comprehensive guides for FHE smart contract development
Templates
Starter templates for common FHE use cases
Live Examples
Test these contracts on the Fhenix testnet