---
# System prepended metadata

title: Weekend Project 2

---

# Weekend Project 2
> Solidity BootCamp 2023Q1 @ encode.club

:::info
## Table of Contents
[TOC]
:::

## Tasks 

* Form groups of 3 to 5 students
* Develop and run scripts for “Ballot.sol” within your group to give voting rights, casting votes, delegating votes and querying results
* Write a report with each function execution and the transaction hash, if successful, or the revert reason, if failed
* Submit your code in a github repository in the form

## General Contract Information

**Contract Address:**
`0xaf5bd48C8dd8F733697e148F952c62868A701b71`

TransactionID Deployment: 
https://goerli.etherscan.io/tx/0xc6ac726a083029ea8b189dbc4abb5962894568b076fb60cf84acdfe97f97e644

Contract Code: 
```solidity 
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/// @title Voting with delegation.
contract Ballot {
    // This declares a new complex type which will
    // be used for variables later.
    // It will represent a single voter.
    struct Voter {
        uint weight; // weight is accumulated by delegation
        bool voted;  // if true, that person already voted
        address delegate; // person delegated to
        uint vote;   // index of the voted proposal
    }

    // This is a type for a single proposal.
    struct Proposal {
        bytes32 name;   // short name (up to 32 bytes)
        uint voteCount; // number of accumulated votes
    }

    address public chairperson;

    // This declares a state variable that
    // stores a `Voter` struct for each possible address.
    mapping(address => Voter) public voters;

    // A dynamically-sized array of `Proposal` structs.
    Proposal[] public proposals;

    /// Create a new ballot to choose one of `proposalNames`.
    constructor(bytes32[] memory proposalNames) {
        chairperson = msg.sender;
        voters[chairperson].weight = 1;

        // For each of the provided proposal names,
        // create a new proposal object and add it
        // to the end of the array.
        for (uint i = 0; i < proposalNames.length; i++) {
            // `Proposal({...})` creates a temporary
            // Proposal object and `proposals.push(...)`
            // appends it to the end of `proposals`.
            proposals.push(Proposal({
                name: proposalNames[i],
                voteCount: 0
            }));
        }
    }

    // Give `voter` the right to vote on this ballot.
    // May only be called by `chairperson`.
    function giveRightToVote(address voter) external {
        // If the first argument of `require` evaluates
        // to `false`, execution terminates and all
        // changes to the state and to Ether balances
        // are reverted.
        // This used to consume all gas in old EVM versions, but
        // not anymore.
        // It is often a good idea to use `require` to check if
        // functions are called correctly.
        // As a second argument, you can also provide an
        // explanation about what went wrong.
        require(
            msg.sender == chairperson,
            "Only chairperson can give right to vote."
        );
        require(
            !voters[voter].voted,
            "The voter already voted."
        );
        require(voters[voter].weight == 0);
        voters[voter].weight = 1;
    }

    /// Delegate your vote to the voter `to`.
    function delegate(address to) external {
        // assigns reference
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "You have no right to vote");
        require(!sender.voted, "You already voted.");

        require(to != msg.sender, "Self-delegation is disallowed.");

        // Forward the delegation as long as
        // `to` also delegated.
        // In general, such loops are very dangerous,
        // because if they run too long, they might
        // need more gas than is available in a block.
        // In this case, the delegation will not be executed,
        // but in other situations, such loops might
        // cause a contract to get "stuck" completely.
        while (voters[to].delegate != address(0)) {
            to = voters[to].delegate;

            // We found a loop in the delegation, not allowed.
            require(to != msg.sender, "Found loop in delegation.");
        }

        Voter storage delegate_ = voters[to];

        // Voters cannot delegate to accounts that cannot vote.
        require(delegate_.weight >= 1);

        // Since `sender` is a reference, this
        // modifies `voters[msg.sender]`.
        sender.voted = true;
        sender.delegate = to;

        if (delegate_.voted) {
            // If the delegate already voted,
            // directly add to the number of votes
            proposals[delegate_.vote].voteCount += sender.weight;
        } else {
            // If the delegate did not vote yet,
            // add to her weight.
            delegate_.weight += sender.weight;
        }
    }

    /// Give your vote (including votes delegated to you)
    /// to proposal `proposals[proposal].name`.
    function vote(uint proposal) external {
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "Has no right to vote");
        require(!sender.voted, "Already voted.");
        sender.voted = true;
        sender.vote = proposal;

        // If `proposal` is out of the range of the array,
        // this will throw automatically and revert all
        // changes.
        proposals[proposal].voteCount += sender.weight;
    }

    /// @dev Computes the winning proposal taking all
    /// previous votes into account.
    function winningProposal() public view
            returns (uint winningProposal_)
    {
        uint winningVoteCount = 0;
        for (uint p = 0; p < proposals.length; p++) {
            if (proposals[p].voteCount > winningVoteCount) {
                winningVoteCount = proposals[p].voteCount;
                winningProposal_ = p;
            }
        }
    }

    // Calls winningProposal() function to get the index
    // of the winner contained in the proposals array and then
    // returns the name of the winner
    function winnerName() external view
            returns (bytes32 winnerName_)
    {
        winnerName_ = proposals[winningProposal()].name;
    }
}
```

