Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

Setting Up a Quadratic Voting Mechanism for Your DAO

A technical guide for developers to implement quadratic voting on-chain. Includes the mathematical model, smart contract examples, and strategies for preventing Sybil attacks.
Chainscore Š 2026
introduction
IMPLEMENTATION GUIDE

Setting Up a Quadratic Voting Mechanism for Your DAO

A technical guide to implementing quadratic voting, a governance model that reduces whale dominance by making each additional vote more expensive.

Quadratic voting (QV) is a collective decision-making process where participants allocate a budget of voice credits to express the intensity of their preferences. Unlike one-token-one-vote, the cost of casting n votes for a single proposal scales quadratically (cost = n²). This design makes it economically prohibitive for a single large token holder (a "whale") to dominate outcomes, as buying 10 votes costs 100 credits, while 100 votes costs 10,000 credits. This mechanism better aligns voting power with the breadth of community support rather than the depth of capital, promoting more equitable governance in DAOs like Gitcoin Grants and Optimism's Citizen House.

To implement QV, you first need to define the voting parameters. Key components include the voting period, vote currency (often a non-transferable "voice credit"), and the quadratic cost function. A common setup allocates each member a fixed budget of credits per funding round (e.g., 99 credits). The smart contract must calculate the cost of a vote as votes² and deduct that from the user's remaining credit balance. It must also prevent over-spending and sybil attacks, often by requiring a proof of unique personhood through services like Worldcoin, BrightID, or Gitcoin Passport.

Here is a simplified Solidity code snippet for the core voting logic. This contract tracks credits and calculates quadratic costs.

solidity
contract QuadraticVoting {
    mapping(address => uint256) public creditBalance;
    mapping(address => mapping(uint256 => uint256)) public votesCast; // voter => proposalId => votes

    function castVote(uint256 proposalId, uint256 voteStrength) external {
        uint256 cost = voteStrength * voteStrength; // Quadratic cost
        require(creditBalance[msg.sender] >= cost, "Insufficient credits");
        
        creditBalance[msg.sender] -= cost;
        votesCast[msg.sender][proposalId] += voteStrength;
        // ... emit event, update proposal total
    }
}

This basic example shows the cost calculation and balance deduction. A production system would include proposal management, result tallying, and sybil resistance.

Integrating sybil resistance is critical. Without it, users could create multiple addresses to bypass the quadratic cost. Solutions include:

  • Proof-of-personhood: Integrating with Worldcoin's Orb verification or BrightID.
  • Staked identity: Requiring a bond of a transferable token (like ETH) that is slashed for fraudulent behavior, as used by Vocdoni.
  • Social graph analysis: Using tools like Gitcoin Passport to aggregate decentralized identity scores. Your contract would check a verified credential or signature from these services before minting voice credits to an address.

After the vote concludes, you must tally the results. The winning proposal is determined by which has the highest sum of square roots of the votes received (sum(√votes)). This is mathematically equivalent to finding the proposal with the highest aggregate "utility" under the quadratic payment model. Off-chain tools like Snapshot with quadratic voting strategies or Tally can handle this calculation. For on-chain execution, your contract must iterate through proposals, calculate the square root sums (using a library like prb-math for fixed-point precision), and declare a winner to trigger the next step, such as fund disbursement.

Successful QV implementations require careful parameter tuning. The total credit budget per user influences participation; too few credits lead to low engagement, while too many diminish the quadratic effect. Platforms like Gitcoin Grants use QV to fund public goods, allocating more matching funds to projects with broad support. The Optimism Collective uses it in its Citizen House to vote on grant distributions. When deploying, start with a test round on a testnet or a pilot proposal with a small budget. Monitor metrics like voter distribution, credit usage, and the Gini coefficient of voting power to iteratively improve the system for your DAO's specific needs.

prerequisites
SETUP GUIDE

Prerequisites

