# E1 - Ranked Choice Voting system

#### My main aims for my voting system are:

* To use multiple smart contracts interacting together.
* Create and properly utilize a smart contract interface.
* Maybe explore a factory contract.
* The owner can create multiple elections / polls if need be.
* the owner sets the names of the participants.
* The time limit for them can be set in days.
* The will be a maximum number of people / things to vote for.

Below you can see how I prompted my way to break down some project ideas to explore. And ultimatly how I came to somewhere where I could start drafting a plan.

### The initial prompt

#### You

Please guide me through lesson 6. I do not want you to complete tasks for me. Instead I want ideas on possible project ideas I can complete to practice the skills learned. here is lesson 6: {paste lesson six here}

#### ChatGpt

Lesson 6 offers a deep dive into the mechanisms of smart contract interactions on the Ethereum blockchain, which is a cornerstone of building functional and interactive decentralized applications (dApps). Here are some project ideas to practice and reinforce the skills you've learned about contract interactions, interfaces, handling dependencies, and considering security and gas efficiency.

#### Project Idea 1: Decentralized Voting System

**Concept**: Create a two-contract system where one contract acts as a registry for candidates and votes, and another contract serves as a voting interface for users.

* **Contract 1 (Registry)**: Stores candidate details and vote counts using structs and mappings. Implements functions to add candidates and tally votes.
* **Contract 2 (Voting Interface)**: Users interact with this contract to cast their votes. It uses an interface to communicate with the registry contract.

**Skills Practiced**: Direct calls, interfaces, contract creation, and interaction patterns.

#### Project Idea 2: Multi-contract Token Wallet

**Concept**: Develop a wallet system where one contract manages user balances and another handles withdrawal limits and security checks.

* **Contract 1 (Balance Manager)**: Manages deposits, withdrawals, and balance queries. Uses mappings to track user balances.
* **Contract 2 (Security Manager)**: Implements withdrawal limits and security checks using interfaces to interact with the balance manager.

**Skills Practiced**: Using interfaces for contract interactions, implementing security patterns, and managing dependencies.

#### Project Idea 3: Decentralized Marketplace

**Concept**: Build a marketplace with separate contracts for listing items, managing sales, and handling payments.

* **Contract 1 (Item Listing)**: Allows users to list items for sale, storing item details and seller information.
* **Contract 2 (Sales Manager)**: Manages the purchase process, including item availability checks and buyer-seller matching.
* **Contract 3 (Payment Processor)**: Handles the transfer of funds between buyers and sellers, possibly integrating with a token contract.

**Skills Practiced**: Interfaces, direct calls, contract creation, handling complex interactions, and considerations for gas efficiency.

#### Project Idea 4: Factory Pattern for Deploying Instances

**Concept**: Implement a contract factory pattern that deploys instances of a contract. Ideal for scenarios requiring multiple instances of similar contracts, like crowdfunding campaigns or token sales.

* **Factory Contract**: Contains logic to deploy new instances of a child contract with parameters specified by the creator.
* **Child Contract**: Template contract that is instantiated by the factory, customized for specific use cases.

**Skills Practiced**: Contract creation from another contract, managing contract dependencies, and factory patterns.

#### Project Idea 5: Upgradeable Contracts Using Proxy Patterns

**Concept**: Explore contract upgradeability by implementing a simple proxy pattern, enabling contract logic updates without losing state.

* **Proxy Contract**: Forwards calls to an implementation contract, holding the state but delegating the logic.
* **Implementation Contract(s)**: Contains the contract logic. Can be upgraded by pointing the proxy to a new implementation.

**Skills Practiced**: Understanding proxy contracts, upgradability, modularity, and the importance of interfaces in upgradeable designs.

#### Conclusion

Each of these projects challenges you to apply the concepts of smart contract interactions, interfaces, and design patterns in practical scenarios. Starting with simpler projects like the decentralized voting system or token wallet can help solidify your foundational knowledge before moving on to more complex systems like marketplaces, factory patterns, or upgradeable contracts. Remember, the key to mastering smart contract development is iterative learning and hands-on practice.



### Prompt 2

#### You

please expand on the project 1: decentralised voting system. Output some different types of voting systems for me to consider

#### ChatGpt

Expanding on Project 1, a decentralized voting system can take various forms, each with its unique characteristics and use cases. Here are several types of voting systems you might consider implementing in a decentralized context, leveraging blockchain technology for transparency, security, and immutability:

#### 1. **Simple Majority Voting**

* **Concept**: Each participant gets one vote, and the option with the majority of votes wins. This system is straightforward and best suited for decisions with a binary outcome.
* **Blockchain Application**: Use smart contracts to track each address's vote, ensuring one vote per address and transparently tallying votes for immediate results.

#### 2. **Weighted Voting**

