A privacy-focused Dollar-Cost Averaging (DCA) bot that executes automated token purchases while maintaining complete user privacy through Fully Homomorphic Encryption (FHE) and k-anonymity batching. Built on Zama's FHEVM protocol with TEE-secured authorized relayers.
- End-to-End Privacy: DCA amounts, intervals, and strategies encrypted client-side
- k-Anonymity: Individual trades hidden within batches of 5-20 users
- MEV Protection: Encrypted intents prevent front-running attacks
- TEE Security: Authorized relayers with hardware-level protection
- Gas Optimization: Batched execution reduces per-user costs by ~50%
- Automated Execution: Chainlink Keepers for decentralized batch triggers
graph TD
A[User Frontend] --> B[Encrypt DCA Parameters]
B --> C[FHEVM Smart Contract]
C --> D[FHE Batch Aggregation]
D --> E[TEE Authorized Relayer]
E --> F[Decrypt Aggregate Only]
F --> G[Uniswap V3 Swap]
G --> H[Proportional Distribution]
H --> I[User Wallets]
Detailed architecture and implementation in the technical design.
- Node.js 18+
- Hardhat development environment
- Access to Sepolia testnet
- Zama FHEVM setup
# Clone repository
git clone https://github.com/0xBurpberly/fhe-dca-bot
cd fhe-dca-bot
# Install dependencies
npm install
# Install Hardhat and FHEVM plugin
npm install --save-dev hardhat
npm install --save-dev @fhevm/hardhat-plugin
# Initialize Hardhat configuration
npx hardhat initCreate .env file:
# Sepolia testnet (optional - falls back to defaults)
MNEMONIC="your twelve word mnemonic phrase here"
INFURA_API_KEY="your_infura_api_key_here"
# Contract addresses (will be populated after deployment)
DCA_BOT_ADDRESS=""
USDC_ADDRESS="0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238" # Sepolia USDC
ETH_TOKEN_ADDRESS="0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9" # Sepolia WETH
SWAP_ROUTER_ADDRESS="0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E" # Uniswap V3 RouterYour hardhat.config.ts should include FHEVM setup:
import { HardhatUserConfig } from "hardhat/config";
import "@fhevm/hardhat-plugin";
import "@nomicfoundation/hardhat-toolbox";
const config: HardhatUserConfig = {
solidity: "0.8.24",
networks: {
sepolia: {
url: `https://sepolia.infura.io/v3/${process.env.INFURA_API_KEY}`,
accounts: {
mnemonic: process.env.MNEMONIC,
},
},
},
};
export default config;The project includes comprehensive test suites across three categories:
# Core contract functionality
npx hardhat test test/unit/PrivacyDCABot.test.ts
# Run with FHE mocked mode (faster)
npx hardhat test --network hardhat# End-to-end user flow
npx hardhat test test/integration/EndToEndFlow.test.ts# k-anonymity verification
npx hardhat test test/privacy/AnonymityTests.test.ts# Run complete test suite
npm test
# Run with coverage
npx hardhat coverage
# Run on different networks
npx hardhat test --network localhost
npx hardhat test --network sepoliaThe tests support three FHEVM runtime modes:
- In-Memory Mode (fastest, for unit tests)
npx hardhat test --network hardhat- Localhost Mode (local FHEVM node)
npx hardhat node
npx hardhat test --network localhost- Sepolia Mode (testnet deployment)
npx hardhat test --network sepoliafunction submitDCAIntent(
externalEuint64 inputEuint64Amount,
bytes calldata inputProofAmount,
externalEuint64 inputEuint64Intervals,
bytes calldata inputProofIntervals,
externalEuint64 inputEuint64Frequency,
bytes calldata inputProofFrequency
) externalfunction executeRelayerSwap(
uint256 batchId,
uint256 decryptedAggregateAmount,
bytes calldata teeProof
) external onlyRole(RELAYER_ROLE)function forceAdvanceBatch() external
function getBatchInfo(uint256 batchId) external view returns (...)
function getCurrentBatchStatus() external view returns (...)- Individual DCA amounts (encrypted end-to-end)
- Purchase frequencies and intervals
- Total user budgets and strategies
- Trading patterns and timing preferences
- Portfolio compositions and wealth levels
- Aggregate batch swap amounts
- Number of participants per batch
- Batch execution timestamps
- User addresses (but not linked to amounts)
- k-Anonymity: Minimum 5 users per batch
- MEV Resistance: Encrypted intent submission
- TEE Protection: Hardware-secured relayer operations
- Access Control: Role-based execution permissions
# Start local FHEVM node
npx hardhat node
# Deploy contracts
npx hardhat run scripts/deploy.ts --network localhost# Deploy to Sepolia
npx hardhat run scripts/deploy.ts --network sepolia
# Verify contracts
npx hardhat verify --network sepolia <CONTRACT_ADDRESS>- Deploy contracts with multi-sig admin
- Setup TEE-secured relayer infrastructure
- Configure Chainlink Keepers for automation
- Initialize with USDC/ETH token addresses
import { fhevm, ethers } from "hardhat";
// User wants to DCA $1000 USDC into ETH over 10 days
const amount = 1000;
const intervals = 10;
const frequency = 86400; // Daily
// Encrypt parameters client-side
const encryptedAmount = await fhevm.createEncryptedInput(dcaBotAddress, userAddress).add64(amount).encrypt();
const encryptedIntervals = await fhevm.createEncryptedInput(dcaBotAddress, userAddress).add64(intervals).encrypt();
const encryptedFrequency = await fhevm.createEncryptedInput(dcaBotAddress, userAddress).add64(frequency).encrypt();
// Submit intent to contract
await dcaBot.submitDCAIntent(
encryptedAmount.handles[0],
encryptedAmount.inputProof,
encryptedIntervals.handles[0],
encryptedIntervals.inputProof,
encryptedFrequency.handles[0],
encryptedFrequency.inputProof,
);// "Buy the dip" strategy with dynamic amounts
const baseAmount = 1000;
const dipMultiplier = 2; // Double on 3% drops
const condition = "ETH_DROP_3PCT";
// These would be encoded in encrypted parameters
const encryptedStrategy = await encryptDynamicStrategy(baseAmount, dipMultiplier, condition);| Batch Size | Gas per User | Cost Savings |
|---|---|---|
| 1 (individual) | ~300k gas | 0% |
| 5 (minimum) | ~180k gas | 40% |
| 10 (optimal) | ~150k gas | 50% |
| 20 (maximum) | ~130k gas | 57% |
- Intent Submission: ~100k gas per user
- Batch Execution: ~200k gas total
- Token Distribution: ~50k gas per user
- Reentrancy guards on all external calls
- Role-based access control
- Input validation and overflow protection
- Emergency pause mechanisms
- No individual data exposure in events
- Uniform gas consumption patterns
- Encrypted storage for all sensitive data
- TEE attestation for relayer operations
- Multi-signature admin controls
- Relayer rotation capabilities
- Comprehensive audit trails
- Incident response procedures
- Intent Collection: Users submit encrypted DCA parameters
- Batch Formation: Contract aggregates 5-20 intents or timeout
- FHE Aggregation: Homomorphic addition of encrypted amounts
- Relayer Decryption: TEE-secured aggregate decryption
- DEX Execution: Single USDC → ETH swap on Uniswap V3
- Distribution: Proportional ETH allocation using FHE
- Settlement: Users receive ETH tokens in wallets
- Batch execution frequency
- Average batch size
- Total volume processed
- Gas efficiency metrics
- k-anonymity distribution
- Timing variance analysis
- MEV protection effectiveness
- Data leakage detection
Built for Zama Bounty Program Season 9 - advancing privacy-preserving DeFi through Fully Homomorphic Encryption.