Skip to content

Latest commit

 

History

History
477 lines (355 loc) · 15.4 KB

File metadata and controls

477 lines (355 loc) · 15.4 KB
description CommBank.eth - Privacy-enabled DeFi with Zero-Knowledge Proofs and Smart Contracts
globs *.ts, *.tsx, *.sol, *.nr, *.html, *.css, *.js, *.jsx, package.json
alwaysApply true

CommBank.eth Architecture & Development Guide

Project Overview

CommBank.eth is a privacy-enabled DeFi platform that facilitates private transfers across blockchains using zero-knowledge proofs. It's "the bank you don't have to trust" - allowing users to conduct private transactions while maintaining full custody of their assets.

Key Features:

  • Private asset transfers using ZK-SNARKs
  • Multi-asset support with Poseidon2 merkle trees
  • Cross-chain capabilities via Layer Zero
  • Encrypted note-based transaction model
  • Anonymous account model with separation of signing and owning keys

Monorepo Structure

This is a pnpm workspace monorepo with the following packages:

client/ - Next.js Frontend (Primary)

  • Status: Legacy/active development
  • Tech Stack: Next.js 14, React 18, Wagmi, RainbowKit, Tailwind CSS
  • Purpose: Web app deployed at https://commbank.eth.limo
  • Key Features:
    • Wallet integration (wagmi/ethers)
    • Token management and transfer UI
    • Account/profile management
    • Dark mode theme support with next-themes
    • Data fetching with TanStack React Query

client/ - Vite + React Frontend (In Development)

  • Status: Active development/migration target
  • Tech Stack: Vite, React 19, Vite + Tailwind CSS, React Router v7
  • Purpose: Modern replacement for the legacy client
  • Key Differences:
    • Vite for faster development
    • React Router instead of Next.js routing
    • Updated React dependencies
    • Simplified build process
  • Structure:
    • src/pages/ - Route components
    • src/components/ - Reusable UI components (account, send, profile, ui)
    • src/lib/ - Utility functions
    • src/hooks/ - Custom React hooks

contracts/ - Smart Contracts & Circuit Integration

  • Tech Stack: Solidity (0.8.21-0.8.27), Hardhat, TypeChain
  • Purpose: Core protocol implementation for private transfers
  • Key Components:
    • Smart Contracts (contracts/):
      • CommBankDotEth.sol - Main protocol contract
      • PrivateStargateFinance.sol - Cross-chain transfer logic
      • PrivateStargateOApp.sol - Layer Zero OApp integration
      • PoseidonMerkleTree.sol - ZK-friendly merkle tree
      • verifiers/ - Auto-generated verifier contracts from Noir circuits
        • DepositVerifier.sol, WithdrawVerifier.sol, TransferVerifier.sol, WarpVerifier.sol
      • utils/ - Cryptographic utilities (Poseidon2 hash, Field math)
      • mocks/ - Test mocks (USDC, LZOFT, etc.)
    • Tests (test/):
      • Hardhat test suite with Chai assertions
      • Tests for deposit, withdraw, transfer, note-sharing functionality
      • Uses custom testing API for circuit integration
    • Scripts (scripts/):
      • TypeScript build and deployment scripts
      • Circuit compilation and ABI extraction
      • IPFS deployment helpers
    • Helpers (helpers/):
      • Poseidon merkle tree implementation
      • Deposit/withdraw proof generation
      • Token approval utilities

circuits/ - Zero-Knowledge Circuits (Noir)

  • Tech Stack: Noir language v1.0.0-beta.16
  • Purpose: ZK-SNARK circuit definitions for private operations
  • Circuits:
    • deposit/ - Prove deposit commitment without revealing amount
    • withdraw/ - Prove withdrawal authorization
    • transfer/ - Prove private transfer between notes
    • warp/ - Cross-chain transfer proof
  • Circuit Features:
    • Use Poseidon2 hash function (merkle tree friendly)
    • Compile to JSON artifacts consumed by frontend & contracts
    • Verifiers auto-generated by Noir and integrated into smart contracts
  • Build Output:
    • target/deposit.json - Compiled circuit artifact
    • target/vk - Verification key
    • Consumed by frontend via @noir-lang/noir_js for proof generation