Before implementing a quadratic voting mechanism, you need to establish the foundational technical environment and understand the core concepts.

Quadratic voting (QV) is a collective decision-making process where participants allocate voice credits to express the intensity of their preferences. Unlike one-person-one-vote, QV uses a cost function where the cost to cast n votes for a proposal is n². This structure makes it exponentially more expensive to concentrate votes on a single option, promoting funding for a wider array of proposals that benefit smaller groups. It's particularly effective for DAOs allocating grants or prioritizing features from a treasury. You'll need a basic understanding of smart contracts, Ethereum, and a development framework like Hardhat or Foundry.

Your development environment must be configured to interact with the blockchain. Install Node.js (v18 or later) and a package manager like npm or yarn. You will also need access to an Ethereum wallet (e.g., MetaMask) with testnet ETH for deployments. For local testing, we recommend using Hardhat as it provides a local Ethereum network, debugging tools, and easy integration with testing libraries. Initialize a new project with npx hardhat init and install necessary dependencies such as @openzeppelin/contracts for secure, audited base contracts and dotenv for managing environment variables like private keys.

The core of the system is the smart contract. We will build upon OpenZeppelin's libraries for security. Key contract components include: a VotingToken (ERC-20) to represent voice credits, a QuadraticVoting contract to manage proposals and tally votes, and potentially a Treasury contract to hold and disburse funds. You must understand Solidity concepts like mappings, events, and access control (e.g., OpenZeppelin's Ownable). Familiarity with IPFS or another decentralized storage solution is also crucial for storing proposal metadata (title, description, link) off-chain to save gas.

key-concepts-text
SETTING UP A QUADRATIC VOTING MECHANISM FOR YOUR DAO

Key Concepts: The Quadratic Cost Function

This guide explains the mathematical foundation of quadratic voting and provides a practical framework for implementing it in a decentralized autonomous organization.

The quadratic cost function is the core mechanism that makes quadratic voting (QV) distinct from simple one-token-one-vote systems. Instead of paying a linear cost (e.g., 1 token for 1 vote), the cost to cast votes scales quadratically with the number of votes allocated to a single proposal. The formula is typically expressed as Cost = (Number of Votes)^2. This means buying your first vote costs 1 credit, the second vote costs 4 credits total (2^2), the third costs 9 credits (3^2), and so on. This non-linear pricing creates a powerful economic disincentive against vote concentration, forcing participants to spread their influence more broadly or pay exponentially more to amplify their support for a single option.

Implementing this in a smart contract requires careful design. A basic Solidity function to calculate the cost of casting v votes would be: function voteCost(uint256 v) public pure returns (uint256) { return v * v; }. However, a production system must integrate a credit allocation mechanism (like a periodic grant of "voice credits" to members), track used credits per voter per round, and prevent double-spending. The contract must calculate the marginal cost of each additional vote in real-time to inform the voter, often by comparing voteCost(desiredVotes) - voteCost(currentVotes). Libraries like OpenZeppelin's SafeMath are essential to prevent overflow errors given the squaring operation.

For a DAO, the primary benefit of QV is the mitigation of tyranny of the majority and whale dominance. A member with 10,000 credits cannot simply dump them all on one proposal; to cast 100 votes would cost 10,000 credits (100^2), whereas they could influence 100 different proposals with 1 vote each for only 100 credits total. This encourages voters to signal the intensity of their preferences rather than just binary support/opposition. Practical use cases include budgeting decisions (e.g., allocating a treasury grant across multiple projects), prioritizing roadmap features, or selecting between high-stakes protocol upgrades. The mechanism forces more nuanced and democratic resource allocation.

Several existing protocols offer templates and tooling. Snapshot supports quadratic voting through its strategy system, allowing DAOs to implement QV without custom contract deployment by using a whitelisted voting credit ERC-20 token. For on-chain implementations, the OpenZeppelin Governor contract can be extended with a custom voting module that enforces the quadratic cost calculation. When designing your system, key parameters to define are: the voting credit distribution schedule, the voting period duration, whether credits are transferable, and how to handle the clearing and settlement of votes (often using a commit-reveal scheme to prevent strategic voting based on early results).