## Adam's Contributions

### Metamask Test Wallet
https://goerli.etherscan.io/address/0x01b5af9976658a33a9809d4261225FAc2f53a9DD

### Repository
Repository code for this project can be found here:
[Week 2 Project](https://github.com/asteinberger/encode-bootcamp-homework/tree/feature/adam-steinberger-week-2)

### State Changes
1. Deployment
2. Give Right To Vote (multiple)
3. Vote

### Edge Cases
![](https://i.imgur.com/9pUHuaq.png)
![](https://i.imgur.com/qlsfhQn.png)

## Dan transactions

### Metamask Wallet
Dan's Wallet: 0xEFC0D955536ed993F93177bdaCdA5d266083F573


### First Transaction

- Attempted to vote without permission granted by the chairperson, transaction reverted.
hash: 0x8626f786afa5de5d037b4a57ae1640fe324546f2c5ff396679318d7e2ff88ff9

### Second Transaction

- Chairperson grants me the right to vote.
hash: 0x4c2bf8e0e5466817aced5ce943df71b451f51d30de128b1aec5147ee90e3f6d6

- I proceed to vote for proposal 2, successful transaction. 
hash: 0xca459bd9f0201a2f3545536275b5f663eb654933a5e38a11274585b20ce14124

#### State Changes:
- Voter struct with my address created, 1 weight added, vote cast = true. 

### Third transaction
I attempt to give the right to vote, even though I am not the chairperson. This transaction is reverted.
- hash: 0x9c4479536e69ad7a675c4f0039a8f4a2ca807ef01a4547ee8f46fe6319ed6702

## David E. Perez Negron R. transactions

### Personal Repository

https://github.com/P1R/ballot

### Specification (TeamWork)
First we get voting rights from the chair person to two address I own,
1. Call the delegation from the first wallet to delegate that vote to the second wallet.
2. Call the vote function from the second wallet (delegated) which will have a vote weight of 2.

### Metamask Wallets
David's Wallet: 
0x934a406B7CAB0D8cB3aD201f0cdcA6a7855F43b0 `-Delegator`
0xD64258a33E7AC0294a9fdE8e4C9A76674bD33A23 `-Voter`

### DelegatingVotes.ts Code

```typescript
import { ethers } from "hardhat";
import { Ballot__factory } from "../typechain-types";
import * as dotenv from 'dotenv';
import { Signer } from "ethers";
dotenv.config();

async function main() {
  
  const provider = new ethers.providers.InfuraProvider(
      "goerli",
      process.env.INFURA_API_KEY
  );

  console.log({ provider });
  const pkey = process.env.PRIVATE_KEY;
  console.log({ pkey });
  const lastBlock = await provider.getBlock("latest");
  console.log({ lastBlock });
  const wallet = new ethers.Wallet(`${pkey}`);
  const signer = wallet.connect(provider);

  const ballotFactory = await new Ballot__factory(signer);
  const ballotContract = await ballotFactory.attach(
    "0xaf5bd48C8dd8F733697e148F952c62868A701b71"
  );
  console.log(
    `attached contract address is ${ballotContract.address}` 
  );
  const delegate = await 
  ballotContract.delegate("0xD64258a33E7AC0294a9fdE8e4C9A76674bD33A23")
  console.log(delegate)
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

```
>Note: when we call the delegate function we send as parameter the second address

### First Transaction 
**Call setText method:**

![](https://i.imgur.com/CEtMJUh.png)

img aaa.
>img aaa. shows the delegate return data"

transactionId: https://goerli.etherscan.io/tx/0xd488124d6f7c94130abe370496fee4a3b914ae3d647e301835a057f3346dddaf


### Votes.ts Code
```typescript
import { ethers } from "hardhat";
import { Ballot__factory } from "../typechain-types";
import * as dotenv from 'dotenv';
import { Signer } from "ethers";
dotenv.config();

async function main() {
  
  const provider = new ethers.providers.InfuraProvider(
      "goerli",
      process.env.INFURA_API_KEY
  );

  console.log({ provider });
  const pkey = process.env.PRIVATE_KEY_VOTE;
  console.log({ pkey });
  const lastBlock = await provider.getBlock("latest");
  console.log({ lastBlock });
  const wallet = new ethers.Wallet(`${pkey}`);
  const signer = wallet.connect(provider);

  const ballotFactory = await new Ballot__factory(signer);
  const ballotContract = await ballotFactory.attach(
    "0xaf5bd48C8dd8F733697e148F952c62868A701b71"
  );
  console.log(
    `attached contract address is ${ballotContract.address}` 
  );
  const vote = await ballotContract.vote("2")
  console.log(vote)
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

```
> Note: the env.PRIVATE_KEY_VOTE is the second wallet private key, after we connect we vote for the second option with the weight of 2 because this voter wallet got delegated from the trasaction 1.

### Second Transaction

![](https://i.imgur.com/d4U95UL.png)

img bbb.
>img bbb. shows the vote return data"

transactionId: 
https://goerli.etherscan.io/tx/0x4e2a141a542b7fd1f42cb83cfb3c58f389c21d0009483462deb4fd06b18d7383

## Cesar transactions

Interacted with Contract `'0xaf5bd48C8dd8F733697e148F952c62868A701b71'`

**Call vote method:**

transactionId:
https://goerli.etherscan.io/tx/0x2e211c70bd4b008a8cad147b1543acc93bcba8238157d20de6d47f3707f0b36f

This transaction executes a call to initiate a state change and 'vote' if a user has voting delegations


## Rebecca transactions

### Successful Vote
Vote confirmation: https://goerli.etherscan.io/tx/0x458c495c2caea4585b68bf49ed7be6deeac1df971d48a8da15ae529064e25487

### Main bugs/obstacles/lessons
- goerli wallet was not properly connected
    - did not confirm that my wallet was connected when sending the vote
    - did not change my wallet currency to goerli before reconnecting my wallet; as a result, i almost paid my gas fee in ETH
- did not input the proper information for voting for a specific proposal
    - I kept trying to input a string instead of a number defined in the script. as a result, i kept getting "out of bounds" errors
- had issues understanding how all the code connected
    - like the week before, i am still facing obstables in understanding how each part of the code works together to interact with a smart contract. unlike last week, i've learned that documentation is not enough for me -- i need to reach out to my classmates, TA and programming friends for help. i will now be communicating more frequently with all of them, and setting up study sessions.


## Brent transactions
### First Transaction
https://goerli.etherscan.io/tx/0xef0443745cf85d781393ea8bc4febe85643b1831bb4d2e2d4f44ca53ec3b3961
#### State Changes
1. "Yo, whats up bro"

## Contact and Developers

- [David E. Perez Negron R.](mailto:david@neetsec.com) Github: @P1R
- [Rebecca Duke Wiesenberg](mailto:rdukewiesenb@gmail.com) Github: @rdukewiesenb
- [Adam Steinberger](mailto:adam@asteinbe.com) | Github: @asteinberger | Discord: steinz08#3291

## References

\[1\] Encode Club Solidity Bootcamp , "Lesson 8 - Scripts for Ballot.sol", https://github.com/Encode-Club-Solidity-Bootcamp/Lesson-08, 2023.
\[2\] docs.soliditylang.org , "Solidity by Example", https://docs.soliditylang.org/en/latest/solidity-by-example.html#voting, 2023.
