npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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

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 effects
  • castVoteWithValidation() - Cast votes with ZK proof verification
  • finalizeProposalWithValidation() - Finalize proposals after voting
  • queueProposalWithValidation() - Queue proposals for execution
  • executeEffectWithValidation() - Execute approved effects

State Management:

  • governorConfig - Governance parameters and thresholds
  • activeProposalCount - Active proposal tracking
  • queuedProposalCount - Queued proposal tracking
  • governorPermissions - Admin and user permissions

2. StakeModule Contract (StakeModule.compact)

Purpose: Manages user stakes and voting power calculation

Key Circuits:

  • registerStakeWithValidation() - Register user stakes
  • withdrawStakeWithValidation() - Withdraw stakes with validation
  • delegateStakeWithValidation() - Delegate voting power
  • getStakeInfo() - Query stake information
  • hasProposalThreshold() - Check proposal creation eligibility

State Management:

  • stakes - Individual user stake records
  • delegations - Delegation mappings
  • totalStakes - Aggregate stake totals
  • governanceConfig - Staking parameters

3. ProposalModule Contract (ProposalModule.compact)

Purpose: Handles complete proposal lifecycle from creation to execution

Proposal States:

  • ActiveSucceeded/DefeatedQueuedExecuted

Key Circuits:

  • createProposal() - Create new governance proposals
  • castVote() - Record votes with double-vote prevention
  • finalizeProposal() - Calculate results and update status
  • getProposal() - Query proposal details and status

State Management:

  • proposals - Proposal records with full lifecycle data
  • voteRecords - Individual vote records
  • proposalCounter - 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 effects
  • executeEffect() - Execute approved effects
  • cancelEffect() - Cancel pending effects
  • batchExecuteEffects() - Execute multiple effects

5. TreasuryModule Contract (TreasuryModule.compact)

Purpose: Manages DAO treasury operations and fund controls

Key Circuits:

  • depositToTreasury() - Add funds to treasury
  • withdrawFromTreasury() - Remove funds with approval
  • getTreasuryBalance() - Query treasury balances
  • transferTreasuryTokens() - Internal treasury transfers

State Management:

  • treasuryBalances - Multi-token balance tracking
  • treasuryTransactions - Complete transaction history
  • treasuryStatistics - 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:#f1f8e9

Complete Governance Process

  1. Stake Registration (registerStakeWithValidation)

    • Users register stake to gain voting power
    • ZK proof validates stake ownership
    • Minimum stake requirements enforced
  2. Proposal Creation (createProposalWithEffect)

    • Users with sufficient stake create proposals
    • Proposals linked to executable effects
    • Timing parameters set (voting start/end)
  3. Voting Period (castVoteWithValidation)

    • Community votes on active proposals
    • Stake-weighted voting power
    • Double-vote prevention enforced
  4. Proposal Finalization (finalizeProposalWithValidation)

    • Vote tallying and result calculation
    • Status transition (Succeeded/Defeated)
    • Quorum and threshold validation
  5. Execution Queue (queueProposalWithValidation)

    • Successful proposals queued for execution
    • Execution delay enforced for security
    • Admin approval mechanisms
  6. Effect Execution (executeEffectWithValidation)

    • Approved effects executed with proofs
    • Treasury operations performed
    • Configuration updates applied
  7. 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,000 tokens - Minimum participation required
  • Proposal Threshold: 50,000 tokens - 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 clean

Development 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

Getting Started

  1. Setup: Install dependencies and build contracts
  2. Testing: Run unit and integration test suites
  3. Deployment: Use CLI for contract deployment
  4. Interaction: Use provided API for governance operations

📄 License

MIT License - see LICENSE file for details.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add comprehensive tests for new functionality
  4. Ensure all tests pass with high coverage
  5. Update documentation as needed
  6. Submit a pull request

Code Standards: Follow established Compact patterns, maintain type safety, and ensure ZK-proof integration for all governance operations.