@claritydao/midnight-agora-contracts
v1.1.1
Published
A comprehensive decentralized autonomous organization (DAO) governance system implemented in Compact for the Midnight blockchain. This module contains all smart contracts that enable stakeholders to propose, vote on, and execute governance decisions throu
Keywords
Readme
Agora DAO - Smart Contracts
A comprehensive decentralized autonomous organization (DAO) governance system implemented in Compact for the Midnight blockchain. This module contains all smart contracts that enable stakeholders to propose, vote on, and execute governance decisions through a decentralized, privacy-preserving, and trustless process.
🏗️ Architecture
The Agora DAO system is built with a modular architecture, separating concerns across multiple Compact modules:
Contract Structure
/src
├── contracts/
│ ├── DAO/
│ │ ├── Governor.compact # Main governance coordinator
│ │ ├── StakeModule.compact # Stake management and delegation
│ │ ├── ProposalModule.compact # Proposal lifecycle and voting
│ │ ├── EffectModule.compact # Effect execution and processing
│ │ └── TreasuryModule.compact # Treasury management and controls
│ ├── utils/
│ │ ├── TypesModule.compact # Shared data structures and enums
│ │ ├── Utils.compact # Common utility functions
│ │ ├── Initializable.compact # Initialization control pattern
│ │ └── Pausable.compact # Emergency pause functionality
│ └── fungibleToken/
│ └── FungibleToken.compact # Token implementation
├── test/
│ ├── governance-simulator.ts # Local testing simulator
│ └── governor-contract.test.ts # Comprehensive test suite
└── witnesses.ts # Private state management📋 Core Contracts
📋 Complete Technical Documentation: See Contract Documentation for detailed specifications of all smart contracts, circuits, and data structures.
1. Governor Contract (Governor.compact)
Purpose: Central orchestrator for all governance operations
Key Circuits:
createProposalWithEffect()- Submit governance proposals with effectscastVoteWithValidation()- Cast votes with ZK proof verificationfinalizeProposalWithValidation()- Finalize proposals after votingqueueProposalWithValidation()- Queue proposals for executionexecuteEffectWithValidation()- Execute approved effects
State Management:
governorConfig- Governance parameters and thresholdsactiveProposalCount- Active proposal trackingqueuedProposalCount- Queued proposal trackinggovernorPermissions- Admin and user permissions
2. StakeModule Contract (StakeModule.compact)
Purpose: Manages user stakes and voting power calculation
Key Circuits:
registerStakeWithValidation()- Register user stakeswithdrawStakeWithValidation()- Withdraw stakes with validationdelegateStakeWithValidation()- Delegate voting powergetStakeInfo()- Query stake informationhasProposalThreshold()- Check proposal creation eligibility
State Management:
stakes- Individual user stake recordsdelegations- Delegation mappingstotalStakes- Aggregate stake totalsgovernanceConfig- Staking parameters
3. ProposalModule Contract (ProposalModule.compact)
Purpose: Handles complete proposal lifecycle from creation to execution
Proposal States:
- Active → Succeeded/Defeated → Queued → Executed
Key Circuits:
createProposal()- Create new governance proposalscastVote()- Record votes with double-vote preventionfinalizeProposal()- Calculate results and update statusgetProposal()- Query proposal details and status
State Management:
proposals- Proposal records with full lifecycle datavoteRecords- Individual vote recordsproposalCounter- Unique proposal ID generation
4. EffectModule Contract (EffectModule.compact)
Purpose: Processes and executes governance effects
Effect Types:
- MintToken: Create new tokens for treasury
- Transfer: Move tokens between accounts
- UpdateConfig: Modify governance parameters
Key Circuits:
createEffect()- Create executable effectsexecuteEffect()- Execute approved effectscancelEffect()- Cancel pending effectsbatchExecuteEffects()- Execute multiple effects
5. TreasuryModule Contract (TreasuryModule.compact)
Purpose: Manages DAO treasury operations and fund controls
Key Circuits:
depositToTreasury()- Add funds to treasurywithdrawFromTreasury()- Remove funds with approvalgetTreasuryBalance()- Query treasury balancestransferTreasuryTokens()- Internal treasury transfers
State Management:
treasuryBalances- Multi-token balance trackingtreasuryTransactions- Complete transaction historytreasuryStatistics- Aggregate treasury metrics
🔄 Governance Workflow
The complete governance process follows this workflow:
flowchart TD
A[Register Stake] --> B[Create Proposal]
B --> C[Voting Period]
C --> D[Finalize Proposal]
D --> E[Queue for Execution]
E --> F[Execute Effects]
F --> G[Update Treasury/Config]
style A fill:#e1f5fe
style B fill:#f3e5f5
style C fill:#fff3e0
style D fill:#e8f5e8
style E fill:#fff8e1
style F fill:#fce4ec
style G fill:#f1f8e9Complete Governance Process
Stake Registration (
registerStakeWithValidation)- Users register stake to gain voting power
- ZK proof validates stake ownership
- Minimum stake requirements enforced
Proposal Creation (
createProposalWithEffect)- Users with sufficient stake create proposals
- Proposals linked to executable effects
- Timing parameters set (voting start/end)
Voting Period (
castVoteWithValidation)- Community votes on active proposals
- Stake-weighted voting power
- Double-vote prevention enforced
Proposal Finalization (
finalizeProposalWithValidation)- Vote tallying and result calculation
- Status transition (Succeeded/Defeated)
- Quorum and threshold validation
Execution Queue (
queueProposalWithValidation)- Successful proposals queued for execution
- Execution delay enforced for security
- Admin approval mechanisms
Effect Execution (
executeEffectWithValidation)- Approved effects executed with proofs
- Treasury operations performed
- Configuration updates applied
State Updates
- Treasury balances updated
- Governance parameters modified
- Transaction history recorded
🔐 Security Features
📋 Complete Security Documentation: See Contract Documentation for detailed security model and threat analysis.
Zero-Knowledge Proof Security
- ProofOfStake: Validates stake ownership without revealing amounts
- ProofOfGovernorApproval: Authorizes governance actions with privacy
- ProofOfEffectExecution: Validates execution rights securely
- Nonce-based Replay Protection: Prevents proof reuse attacks
Access Control Framework
- Stake-weighted Voting: Voting power proportional to stake
- Proposal Thresholds: Minimum stake required for proposal creation
- Admin Permissions: Role-based access for critical operations
- Time-locked Execution: Security delays before effect execution
- Emergency Controls: Veto mechanisms for critical situations
Anti-Manipulation Safeguards
- Double-vote Prevention: Cryptographic prevention of vote duplication
- Proposal Lifetime Limits: Time bounds prevent stale proposals
- Quorum Requirements: Minimum participation for valid decisions
- Voting Period Enforcement: Strict timing for proposal phases
- Effect Validation: Comprehensive validation before execution
- Treasury Protection: Multi-layered spending controls
📊 Key Features
Configurable Governance Parameters
- Voting Period:
300s(5 minutes for testing) - Duration for proposal voting - Quorum Threshold:
100,000tokens - Minimum participation required - Proposal Threshold:
50,000tokens - Minimum stake to create proposals - Proposal Lifetime:
86,400s(1 day) - Maximum proposal validity - Execution Delay:
60s(1 minute) - Security delay before execution - Grace Period:
300s(5 minutes) - Window for effect execution - Emergency Veto: Community override with higher threshold
Effect Action Types
- MintToken (
EffectActionType.MintToken)- Create new tokens for treasury or recipients
- Configurable amounts and recipients
- Treasury balance tracking
- Transfer (
EffectActionType.Transfer)- Move tokens between accounts
- Treasury to external transfers
- Multi-token support
- UpdateConfig (
EffectActionType.UpdateConfig)- Modify governance parameters
- Update thresholds and periods
- Admin permission changes
Advanced Treasury Features
- Multi-token Support: Handle various token types
- Balance Tracking: Real-time treasury monitoring
- Transaction History: Complete audit trail
- Spending Controls: Authorized withdrawal limits
- Emergency Freeze: Pause capabilities for security
- Statistics Tracking: Usage and performance metrics
🧪 Testing & Validation
📋 Complete Test Documentation: See Test Scenarios and Results for comprehensive testing analysis and results.
Test Coverage
- Unit Tests: 95.8% function coverage (137/143 functions)
- Integration Tests: Real blockchain interaction testing
- Fuzz Testing: Property-based testing with random inputs
- Edge Cases: Boundary conditions and error scenarios
Test Results
- Total Tests: 125 tests across unit and integration suites
- Success Rate: 99.2% (124/125 tests passing)
- Execution Time: ~47 minutes total (~45 min integration due to blockchain)
- Coverage: 95.1% overall code coverage
Testing Infrastructure
- GovernanceSimulator: Local contract testing without blockchain
- Integration Environment: Real testnet interaction
- Automated Testing: Continuous validation pipeline
- Performance Monitoring: Load and stress testing
🛠️ Implementation Notes
Compact Language Features
- Ledger State: Persistent on-chain state storage
- Pure Circuits: ZK-proof-enabled functions with validation
- Witness Functions: Private input handling for proofs
- Structs and Enums: Type-safe data structures
- Vector<N, T>: Fixed-size array operations
- Map<K, V>: Key-value state storage
- Assert Statements: Validation and constraint enforcement
Architecture Principles
- Modularity: Clear separation of concerns across contracts
- Composability: Contracts work together seamlessly
- Type Safety: Strict typing prevents runtime errors
- ZK-Native: Built-in zero-knowledge proof integration
- Configurable: Parameter-driven governance customization
- Upgradeable: Admin-controlled configuration updates
🚀 Usage Examples
Complete Governance Flow Example
1. Register Stake
// User registers stake to participate in governance
registerStakeWithValidation(
userId,
50000, // 50K tokens
ProofOfStake {
userId: userId,
amount: 50000,
nonce: randomNonce
}
);2. Create Proposal with Effects
// Create proposal with multiple effects
const actions = Vector<10, EffectAction> {
EffectAction {
typ: EffectActionType.MintToken,
token: treasuryToken,
amount: 10000,
to: developmentFund,
configKey: emptyBytes,
configValue: emptyBytes
},
EffectAction {
typ: EffectActionType.Transfer,
token: treasuryToken,
amount: 5000,
to: marketingFund,
configKey: emptyBytes,
configValue: emptyBytes
}
// ... up to 10 actions
};
const proposalId = createProposalWithEffect(
creatorUserId,
"Treasury Allocation Q1",
"Allocate funds for development and marketing",
actions,
ProofOfStake { userId: creatorUserId, amount: 50000, nonce: randomNonce },
currentTime, // voting start
currentTime + 300 // voting end (5 minutes)
);3. Cast Votes
// Multiple users vote on the proposal
castVoteWithValidation(
proposalId,
voter1UserId,
VoteChoice.For,
ProofOfStake { userId: voter1UserId, amount: 75000, nonce: randomNonce }
);
castVoteWithValidation(
proposalId,
voter2UserId,
VoteChoice.Against,
ProofOfStake { userId: voter2UserId, amount: 25000, nonce: randomNonce }
);4. Execute Governance Pipeline
// After voting period ends, finalize proposal
finalizeProposalWithValidation(proposalId);
// Queue for execution with delay
queueProposalWithValidation(proposalId);
// Execute effects after delay period
executeEffectWithValidation(
effectId,
ProofOfGovernorApproval {
proposalId: proposalId,
effectId: effectId,
approvalTime: currentTime,
nonce: randomNonce
}
);🔧 Development & Deployment
Build & Test Commands
# Install dependencies
npm install
# Build contracts
npm run build
# Run unit tests
npm test
# Run unit tests with coverage
npm run test:coverage
# Clean build artifacts
npm run cleanDevelopment Status
✅ Completed Components:
- [x] All core governance contracts (Governor, Stake, Proposal, Effect, Treasury)
- [x] Comprehensive type system and utilities
- [x] Zero-knowledge proof integration
- [x] Complete test suite with 95.8% coverage
- [x] Local testing simulator
- [x] Integration test infrastructure
- [x] CLI interface for contract interaction
✅ Quality Assurance:
- [x] Unit testing (95.8% function coverage)
- [x] Integration testing (real blockchain interaction)
- [x] Fuzz testing (property-based validation)
- [x] Edge case testing (boundary conditions)
- [x] Performance testing (load and stress tests)
Production Readiness
- Security: ZK-proof validation, access controls, time locks
- Testing: Comprehensive test suite with high coverage
- Documentation: Complete technical and API documentation
- Performance: Optimized for Midnight blockchain efficiency
- Monitoring: Built-in metrics and audit trails
📚 Documentation
Contract-Specific Documentation
- Technical Specifications: Detailed contract architecture
- Test Results: Comprehensive testing analysis
- Module Details: CLI and component documentation
Getting Started
- Setup: Install dependencies and build contracts
- Testing: Run unit and integration test suites
- Deployment: Use CLI for contract deployment
- Interaction: Use provided API for governance operations
📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
- Fork the repository
- Create a feature branch
- Add comprehensive tests for new functionality
- Ensure all tests pass with high coverage
- Update documentation as needed
- Submit a pull request
Code Standards: Follow established Compact patterns, maintain type safety, and ensure ZK-proof integration for all governance operations.