* **Concept**: Votes are weighted based on certain criteria, such as the amount of tokens held, length of token holding, or other factors contributing to the weight of a participant's vote.
* **Blockchain Application**: Implement a smart contract that interfaces with a token contract to determine the weight of each vote based on the voter's token balance or other defined criteria.

#### 3. **Quadratic Voting**

* **Concept**: Allows participants to allocate votes based on the intensity of their preference, with the cost of each additional vote for an option increasing quadratically. This encourages voters to distribute votes according to their true preferences across multiple options.
* **Blockchain Application**: Design a contract that calculates the cost of votes and requires participants to spend tokens to cast their votes, with the price increasing quadratically for multiple votes on the same option.

#### 4. **Ranked-Choice Voting (RCV)**

* **Concept**: Voters rank their preferences among the options rather than choosing a single one. If no option wins a majority of the first-choice votes, the option with the fewest votes is eliminated, and votes for it are redistributed based on the next preference, continuing until a candidate achieves a majority.
* **Blockchain Application**: Develop a more complex smart contract system that can handle multiple rounds of vote tallying and redistribution based on voters' ranked preferences.

#### 5. **Liquid Democracy (Delegative Voting)**

* **Concept**: Combines direct democracy and representative democracy by allowing participants to either vote directly on proposals or delegate their voting power to a representative who votes on their behalf. Delegations can be specific to certain issues or general.
* **Blockchain Application**: Create a smart contract that tracks both direct votes and delegations, dynamically calculating the outcome based on the current state of direct and delegated votes.

#### 6. **Anonymous Voting**

* **Concept**: Ensures the privacy and anonymity of voters, hiding their choices from the public while still guaranteeing the integrity and correctness of the vote tally.
* **Blockchain Application**: Utilize cryptographic techniques like zero-knowledge proofs within smart contracts to verify votes without revealing the voter's choice, ensuring anonymity and preventing coercion.

#### Considerations for Implementation

* **Security and Integrity**: Focus on the security of the voting process, ensuring that votes cannot be tampered with and that the system is resistant to common vulnerabilities.
* **Gas Efficiency**: Optimize contract operations to minimize transaction costs, which is particularly important for systems with complex logic like quadratic or ranked-choice voting.
* **User Experience**: Design the front-end interface to be user-friendly, making it easy for voters to understand and participate in the voting process.

Each of these voting systems offers a unique approach to collective decision-making, demonstrating the versatility of smart contracts in implementing decentralized governance mechanisms. Choosing the right system depends on the specific needs, goals, and constraints of your project or community.

###

### Prompt 3

#### You

please expand on the RCV voting system. Give me a step by step guide to follow, in order to complete the smart contract. Must use multiple contracts including an interface.

ChatGpt

Implementing a Ranked-Choice Voting (RCV) system using Solidity involves several steps and components to manage the complexities of ranked voting. In this guide, we'll outline how to structure your smart contracts, including the use of an interface for contract interactions. The system will comprise at least two contracts: a `VotingContract` that handles the voting logic and a `BallotContract` that manages individual ballots.

#### Step 1: Define the Interface for BallotContract

First, define an interface to outline how the `VotingContract` will interact with the `BallotContract`. This interface includes functions for creating ballots and retrieving voter choices.

```solidity
solidityCopy code// IBallotContract.sol
pragma solidity ^0.8.0;

interface IBallotContract {
    function createBallot(address voter, uint[] memory rankings) external;
    function getVoterRanking(address voter, uint candidate) external view returns (uint);
}
```

#### Step 2: Implement the BallotContract

Implement the `BallotContract` that stores each voter's ranked choices. It follows the interface defined above.

```solidity
solidityCopy code// BallotContract.sol
pragma solidity ^0.8.0;

import "./IBallotContract.sol";

contract BallotContract is IBallotContract {
    struct Ballot {
        mapping(uint => uint) rankings; // candidateId => ranking
    }

    mapping(address => Ballot) private ballots;

    function createBallot(address voter, uint[] memory rankings) external override {
        Ballot storage ballot = ballots[voter];
        for (uint i = 0; i < rankings.length; i++) {
            ballot.rankings[i] = rankings[i];
        }
    }

    function getVoterRanking(address voter, uint candidate) external view override returns (uint) {
        return ballots[voter].rankings[candidate];
    }
}
```

#### Step 3: Implement the VotingContract

The `VotingContract` manages the overall voting process, including tallying votes based on the RCV algorithm.

