Skip to content

Repository files navigation

Privacy-Preserving DCA Bot with TEE Authorized Relayer

Overview

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.

Key Features

  • 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

Architecture

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]
Loading

Detailed architecture and implementation in the technical design.

Quick Start

Prerequisites

  • Node.js 18+
  • Hardhat development environment
  • Access to Sepolia testnet
  • Zama FHEVM setup

Installation

# 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 init

Environment Setup

Create .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 Router

Hardhat Configuration

Your 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;

Testing

The project includes comprehensive test suites across three categories:

Unit Tests

# Core contract functionality
npx hardhat test test/unit/PrivacyDCABot.test.ts

# Run with FHE mocked mode (faster)
npx hardhat test --network hardhat

Integration Tests

# End-to-end user flow
npx hardhat test test/integration/EndToEndFlow.test.ts

Privacy Tests

# k-anonymity verification
npx hardhat test test/privacy/AnonymityTests.test.ts

Running All Tests

# 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 sepolia

FHEVM Runtime Modes

The tests support three FHEVM runtime modes:

  1. In-Memory Mode (fastest, for unit tests)
npx hardhat test --network hardhat
  1. Localhost Mode (local FHEVM node)
npx hardhat node
npx hardhat test --network localhost
  1. Sepolia Mode (testnet deployment)
npx hardhat test --network sepolia

Contract Interface

Core Functions

Submit DCA Intent

function submitDCAIntent(
    externalEuint64 inputEuint64Amount,
    bytes calldata inputProofAmount,
    externalEuint64 inputEuint64Intervals,
    bytes calldata inputProofIntervals,
    externalEuint64 inputEuint64Frequency,
    bytes calldata inputProofFrequency
) external

Execute Batch (Relayer Only)

function executeRelayerSwap(
    uint256 batchId,
    uint256 decryptedAggregateAmount,
    bytes calldata teeProof
) external onlyRole(RELAYER_ROLE)

Batch Management

function forceAdvanceBatch() external
function getBatchInfo(uint256 batchId) external view returns (...)
function getCurrentBatchStatus() external view returns (...)

Privacy Guarantees

What Remains Private ✓

  • 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

What's Visible On-Chain ✕

  • Aggregate batch swap amounts
  • Number of participants per batch
  • Batch execution timestamps
  • User addresses (but not linked to amounts)

Security Properties

  • k-Anonymity: Minimum 5 users per batch
  • MEV Resistance: Encrypted intent submission
  • TEE Protection: Hardware-secured relayer operations
  • Access Control: Role-based execution permissions

Deployment

Local Development

# Start local FHEVM node
npx hardhat node

# Deploy contracts
npx hardhat run scripts/deploy.ts --network localhost

Sepolia Testnet

# Deploy to Sepolia
npx hardhat run scripts/deploy.ts --network sepolia

# Verify contracts
npx hardhat verify --network sepolia <CONTRACT_ADDRESS>

Production Setup

  1. Deploy contracts with multi-sig admin
  2. Setup TEE-secured relayer infrastructure
  3. Configure Chainlink Keepers for automation
  4. Initialize with USDC/ETH token addresses

Usage Examples

Basic DCA Strategy

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,
);

Advanced Strategies

// "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);

Gas Optimization

Batch Size vs Cost Analysis

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%

Execution Costs

  • Intent Submission: ~100k gas per user
  • Batch Execution: ~200k gas total
  • Token Distribution: ~50k gas per user

Security Considerations

Smart Contract Security

  • Reentrancy guards on all external calls
  • Role-based access control
  • Input validation and overflow protection
  • Emergency pause mechanisms

Privacy Security

  • No individual data exposure in events
  • Uniform gas consumption patterns
  • Encrypted storage for all sensitive data
  • TEE attestation for relayer operations

Operational Security

  • Multi-signature admin controls
  • Relayer rotation capabilities
  • Comprehensive audit trails
  • Incident response procedures

Batch Execution Flow

  1. Intent Collection: Users submit encrypted DCA parameters
  2. Batch Formation: Contract aggregates 5-20 intents or timeout
  3. FHE Aggregation: Homomorphic addition of encrypted amounts
  4. Relayer Decryption: TEE-secured aggregate decryption
  5. DEX Execution: Single USDC → ETH swap on Uniswap V3
  6. Distribution: Proportional ETH allocation using FHE
  7. Settlement: Users receive ETH tokens in wallets

Monitoring & Analytics

On-Chain Metrics

  • Batch execution frequency
  • Average batch size
  • Total volume processed
  • Gas efficiency metrics

Privacy 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.

About

A fully decentralized, privacy-focused bot for executing Dollar-Cost Averaging (DCA) strategies without revealing trade sizes or patterns, powered by Zama’s FHEVM.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages