@claritydao/midnight-agora-contracts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.prettierrc ADDED
@@ -0,0 +1 @@
1
+ { "trailingComma": "none" }
package/README.md ADDED
@@ -0,0 +1,435 @@
1
+ # Agora DAO - Smart Contracts
2
+
3
+ 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.
4
+
5
+ ## 🏗️ Architecture
6
+
7
+ The Agora DAO system is built with a modular architecture, separating concerns across multiple Compact modules:
8
+
9
+ ### Contract Structure
10
+
11
+ ```
12
+ /src
13
+ ├── contracts/
14
+ │ ├── DAO/
15
+ │ │ ├── Governor.compact # Main governance coordinator
16
+ │ │ ├── StakeModule.compact # Stake management and delegation
17
+ │ │ ├── ProposalModule.compact # Proposal lifecycle and voting
18
+ │ │ ├── EffectModule.compact # Effect execution and processing
19
+ │ │ └── TreasuryModule.compact # Treasury management and controls
20
+ │ ├── utils/
21
+ │ │ ├── TypesModule.compact # Shared data structures and enums
22
+ │ │ ├── Utils.compact # Common utility functions
23
+ │ │ ├── Initializable.compact # Initialization control pattern
24
+ │ │ └── Pausable.compact # Emergency pause functionality
25
+ │ └── fungibleToken/
26
+ │ └── FungibleToken.compact # Token implementation
27
+ ├── test/
28
+ │ ├── governance-simulator.ts # Local testing simulator
29
+ │ └── governor-contract.test.ts # Comprehensive test suite
30
+ └── witnesses.ts # Private state management
31
+ ```
32
+
33
+ ## 📋 Core Contracts
34
+
35
+ > 📋 **Complete Technical Documentation**: See [Contract Documentation](../docs/CONTRACT_DOCUMENTATION.md) for detailed specifications of all smart contracts, circuits, and data structures.
36
+
37
+ ### 1. Governor Contract (`Governor.compact`)
38
+ **Purpose**: Central orchestrator for all governance operations
39
+
40
+ **Key Circuits:**
41
+ - `createProposalWithEffect()` - Submit governance proposals with effects
42
+ - `castVoteWithValidation()` - Cast votes with ZK proof verification
43
+ - `finalizeProposalWithValidation()` - Finalize proposals after voting
44
+ - `queueProposalWithValidation()` - Queue proposals for execution
45
+ - `executeEffectWithValidation()` - Execute approved effects
46
+
47
+ **State Management:**
48
+ - `governorConfig` - Governance parameters and thresholds
49
+ - `activeProposalCount` - Active proposal tracking
50
+ - `queuedProposalCount` - Queued proposal tracking
51
+ - `governorPermissions` - Admin and user permissions
52
+
53
+ ### 2. StakeModule Contract (`StakeModule.compact`)
54
+ **Purpose**: Manages user stakes and voting power calculation
55
+
56
+ **Key Circuits:**
57
+ - `registerStakeWithValidation()` - Register user stakes
58
+ - `withdrawStakeWithValidation()` - Withdraw stakes with validation
59
+ - `delegateStakeWithValidation()` - Delegate voting power
60
+ - `getStakeInfo()` - Query stake information
61
+ - `hasProposalThreshold()` - Check proposal creation eligibility
62
+
63
+ **State Management:**
64
+ - `stakes` - Individual user stake records
65
+ - `delegations` - Delegation mappings
66
+ - `totalStakes` - Aggregate stake totals
67
+ - `governanceConfig` - Staking parameters
68
+
69
+ ### 3. ProposalModule Contract (`ProposalModule.compact`)
70
+ **Purpose**: Handles complete proposal lifecycle from creation to execution
71
+
72
+ **Proposal States:**
73
+ - **Active** → **Succeeded/Defeated** → **Queued** → **Executed**
74
+
75
+ **Key Circuits:**
76
+ - `createProposal()` - Create new governance proposals
77
+ - `castVote()` - Record votes with double-vote prevention
78
+ - `finalizeProposal()` - Calculate results and update status
79
+ - `getProposal()` - Query proposal details and status
80
+
81
+ **State Management:**
82
+ - `proposals` - Proposal records with full lifecycle data
83
+ - `voteRecords` - Individual vote records
84
+ - `proposalCounter` - Unique proposal ID generation
85
+
86
+ ### 4. EffectModule Contract (`EffectModule.compact`)
87
+ **Purpose**: Processes and executes governance effects
88
+
89
+ **Effect Types:**
90
+ - **MintToken**: Create new tokens for treasury
91
+ - **Transfer**: Move tokens between accounts
92
+ - **UpdateConfig**: Modify governance parameters
93
+
94
+ **Key Circuits:**
95
+ - `createEffect()` - Create executable effects
96
+ - `executeEffect()` - Execute approved effects
97
+ - `cancelEffect()` - Cancel pending effects
98
+ - `batchExecuteEffects()` - Execute multiple effects
99
+
100
+ ### 5. TreasuryModule Contract (`TreasuryModule.compact`)
101
+ **Purpose**: Manages DAO treasury operations and fund controls
102
+
103
+ **Key Circuits:**
104
+ - `depositToTreasury()` - Add funds to treasury
105
+ - `withdrawFromTreasury()` - Remove funds with approval
106
+ - `getTreasuryBalance()` - Query treasury balances
107
+ - `transferTreasuryTokens()` - Internal treasury transfers
108
+
109
+ **State Management:**
110
+ - `treasuryBalances` - Multi-token balance tracking
111
+ - `treasuryTransactions` - Complete transaction history
112
+ - `treasuryStatistics` - Aggregate treasury metrics
113
+
114
+ ## 🔄 Governance Workflow
115
+
116
+ The complete governance process follows this workflow:
117
+
118
+ ```mermaid
119
+ flowchart TD
120
+ A[Register Stake] --> B[Create Proposal]
121
+ B --> C[Voting Period]
122
+ C --> D[Finalize Proposal]
123
+ D --> E[Queue for Execution]
124
+ E --> F[Execute Effects]
125
+ F --> G[Update Treasury/Config]
126
+
127
+ style A fill:#e1f5fe
128
+ style B fill:#f3e5f5
129
+ style C fill:#fff3e0
130
+ style D fill:#e8f5e8
131
+ style E fill:#fff8e1
132
+ style F fill:#fce4ec
133
+ style G fill:#f1f8e9
134
+ ```
135
+
136
+ ### Complete Governance Process
137
+
138
+ 1. **Stake Registration** (`registerStakeWithValidation`)
139
+ - Users register stake to gain voting power
140
+ - ZK proof validates stake ownership
141
+ - Minimum stake requirements enforced
142
+
143
+ 2. **Proposal Creation** (`createProposalWithEffect`)
144
+ - Users with sufficient stake create proposals
145
+ - Proposals linked to executable effects
146
+ - Timing parameters set (voting start/end)
147
+
148
+ 3. **Voting Period** (`castVoteWithValidation`)
149
+ - Community votes on active proposals
150
+ - Stake-weighted voting power
151
+ - Double-vote prevention enforced
152
+
153
+ 4. **Proposal Finalization** (`finalizeProposalWithValidation`)
154
+ - Vote tallying and result calculation
155
+ - Status transition (Succeeded/Defeated)
156
+ - Quorum and threshold validation
157
+
158
+ 5. **Execution Queue** (`queueProposalWithValidation`)
159
+ - Successful proposals queued for execution
160
+ - Execution delay enforced for security
161
+ - Admin approval mechanisms
162
+
163
+ 6. **Effect Execution** (`executeEffectWithValidation`)
164
+ - Approved effects executed with proofs
165
+ - Treasury operations performed
166
+ - Configuration updates applied
167
+
168
+ 7. **State Updates**
169
+ - Treasury balances updated
170
+ - Governance parameters modified
171
+ - Transaction history recorded
172
+
173
+ ## 🔐 Security Features
174
+
175
+ > 📋 **Complete Security Documentation**: See [Contract Documentation](../docs/CONTRACT_DOCUMENTATION.md#security-model) for detailed security model and threat analysis.
176
+
177
+ ### Zero-Knowledge Proof Security
178
+ - **ProofOfStake**: Validates stake ownership without revealing amounts
179
+ - **ProofOfGovernorApproval**: Authorizes governance actions with privacy
180
+ - **ProofOfEffectExecution**: Validates execution rights securely
181
+ - **Nonce-based Replay Protection**: Prevents proof reuse attacks
182
+
183
+ ### Access Control Framework
184
+ - **Stake-weighted Voting**: Voting power proportional to stake
185
+ - **Proposal Thresholds**: Minimum stake required for proposal creation
186
+ - **Admin Permissions**: Role-based access for critical operations
187
+ - **Time-locked Execution**: Security delays before effect execution
188
+ - **Emergency Controls**: Veto mechanisms for critical situations
189
+
190
+ ### Anti-Manipulation Safeguards
191
+ - **Double-vote Prevention**: Cryptographic prevention of vote duplication
192
+ - **Proposal Lifetime Limits**: Time bounds prevent stale proposals
193
+ - **Quorum Requirements**: Minimum participation for valid decisions
194
+ - **Voting Period Enforcement**: Strict timing for proposal phases
195
+ - **Effect Validation**: Comprehensive validation before execution
196
+ - **Treasury Protection**: Multi-layered spending controls
197
+
198
+ ## 📊 Key Features
199
+
200
+ ### Configurable Governance Parameters
201
+ - **Voting Period**: `300s` (5 minutes for testing) - Duration for proposal voting
202
+ - **Quorum Threshold**: `100,000` tokens - Minimum participation required
203
+ - **Proposal Threshold**: `50,000` tokens - Minimum stake to create proposals
204
+ - **Proposal Lifetime**: `86,400s` (1 day) - Maximum proposal validity
205
+ - **Execution Delay**: `60s` (1 minute) - Security delay before execution
206
+ - **Grace Period**: `300s` (5 minutes) - Window for effect execution
207
+ - **Emergency Veto**: Community override with higher threshold
208
+
209
+ ### Effect Action Types
210
+ - **MintToken** (`EffectActionType.MintToken`)
211
+ - Create new tokens for treasury or recipients
212
+ - Configurable amounts and recipients
213
+ - Treasury balance tracking
214
+
215
+ - **Transfer** (`EffectActionType.Transfer`)
216
+ - Move tokens between accounts
217
+ - Treasury to external transfers
218
+ - Multi-token support
219
+
220
+ - **UpdateConfig** (`EffectActionType.UpdateConfig`)
221
+ - Modify governance parameters
222
+ - Update thresholds and periods
223
+ - Admin permission changes
224
+
225
+ ### Advanced Treasury Features
226
+ - **Multi-token Support**: Handle various token types
227
+ - **Balance Tracking**: Real-time treasury monitoring
228
+ - **Transaction History**: Complete audit trail
229
+ - **Spending Controls**: Authorized withdrawal limits
230
+ - **Emergency Freeze**: Pause capabilities for security
231
+ - **Statistics Tracking**: Usage and performance metrics
232
+
233
+ ## 🧪 Testing & Validation
234
+
235
+ > 📋 **Complete Test Documentation**: See [Test Scenarios and Results](../docs/TEST_SCENARIOS_AND_RESULTS.md) for comprehensive testing analysis and results.
236
+
237
+ ### Test Coverage
238
+ - **Unit Tests**: 95.8% function coverage (137/143 functions)
239
+ - **Integration Tests**: Real blockchain interaction testing
240
+ - **Fuzz Testing**: Property-based testing with random inputs
241
+ - **Edge Cases**: Boundary conditions and error scenarios
242
+
243
+ ### Test Results
244
+ - **Total Tests**: 125 tests across unit and integration suites
245
+ - **Success Rate**: 99.2% (124/125 tests passing)
246
+ - **Execution Time**: ~47 minutes total (~45 min integration due to blockchain)
247
+ - **Coverage**: 95.1% overall code coverage
248
+
249
+ ### Testing Infrastructure
250
+ - **GovernanceSimulator**: Local contract testing without blockchain
251
+ - **Integration Environment**: Real testnet interaction
252
+ - **Automated Testing**: Continuous validation pipeline
253
+ - **Performance Monitoring**: Load and stress testing
254
+
255
+ ## 🛠️ Implementation Notes
256
+
257
+ ### Compact Language Features
258
+ - **Ledger State**: Persistent on-chain state storage
259
+ - **Pure Circuits**: ZK-proof-enabled functions with validation
260
+ - **Witness Functions**: Private input handling for proofs
261
+ - **Structs and Enums**: Type-safe data structures
262
+ - **Vector<N, T>**: Fixed-size array operations
263
+ - **Map<K, V>**: Key-value state storage
264
+ - **Assert Statements**: Validation and constraint enforcement
265
+
266
+ ### Architecture Principles
267
+ - **Modularity**: Clear separation of concerns across contracts
268
+ - **Composability**: Contracts work together seamlessly
269
+ - **Type Safety**: Strict typing prevents runtime errors
270
+ - **ZK-Native**: Built-in zero-knowledge proof integration
271
+ - **Configurable**: Parameter-driven governance customization
272
+ - **Upgradeable**: Admin-controlled configuration updates
273
+
274
+ ## 🚀 Usage Examples
275
+
276
+ ### Complete Governance Flow Example
277
+
278
+ #### 1. Register Stake
279
+ ```compact
280
+ // User registers stake to participate in governance
281
+ registerStakeWithValidation(
282
+ userId,
283
+ 50000, // 50K tokens
284
+ ProofOfStake {
285
+ userId: userId,
286
+ amount: 50000,
287
+ nonce: randomNonce
288
+ }
289
+ );
290
+ ```
291
+
292
+ #### 2. Create Proposal with Effects
293
+ ```compact
294
+ // Create proposal with multiple effects
295
+ const actions = Vector<10, EffectAction> {
296
+ EffectAction {
297
+ typ: EffectActionType.MintToken,
298
+ token: treasuryToken,
299
+ amount: 10000,
300
+ to: developmentFund,
301
+ configKey: emptyBytes,
302
+ configValue: emptyBytes
303
+ },
304
+ EffectAction {
305
+ typ: EffectActionType.Transfer,
306
+ token: treasuryToken,
307
+ amount: 5000,
308
+ to: marketingFund,
309
+ configKey: emptyBytes,
310
+ configValue: emptyBytes
311
+ }
312
+ // ... up to 10 actions
313
+ };
314
+
315
+ const proposalId = createProposalWithEffect(
316
+ creatorUserId,
317
+ "Treasury Allocation Q1",
318
+ "Allocate funds for development and marketing",
319
+ actions,
320
+ ProofOfStake { userId: creatorUserId, amount: 50000, nonce: randomNonce },
321
+ currentTime, // voting start
322
+ currentTime + 300 // voting end (5 minutes)
323
+ );
324
+ ```
325
+
326
+ #### 3. Cast Votes
327
+ ```compact
328
+ // Multiple users vote on the proposal
329
+ castVoteWithValidation(
330
+ proposalId,
331
+ voter1UserId,
332
+ VoteChoice.For,
333
+ ProofOfStake { userId: voter1UserId, amount: 75000, nonce: randomNonce }
334
+ );
335
+
336
+ castVoteWithValidation(
337
+ proposalId,
338
+ voter2UserId,
339
+ VoteChoice.Against,
340
+ ProofOfStake { userId: voter2UserId, amount: 25000, nonce: randomNonce }
341
+ );
342
+ ```
343
+
344
+ #### 4. Execute Governance Pipeline
345
+ ```compact
346
+ // After voting period ends, finalize proposal
347
+ finalizeProposalWithValidation(proposalId);
348
+
349
+ // Queue for execution with delay
350
+ queueProposalWithValidation(proposalId);
351
+
352
+ // Execute effects after delay period
353
+ executeEffectWithValidation(
354
+ effectId,
355
+ ProofOfGovernorApproval {
356
+ proposalId: proposalId,
357
+ effectId: effectId,
358
+ approvalTime: currentTime,
359
+ nonce: randomNonce
360
+ }
361
+ );
362
+ ```
363
+
364
+ ## 🔧 Development & Deployment
365
+
366
+ ### Build & Test Commands
367
+ ```bash
368
+ # Install dependencies
369
+ npm install
370
+
371
+ # Build contracts
372
+ npm run build
373
+
374
+ # Run unit tests
375
+ npm test
376
+
377
+ # Run unit tests with coverage
378
+ npm run test:coverage
379
+
380
+ # Clean build artifacts
381
+ npm run clean
382
+ ```
383
+
384
+ ### Development Status
385
+
386
+ ✅ **Completed Components**:
387
+ - [x] All core governance contracts (Governor, Stake, Proposal, Effect, Treasury)
388
+ - [x] Comprehensive type system and utilities
389
+ - [x] Zero-knowledge proof integration
390
+ - [x] Complete test suite with 95.8% coverage
391
+ - [x] Local testing simulator
392
+ - [x] Integration test infrastructure
393
+ - [x] CLI interface for contract interaction
394
+
395
+ ✅ **Quality Assurance**:
396
+ - [x] Unit testing (95.8% function coverage)
397
+ - [x] Integration testing (real blockchain interaction)
398
+ - [x] Fuzz testing (property-based validation)
399
+ - [x] Edge case testing (boundary conditions)
400
+ - [x] Performance testing (load and stress tests)
401
+
402
+ ### Production Readiness
403
+ - **Security**: ZK-proof validation, access controls, time locks
404
+ - **Testing**: Comprehensive test suite with high coverage
405
+ - **Documentation**: Complete technical and API documentation
406
+ - **Performance**: Optimized for Midnight blockchain efficiency
407
+ - **Monitoring**: Built-in metrics and audit trails
408
+
409
+ ## 📚 Documentation
410
+
411
+ ### Contract-Specific Documentation
412
+ - **[Technical Specifications](../docs/CONTRACT_DOCUMENTATION.md)**: Detailed contract architecture
413
+ - **[Test Results](../docs/TEST_SCENARIOS_AND_RESULTS.md)**: Comprehensive testing analysis
414
+ - **[Module Details](../docs/MODULE_DOCUMENTATION.md)**: CLI and component documentation
415
+
416
+ ### Getting Started
417
+ 1. **Setup**: Install dependencies and build contracts
418
+ 2. **Testing**: Run unit and integration test suites
419
+ 3. **Deployment**: Use CLI for contract deployment
420
+ 4. **Interaction**: Use provided API for governance operations
421
+
422
+ ## 📄 License
423
+
424
+ MIT License - see [LICENSE](../LICENSE) file for details.
425
+
426
+ ## 🤝 Contributing
427
+
428
+ 1. Fork the repository
429
+ 2. Create a feature branch
430
+ 3. Add comprehensive tests for new functionality
431
+ 4. Ensure all tests pass with high coverage
432
+ 5. Update documentation as needed
433
+ 6. Submit a pull request
434
+
435
+ **Code Standards**: Follow established Compact patterns, maintain type safety, and ensure ZK-proof integration for all governance operations.