shared/ - Shared Types & Utilities

  • Purpose: Cross-package shared code (TypeScript only)
  • Exports:
    • shared/classes/* - Circuit and transaction classes
      • Note.ts - Note representation (currently placeholder)
      • Deposit.ts - Deposit circuit wrapper using Noir + Aztec BB
      • Withdraw.ts - Withdraw circuit wrapper
      • Transact.ts - Transfer circuit wrapper
    • shared/constants/* - Shared constants
      • token.ts - Token definitions
  • Import Path: Use shared-package/* in workspace packages (e.g., import { Deposit } from 'shared-package/classes/Deposit')
  • Dependencies: References contracts workspace for ABI types

server/ - Backend (Next.js, WIP)

  • Status: Work in progress
  • Purpose: Price data aggregation and transaction relaying
  • Current Tech: Next.js 15, React 19
  • Planned Features:
    • CoinGecko price data API
    • Transaction relay service for gas optimization

Common Development Commands

Root Level (Monorepo)

# Install all dependencies
pnpm install

# Format all code
pnpm run format

# Check formatting
pnpm run format:check

# Lint all code
pnpm run lint

# Fix lint errors
pnpm run lint:fix

# Start development (runs client by default)
pnpm run dev

# Build client
pnpm run build

# Build contracts and generate verifiers
pnpm run build-contracts

Client (Next.js)

cd client
pnpm run dev      # Start dev server on localhost:3000
pnpm run build    # Production build
pnpm run start    # Run production build
pnpm run lint     # Next.js linting

client (Vite + React Router)

cd client
pnpm run dev      # Start Vite dev server
pnpm run build    # Build with TypeScript + Vite
pnpm run preview  # Preview production build
pnpm run lint     # ESLint check

Contracts

cd contracts
pnpm run build                # Build verifiers from circuits (primary build command)
pnpm run build-bb            # Compile Noir circuits to bytecode

# Testing
npx hardhat test            # Run all tests
npx hardhat test test/deposit.test.ts  # Run specific test
npx hardhat test --grep "pattern"      # Run tests matching pattern

# Network interaction
npx hardhat run scripts/deploy.ts --network arbitrumOne
npx hardhat run scripts/deploy.ts --network base
npx hardhat run scripts/deploy.ts --network mainnet

Circuits (Noir)

cd circuits/deposit
nargo build             # Compile to target/deposit.json
nargo prove             # Create proof from Prover.toml
nargo verify            # Verify proof with vk

Architecture Patterns

Private Transfer Model

The protocol implements a note-based private transfer system:

  1. User Account Model:

    • Each user has an EVM wallet derived from a mnemonic (stored in passkey)
    • Signing Key: User's public key (used for note encryption/decryption)
    • Owning Key: poseidon2(wallet.privateKey) (used for ZK ownership proofs)
  2. Note Lifecycle:

    • Deposit: User commits USDC → encrypted note in merkle tree
    • Transfer: Prove note ownership → create new note for recipient
    • Withdraw: Prove note ownership → redeem to EVM address
  3. Zero-Knowledge Proofs:

    • Each operation (deposit/transfer/withdraw) has a corresponding Noir circuit
    • Circuits prove facts without revealing sensitive data (amounts, owners)
    • Verifiers auto-generated from circuits and deployed on-chain
    • Frontend generates proofs using @noir-lang/noir_js + Aztec Barretenberg backend

Shared Package Architecture

The shared package bridges circuit logic and frontend:

// Usage pattern in client or contracts
import { Deposit } from "shared-package/classes/Deposit";

const deposit = new Deposit();
// Uses Noir + UltraHonkBackend to generate proofs
const proof = await deposit.depositNoir.generateProof(inputs);

Key Classes:

  • Deposit - Wraps deposit circuit (Noir + UltraHonkBackend)
  • Withdraw - Wraps withdraw circuit
  • Transact - Wraps transfer circuit
  • All use @noir-lang/noir_js for proof generation
  • All use @aztec/bb.js (UltraHonkBackend) for proof verification

Smart Contract Structure

Core Contracts:

  • CommBankDotEth.sol - Main entry point, manages notes and state
  • PoseidonMerkleTree.sol - ZK-friendly merkle tree for commitments
  • PrivateStargateFinance.sol - Liquidity pool for private transfers
  • Auto-generated verifier contracts validate ZK proofs

Testing Pattern:

  • getTestingAPI() helper sets up contracts, signers, and utilities
  • Tests use PoseidonMerkleTree for computing expected tree state
  • Proof generation via getDepositDetails() and similar helpers

Frontend State Management

Client (Next.js):

  • Wagmi for wallet connection and contract interaction
  • TanStack React Query for data fetching
  • Zustand for global state (likely in newer versions)
  • Theme support via next-themes

client (Vite):

  • React Router for navigation
  • Form handling with react-hook-form
  • TanStack React Query for data management
  • Tailwind CSS + Radix UI for components

Code Quality & Formatting

ESLint Configuration

  • Config: eslint.config.mjs at root (modern flat config)
  • Rules: TypeScript + Prettier plugin integration
  • Ignored Paths: node_modules, dist, build, .next, out
  • Run: pnpm run lint and pnpm run lint:fix

Prettier Configuration

  • Config: .prettierrc at root
  • Settings:
    • Semicolons: enabled
    • Trailing commas: all
    • Single quotes: false (use double quotes)
    • Print width: 80 characters
    • Tab width: 2 spaces
  • Run: pnpm run format and pnpm run format:check

TypeScript Configuration

Client (Next.js):

  • Target: ES2017, DOM + DOM.iterable + ES modules
  • Module: ESNext with bundler resolution
  • Strict mode enabled
  • Incremental builds
  • Path aliases: @/* → project root

client:

  • Dual tsconfig: app (src) and node configs
  • Path aliases: @/*src/*
  • Strict type checking

Contracts:

  • Target: modern ES for Node.js tooling
  • Reference from hardhat config
  • Used for script and test compilation

Build Artifacts & Outputs

Circuit Artifacts

  • Location: circuits/*/target/
  • Files: *.json (compiled circuit), vk (verification key)
  • Consumed By: Frontend (Noir.js) and verifier contract generation