Security considerations are paramount. The contract must guard against Sybil attacks, where an attacker creates multiple identities to gain more low-cost votes. This is typically addressed by coupling voting power to a scarce, non-fungible asset like a proof-of-personhood token (e.g., BrightID) or a non-transferable membership NFT. Additionally, the quadratic calculation must be gas-optimized; pre-computing cost tables or using fixed-point math libraries can reduce transaction costs for voters. Always conduct thorough testing on a testnet with simulated voting scenarios to ensure the economic incentives behave as intended before a mainnet deployment.

To get started, a DAO can prototype using Snapshot's off-chain QV. For a fully on-chain implementation, a minimal contract structure includes: a VoiceCredit token for tracking budgets, a QuadraticVoting module that inherits from a governance standard, and a Tally function that uses the square root of the summed squares of votes (sqrt(sum(votes_i^2))) to determine the winning outcome in contests with multiple choices. This final tally method ensures the collective decision reflects the aggregated intensity of preference across all voters, which is the ultimate goal of moving beyond simple majority rule.

GOVERNANCE MECHANICS

Voting Model Comparison: Linear vs. Quadratic

A technical comparison of core attributes between traditional linear (one-token-one-vote) and quadratic voting models for DAO governance.

Governance AttributeLinear Voting (1T1V)Quadratic Voting (QV)

Voting Power Calculation

Directly proportional to token holdings (P = T)

Proportional to square root of tokens committed (P = √T)

Resistance to Whale Dominance

Cost to Cast N Votes

Cost scales linearly (Cost ∝ N)

Cost scales quadratically (Cost ∝ N²)

Ideal Use Case

Token-weighted protocol upgrades, treasury management

Public goods funding, opinion polling, grant allocation

Implementation Complexity (Smart Contracts)

Low

High (requires signature verification, sybil resistance)

Voter Collusion Incentive

High (large holders can easily coordinate)

Reduced (costly to concentrate voting power)

Example: Cost for 100 Votes

100 credits

10,000 credits (100²)

Primary Sybil Attack Vector

Token accumulation

Identity fragmentation / fake accounts

implementation-steps
IMPLEMENTATION STEPS

Setting Up a Quadratic Voting Mechanism for Your DAO

A step-by-step guide to implementing a Sybil-resistant quadratic voting system for on-chain governance using smart contracts and zero-knowledge proofs.

Quadratic voting (QV) is a governance mechanism where the cost of a vote increases quadratically with the number of votes cast on a single proposal. This system, popularized by projects like Gitcoin Grants, helps prevent whale dominance by making it expensive to concentrate voting power. Implementing QV for a DAO requires a secure method to verify unique identity to prevent Sybil attacks—where a single user creates multiple identities to game the system. The core components are a verification registry (like BrightID or Worldcoin) and a smart contract that calculates vote weight as the square root of the credits spent.

The first step is to design your voting smart contract. You'll need functions to: propose new votes, commit votes (to hide preferences), reveal votes after the commit phase, and tally results. The key formula is implemented in the tally function: vote_weight = sqrt(credits_used). For example, if a member spends 9 credits on a proposal, their voting power is 3. Use a library like OpenZeppelin's Math for the square root calculation. Always include a commit-reveal scheme to prevent strategic voting based on early results. Store vote commitments as keccak256 hashes of the voter's address, proposal ID, choice, and a secret salt.

Next, integrate a Sybil-resistance solution. You can use ERC-20 tokens with a proof-of-personhood check during token distribution, or directly verify users in your voting contract. For a gas-efficient approach, use a merkle tree of verified identities. An off-chain service maintains a list of verified user addresses, generates a merkle root, and posts it on-chain. Voters submit a merkle proof along with their vote to prove they are in the verified set. Alternatively, leverage zero-knowledge proofs (ZKPs) with Semaphore or Interep to allow users to prove membership in a group without revealing their identity, enhancing privacy.