```solidity
solidityCopy code// VotingContract.sol
pragma solidity ^0.8.0;

import "./IBallotContract.sol";

contract VotingContract {
    address[] public candidates;
    address public ballotContractAddress;
    mapping(address => uint) public candidateVotes;
    
    constructor(address[] memory _candidates, address _ballotContract) {
        candidates = _candidates;
        ballotContractAddress = _ballotContract;
    }

    function vote(address voter, uint[] memory rankings) public {
        IBallotContract(ballotContractAddress).createBallot(voter, rankings);
    }

    function tallyVotes() public {
        // Reset votes
        for (uint i = 0; i < candidates.length; i++) {
            candidateVotes[candidates[i]] = 0;
        }

        // Example tally logic (simplified for brevity)
        // In practice, you would implement the full RCV algorithm, redistributing votes from eliminated candidates
        for (uint i = 0; i < candidates.length; i++) {
            for (uint j = 0; j < candidates.length; j++) {
                uint ranking = IBallotContract(ballotContractAddress).getVoterRanking(candidates[j], i);
                if (ranking == 1) { // Assuming 1 is the highest preference
                    candidateVotes[candidates[i]] += 1;
                }
            }
        }

        // Add logic to determine winner based on RCV rules
    }
}
```

#### Step 4: Deploy and Interact with Contracts

1. **Deploy the `BallotContract`** and note its deployed address.
2. **Deploy the `VotingContract`**, passing the candidates and the address of the `BallotContract`.
3. **Vote**: Call the `vote` function on the `VotingContract` for each voter, passing their rankings.
4. **Tally Votes**: After voting is complete, call `tallyVotes` to calculate the results.

#### Considerations

* **RCV Algorithm**: The example provided simplifies the RCV tallying process. In a complete implementation, you would need to iteratively eliminate the candidate with the fewest votes, redistributing their votes based on next preferences until a winner is determined.
* **Security and Gas Costs**: Implement checks to ensure only eligible voters can vote, and optimize your contracts to manage gas costs effectively.
* **Testing**: Thoroughly test your contracts, especially the RCV tallying logic, to ensure accuracy and fairness.

Implementing an RCV system on the blockchain presents unique challenges, especially around managing dynamic arrays in Solidity and optimizing for gas costs. This step-by-step guide gives you a foundation, but be prepared to adapt and expand based on the specific requirements of your voting system.



### Prompt 4

#### You

I do not want you to build contracts for me, instead I want you an overview of the contracts needed. Then when prompted I want to know what each contract needs to include.

#### ChatGpt

Certainly! Let's outline a high-level overview of the contracts needed for implementing a Ranked-Choice Voting (RCV) system on the Ethereum blockchain. This system will ensure transparency, security, and integrity in the voting process.

#### Overview of Contracts Needed

1. **BallotContract**: Manages individual ballots, recording voters' ranked choices for candidates.
2. **VotingContract**: Oversees the entire voting process, interacts with `BallotContract` to store votes, and implements the logic for tallying votes based on RCV.
3. **CandidatesContract** (Optional): Manages candidate registration and information. This could be integrated into the `VotingContract` or managed separately for modularity.
4. **VotingInterface**: Defines the interaction interface for the `BallotContract`. This can be part of the `VotingContract` or a separate interface contract if you want to abstract the interaction layer.

#### Key Components for Each Contract

**BallotContract**

* **Struct for Ballots**: To store a voter's ranked choices. Each ballot could map candidate identifiers to rankings.
* **Ballot Creation Function**: Allows voters to submit their ranked choices. It needs to ensure that rankings are valid (e.g., no duplicate rankings).
* **Data Retrieval Functions**: Functions to retrieve the rankings for a specific voter or ballot, ensuring the `VotingContract` can access the necessary information for vote tallying.

**VotingContract**

* **Candidate Management**: Functions to add or register candidates for the election. This could also be handled by a separate `CandidatesContract`.
* **Voting Function**: Interface with the `BallotContract` to submit votes. This includes validating voter eligibility and enforcing voting rules.
* **Vote Tallying Logic**: Implements the RCV algorithm, which involves counting first-choice votes, identifying the candidate with the fewest votes for elimination, redistributing votes, and determining the winner.
* **Event Emissions**: Emit events for significant actions, such as vote submission and the announcement of results, facilitating frontend integration.

**CandidatesContract (Optional)**

* **Candidate Registration**: Functions to add candidates to the election, including checks to prevent duplicate entries.
* **Candidate Information Retrieval**: Functions to get candidate details, useful for voters and for displaying results.

**VotingInterface**

* **Function Signatures**: Defines the external functions of the `BallotContract` that the `VotingContract` will call. This includes creating ballots and fetching ballot information.

#### Additional Considerations

* **Security Measures**: Implement checks against common vulnerabilities, like reentrancy attacks. Consider using the Checks-Effects-Interactions pattern.
* **Access Control**: Use modifiers to restrict access to certain functions, such as those that allow adding candidates or tallying votes, to authorized users only.
* **Gas Optimization**: Since blockchain operations can be costly, optimize your contracts for gas usage, especially in vote tallying and data storage.

This overview provides a roadmap for building a decentralized RCV system with Solidity. Each contract plays a critical role in managing different aspects of the voting process, from storing individual ballots to tallying votes according to ranked-choice rules.

\