Contract Verifiers

  • Auto-generated: contracts/contracts/verifiers/*.sol
  • Generated From: Noir circuit artifacts
  • Build Process: scripts/ts-sol-verifier-create.ts
  • Usage: On-chain proof validation in CommBankDotEth

TypeChain Types

  • Location: contracts/typechain-types/
  • Purpose: Type-safe contract interactions in tests and frontend
  • Generated From: Contract ABIs via hardhat-typechain

Important Conventions

Circuit Development

  1. Define circuit logic in Noir (*.nr files)
  2. Use Poseidon2 for merkle trees (ZK-friendly)
  3. Compile with nargo build
  4. Auto-generated verifier is integrated into contracts

Smart Contract Testing

  1. Use Hardhat with ethers v6
  2. Leverage getTestingAPI() for test setup
  3. Use Chai assertions with hardhat-chai-matchers
  4. Tests timeout: 40 seconds (configured in hardhat.config.ts)

Frontend Development

  • Client uses Next.js 14 with wagmi/rainbowkit
  • client uses Vite with React Router
  • Both use Tailwind CSS and Radix UI components
  • Shared utilities via shared-package imports
  • State management via wagmi (contracts) + TanStack Query (data)

Cross-chain Integration

  • Layer Zero integration for cross-chain messages
  • Stargate for liquidity bridging
  • Multi-network support: Ethereum, Arbitrum, Base
  • Network configuration in hardhat.config.ts

Key Dependencies

Frontend

  • Web3: wagmi, viem, ethers, @rainbow-me/rainbowkit
  • UI: @radix-ui/*, lucide-react, framer-motion, sonner (toast)
  • Forms: react-hook-form (client)
  • Utilities: TanStack React Query, zustand, class-variance-authority
  • Styling: Tailwind CSS, tailwind-merge
  • Crypto: @noir-lang/noir_js (proof generation)

Contracts

  • Testing: Hardhat, Chai, hardhat-chai-matchers
  • Compilation: TypeChain, hardhat-compile
  • ZK: @noir-lang/noir_js, @aztec/bb.js
  • Crypto: @openzeppelin/contracts (ERC20, Ownable, etc.)
  • Cross-chain: @layerzerolabs/lz-evm-v2, Stargate
  • Utils: ethers, merkletreejs, eciesjs

Circuits

  • Language: Noir v1.0.0-beta.16
  • Dependencies: Poseidon (noir-lang/poseidon)
  • Proving: Aztec Barretenberg backend via bb.js

Environment Configuration

Required ENV Variables (in contracts/.env):

  • ALCHEMY_API_KEY - Alchemy RPC access
  • ETHERSCAN_API_KEY - Ethereum contract verification
  • BASESCAN_API_KEY - Base contract verification
  • ARBISCAN_API_KEY - Arbitrum contract verification
  • PRIVATE_KEY - Deployment account key
  • DEMO_MNEMONIC_ALICE - Test wallet mnemonic

Loading ENV: Use dotenv or configure your shell to load .env files

Testing Overview

Smart Contract Tests

  • Location: contracts/test/*.test.ts
  • Runner: Hardhat (mocha-based)
  • Test Cases:
    • deposit.test.ts - Note creation and commitment
    • withdraw.test.ts - Note redemption
    • transfer.test.ts - Private transfers
    • note-sharing.test.ts - Note encryption patterns

Circuit Tests

  • Proofs generated and verified in TypeScript (via @noir-lang/noir_js)
  • Tests use circuit artifacts from circuits/*/target/
  • Proof verification via Aztec Barretenberg backend