Deploy and test your contracts on a testnet like Goerli or Sepolia. Write comprehensive tests using Hardhat or Foundry that simulate various attack vectors: Sybil attacks, flash loan attacks to manipulate token holdings, and front-running during the commit phase. Use snapshot.js or Tenderly to fork mainnet state and test with real token distributions. Key metrics to verify are: the quadratic cost curve is enforced, the total voting power scales correctly, and the system correctly rejects unverified identities. Consider adding a timelock on executed proposals and a guardian multisig for emergency pauses during the initial launch phase.

Finally, frontend integration is crucial for user adoption. Build a simple dApp interface that connects user wallets (via WalletConnect or MetaMask), checks their verification status, and displays active proposals. Use The Graph to index proposal and vote data for efficient querying. For the commit-reveal flow, the frontend must generate the secret salt client-side, create the vote commitment, and store the salt locally (e.g., in localStorage) until the reveal phase. Clearly communicate the quadratic cost to users: "Spending 1 credit gives 1 power, 4 credits gives 2 power, 9 credits gives 3 power." Document the process thoroughly and consider a test vote for members to familiarize themselves with the system before a real treasury proposal.

sybil-resistance-methods
SYBIL RESISTANCE AND IDENTITY

Setting Up a Quadratic Voting Mechanism for Your DAO

Quadratic voting is a governance mechanism that allocates voting power based on the square root of tokens held, reducing the influence of large token whales. This guide explains how to implement it to enhance Sybil resistance in your DAO.

Quadratic voting (QV) is a collusion-resistant mechanism designed to reflect the intensity of voter preference rather than just binary support. Instead of one token equaling one vote, a voter with n tokens receives sqrt(n) voting power. This mathematical curve makes it exponentially more expensive for a single entity to dominate a vote, thereby mitigating Sybil attacks where an attacker creates many fake identities (Sybils) to gain disproportionate influence. For a DAO, this means governance decisions better reflect the consensus of a diverse group rather than being controlled by a few large holders.

Implementing QV requires careful smart contract design. The core logic involves calculating voting power using a square root function, which is computationally expensive on-chain. Use a proven library like OpenZeppelin's Math library for the sqrt operation. A basic vote casting function would check a user's token balance, calculate the square root, and add that weight to a proposal tally. It's crucial to use a snapshot of token balances at a specific block to prevent manipulation during the voting period. Tools like Snapshot.org support QV, but for on-chain voting, you must implement this logic directly in your governance contract.

Consider this simplified Solidity code snippet for a QV calculation:

solidity
import "@openzeppelin/contracts/utils/math/Math.sol";
function castVote(uint256 proposalId, uint8 support) public {
    uint256 balance = token.balanceOfAt(msg.sender, snapshotBlock);
    uint256 votingPower = Math.sqrt(balance);
    proposals[proposalId].voteWeight += votingPower;
}

This function fetches the user's balance at the pre-defined snapshotBlock, calculates the square root using a gas-efficient method from OpenZeppelin, and adds the result to the proposal. Remember to include checks for double voting and to ensure the snapshot is taken before the proposal starts.

While QV strengthens Sybil resistance, it has trade-offs. It can disadvantage smaller holders if the cost of acquiring even a few tokens is prohibitive, and the square root calculation increases gas costs. Furthermore, QV alone doesn't prevent collusion where multiple wallets are controlled by one entity; it just raises the cost. For robust Sybil defense, combine QV with identity verification layers like BrightID or Gitcoin Passport, or use conviction voting models. Always audit your contract and consider using battle-tested frameworks like Aragon or Colony that offer modular governance components.

To deploy, start with a testnet using a token like ERC-20 or ERC-721 (for one-person-one-vote models). Use a verification tool like Tenderly to simulate voting scenarios and ensure the sqrt function behaves correctly with large numbers. The final step is to integrate the voting contract with a front-end, using a library like wagmi or ethers.js to connect user wallets, display voting power, and submit transactions. Proper documentation and community education are essential for successful adoption of this more complex governance model.

code-example-cost-contract
SOLIDITY IMPLEMENTATION

Code Example: Quadratic Cost Contract

A step-by-step guide to building a smart contract that implements a quadratic cost function for voting, a core mechanism for mitigating Sybil attacks in DAO governance.

Quadratic voting is a governance mechanism where the cost of casting votes increases quadratically with the number of votes purchased for a single proposal. This means buying 2 votes costs 4 credits, 3 votes cost 9 credits, and so on. The formula is cost = votes². This design, popularized by projects like Gitcoin Grants, makes it economically prohibitive for a single entity to dominate a vote, promoting more egalitarian outcomes. It's a fundamental tool for Sybil resistance, as accumulating large influence requires quadratic financial expenditure.

Below is a basic Solidity contract implementing a quadratic cost function for a token-weighted voting system. This example uses a simple credit system for demonstration. In production, you would integrate with a real ERC-20 token and include comprehensive access control and security checks.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract QuadraticVoting {
    // Maps voter address to their remaining credit balance
    mapping(address => uint256) public creditBalance;
    // Maps proposal ID to a tally of net votes (for/against)
    mapping(uint256 => int256) public proposalVotes;

    // Cost to vote is the square of the vote weight
    function _getVoteCost(uint256 _voteWeight) internal pure returns (uint256) {
        return _voteWeight * _voteWeight;
    }

    // Core function to cast a quadratic vote
    function castVote(uint256 _proposalId, uint256 _voteWeight, bool _isFor) external {
        uint256 cost = _getVoteCost(_voteWeight);
        require(creditBalance[msg.sender] >= cost, "Insufficient credits");

        // Deduct the quadratic cost from the voter's balance
        creditBalance[msg.sender] -= cost;

        // Apply the vote weight to the proposal tally
        // Positive for 'for', negative for 'against'
        int256 voteImpact = _isFor ? int256(_voteWeight) : -int256(_voteWeight);
        proposalVotes[_proposalId] += voteImpact;
    }

    // Function to allocate credits (for demo purposes)
    function allocateCredits(address _to, uint256 _amount) external {
        creditBalance[_to] += _amount;
    }
}

The key function is _getVoteCost, which calculates the quadratic cost. The castVote function first checks if the voter has enough credits to cover voteWeight². If so, it deducts that cost and updates the proposal's tally. A vote weight of 5 would cost 25 credits, making a weight of 10 cost 100 credits. This exponential increase is the core deterrent against centralized vote buying. Note that this example uses a simple int256 tally; a real implementation would likely track individual voter choices per proposal for transparency and potential vote changing.

When integrating this pattern, consider these critical enhancements: - Snapshotting: Use a snapshot of token balances at a specific block to prevent manipulation via token transfers during voting. - Vote changing: Allow users to recast votes, refunding the previous cost's square and charging the new one. - Multiple choices: Extend beyond for/against to support voting on multiple options, as seen in quadratic funding rounds. - Gas optimization: Pre-calculate and store costs for common vote weights to save on-chain computation. Always audit such contracts thoroughly, as the quadratic math must be precise to avoid rounding errors or exploits.

For real-world reference, review the OpenZeppelin Governor contracts and the ERC-5805 standard for delegate voting, which can be adapted for quadratic logic. The Gitcoin Grants Stack also provides extensive, audited implementations for quadratic funding. Testing is paramount: write extensive unit tests that simulate edge cases, such as a user attempting to vote with a weight that would cause an overflow in the _voteWeight * _voteWeight calculation, and ensure the contract handles the quadratic refund logic correctly if you implement vote changing.