Frontend Tests

  • Not yet configured (opportunity for vitest/jest setup)

Documentation References

  • AUTH.md - Account model details, signing/owning key separation, note encryption
  • Circuit Build: See scripts/bash/build-and-export-circuits.sh
  • Deployment: See scripts/deploy.ts and scripts/ts-sol-verifier-create.ts

Development Tips

Running client Locally

  1. cd client
  2. pnpm install (if dependencies changed)
  3. pnpm run dev - Opens at http://localhost:5173
  4. Changes auto-reload (Vite HMR)

Debugging Proofs

  1. Check circuit inputs in helpers/functions/deposit.ts
  2. Verify Poseidon2 hash outputs match expected values
  3. Use hardhat console for contract state inspection
  4. Check merkle tree leaf insertion order

Deploying to Testnets

  1. Ensure proper ENV variables are set
  2. Verify circuit artifacts are built (pnpm run build-contracts)
  3. Run: npx hardhat run scripts/deploy.ts --network <network-name>
  4. Network names: hardhat, mainnet, arbitrumOne, base

Working with Shared Package

  • Always import as shared-package/* (not relative paths)
  • Changes to shared require re-running pnpm install in dependent packages
  • Shared uses workspace:* to link to contracts package

Notable Design Decisions

  1. Separate Circuits: Each operation (deposit/withdraw/transfer/warp) has its own circuit for optimization
  2. Poseidon2: Used for merkle trees because it's ZK-circuit native (cheaper proofs)
  3. Encrypted Notes: Notes encrypted with user's public key, enabling note passing without on-chain storage
  4. Two Keys: Signing key (public key) and owning key (poseidon hash) allow efficient ZK proofs vs on-chain encryption
  5. TypeChain Integration: Type-safe contract ABIs prevent runtime errors during tests
  6. pnpm Workspaces: Efficient disk space usage with symlinked node_modules; strict dependency resolution

Known Limitations & WIPs

  • Server backend (price data, tx relay) is work-in-progress
  • Note class placeholders pending full implementation
  • Frontend tests not yet configured
  • Disaster recovery documentation in client (see DISASTER_RECOVERY.md)
  • Circuit optimization ongoing (runs: 100 hardhat setting is conservative)