IMPLEMENTATION PATHS

Platform-Specific Considerations

Using Snapshot for Quadratic Voting

Snapshot is the most popular off-chain voting platform, ideal for gasless, signaling votes. Its flexible voting strategies allow for quadratic voting implementations without smart contract deployment.

Key Setup Steps:

  1. Create a space for your DAO on snapshot.org.
  2. Configure the voting strategy. Use the erc20-balance-of or erc20-with-balance strategy with a quadratic formula.
  3. Define the quadratic formula in the proposal settings. For example, use sqrt(votingPower) to calculate cost.
  4. Set the voting type to 'Quadratic voting' or 'Weighted voting' and define the cost function.

Pros: Zero gas costs for voters, user-friendly interface, integrates with most wallets. Cons: Votes are off-chain signals; execution requires separate, trusted multisig.

QUADRATIC VOTING

Frequently Asked Questions

Common technical questions and troubleshooting steps for implementing a quadratic voting mechanism in a DAO.

Quadratic voting (QV) is a collective decision-making mechanism where participants allocate a budget of voice credits to express the intensity of their preferences. The core mathematical principle is that the cost of additional votes on a single proposal increases quadratically.

Key formula: Cost = (Number of Votes)^2

For example, casting 1 vote costs 1 credit, 2 votes cost 4 credits (2²), and 3 votes cost 9 credits (3²). This pricing curve makes it exponentially expensive to concentrate all influence on a single option, encouraging voters to distribute their credits across multiple proposals they care about. The final tally for a proposal is the sum of the square roots of the credits spent on it: Tally = Σ √(Credits Spent on Proposal). This system is designed to more accurately measure the aggregate welfare or intensity of preference across a community compared to one-person-one-vote.

conclusion-next-steps
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have successfully configured a quadratic voting (QV) system for your DAO, establishing a more democratic and Sybil-resistant governance layer. This guide has covered the core concepts, smart contract setup, and frontend integration required to deploy a functional QV mechanism.

The primary advantage of implementing quadratic voting is its ability to measure the intensity of voter preference, not just the direction. By making the cost of votes scale quadratically, the system reduces the influence of whales and encourages broader, more nuanced participation. Your DAO can now handle proposals where members express how strongly they feel, leading to outcomes that better reflect the collective will. However, remember that QV's effectiveness is heavily dependent on a robust Sybil-resistance mechanism, such as proof-of-personhood or a verified credential system, to prevent vote farming through multiple identities.

For production deployment, several critical next steps remain. First, conduct thorough testing on a testnet using frameworks like Hardhat or Foundry, simulating various attack vectors and voter scenarios. Second, consider gas optimization; the squaring and square root operations in the _calculateQuadraticCost function can be expensive. Explore using precomputed lookup tables or optimized math libraries like PRBMath. Finally, establish clear governance parameters: set the voteCreditPrice, define proposal duration windows, and decide on quorum thresholds before going live on mainnet.

To extend your QV system, you can integrate more advanced features. Implement delegated quadratic voting, allowing members to delegate their voting credits to trusted experts while preserving the quadratic cost curve. Add support for partial commitment schemes like MACI (Minimal Anti-Collusion Infrastructure) to enhance privacy and prevent coercion. You can also explore cross-chain quadratic funding rounds using protocols like Gitcoin Grants, enabling your DAO to allocate treasury funds to public goods projects across the ecosystem.

The code and concepts from this tutorial provide a foundation. For further learning, review the complete Quadratic Voting SDK from Worldcoin, study Vitalik Buterin's original paper on liberal radicalism (pairwise coordination subsidies), and examine live implementations in DAOs like Gitcoin and Optimism's Citizen House. Continuously audit and iterate on your mechanism based on voter feedback and on-chain data to ensure it serves your community's evolving needs.

How to Implement Quadratic Voting for a DAO | ChainScore Guides