TODO about batch adding

TODO about batch adding

pragma solidity ^0.4.4;

contract PunchClock {
    // the owner of the contract
    address owner;

    // The data structure to store the time in and out of a person
    struct PunchCard {
        uint timeIn; // time the person gets in, unix timestamp
        uint timeOut; // time the person gets out, unix timestamp
    }

    // The list of all admins. The reason for having these two mapping is that
    // it's not possible to iterate through the list of keys in a mapping,
    // so the workaround is to have two mapping, with the second mapping is basically
    // just a map by index so that we can get all the keys. Similarly, it's not
    // possible to iterate through a mapping, so the workaround is to keep track
    // of the size manually.
    mapping(address => bool) admins;
    mapping(uint => address) adminsByIndex;
    uint totalNumberOfAdmins;

    // The list of all members.
    mapping(address => bool) members;
    mapping(uint => address) membersByIndex;
    uint totalNumberOfMembers;

    // All punch cards of all members
    mapping(address => PunchCard[]) punchClock;

    // Constructor, create a new punch clock and assign the creator as the owner of the punch clock
    function PunchClock() {
        owner = msg.sender;
        admins[owner] = true;
        adminsByIndex[0] = owner;
        totalNumberOfAdmins = 1;
        members[owner] = true;
        membersByIndex[0] = owner;
        totalNumberOfMembers = 1;
    }

    modifier onlyOwner() {
        if (msg.sender != owner) throw;
        _;
    }
    modifier onlyAdmins() {
        if (admins[msg.sender] == false) throw;
        _;
    }
    modifier onlyMembers() {
        if (members[msg.sender] == false) throw;
        _;
    }

    // Add a member to the contract if the member does not already exist
    function addMemberInternal(address member) internal {
        if (members[member] == false) {
            var newMemberIndex = totalNumberOfMembers;
            members[member] = true;
            membersByIndex[newMemberIndex] = member;
            totalNumberOfMembers++;
        }
    }
    // Add a new admin. Only the owner can perform this task.
    function addAdmin(address admin) onlyOwner {
        if (admins[admin] == false) {
            var indexOfNewAdmin = totalNumberOfAdmins;
            admins[admin] = true;
            adminsByIndex[indexOfNewAdmin] = admin;
            totalNumberOfAdmins++;

            addMemberInternal(admin);
        }
    }

    // Add a new member to the list of member. Only admins can perform this task
    function addMember(address member) onlyAdmins {
        addMemberInternal(member);
    }

    // Return all punch cards of a member
    function getPunchCardsInternal(address member) internal returns(uint[2][]) {
        var allCards = punchClock[member];
        uint[2][] memory tmp = new uint[2][](allCards.length);
        for (uint i = 0; i < allCards.length; i++) {
            tmp[i] = [allCards[i].timeIn, allCards[i].timeOut];
        }
        return tmp;
    }

    // Return all punch cards of the requestor. Only member can perform this task
    function getMyPunchCards() onlyMembers constant returns(uint[2][] punchCards) {
        getPunchCardsInternal(msg.sender);
    }

    // Return all punch cards of a member. Only admin can perform this task
    function getPunchCardsOf(address member) onlyAdmins constant returns(uint[2][] punchcards) {
        getPunchCardsInternal(member);
    }

    // Return all members in the contract. Only admins can perform this task.
    function getAllMembers() onlyAdmins constant returns(address[]) {
        address[] memory allMembers = new address[](totalNumberOfMembers);
        for (uint i = 0; i < totalNumberOfMembers; i++) {
            allMembers[i] = membersByIndex[i];
        }
        return allMembers;
    }

    // Return all admins in the contract. Only owner can perform this task.
    function getAllAdmins() onlyOwner constant returns(address[]) {
        address[] memory allAdmins = new address[](totalNumberOfAdmins);
        for (uint i = 0; i < totalNumberOfAdmins; i++) {
            allAdmins[i] = adminsByIndex[i];
        }
        return allAdmins;
    }

    // Helper function to get the last element in an array
    function getLast(PunchCard[] punchCards) internal returns(PunchCard) {
        return punchCards[punchCards.length - 1];
    }

    // Add a new punch card into an array of cards
    function getNewCardInternal(uint inTime) internal returns(PunchCard) {
        PunchCard({
            timeIn: inTime,
            timeOut: 0
        });
    }

    // Register an in time for a member. Only admins can perform this task.
    function punchIn(address member, uint inTime) onlyAdmins {
        // If the member does not exist, throw
        if (members[member] == false) throw;

        var allCards = punchClock[member];
        if (allCards.length == 0) {
            allCards.push(getNewCardInternal(inTime));
        } else {
            var lastCard = getLast(allCards);
            if (lastCard.timeOut == 0) {
                // If there's an incomplete card, just update the in time of this card
                lastCard.timeIn = inTime;
            } else {
                allCards.push(getNewCardInternal(inTime));
            }
        }
    }

    // Register an out time for a member. Only admins can perform this task.
    function punchOut(address member, uint outTime) onlyAdmins {
        // If the member does not exist, throw
        if (members[member] == false) throw;

        var allCards = punchClock[member];
        if (allCards.length == 0) throw;
        var lastCard = getLast(allCards);
        if (lastCard.timeOut != 0) throw;
        lastCard.timeOut = outTime;
    }

    // TODO: batch adding
    // function addAdmins(address[] admins) onlyOwner
    // function addMembers(address[] members) onlyAdmins

    // TODO: batch punching
    //  function batchPunchIn(address[] members,  uint[] inTimes) onlyAdmins
    //  function batchPunchOut(address[] members,  uint[] outTimes) onlyAdmins
}

pragma solidity ^0.4.4;

contract PunchClock {
    // the owner of the contract
    address owner;

    // The data structure to store the time in and out of a person
    struct PunchCard {
        uint timeIn; // time the person gets in, unix timestamp
        uint timeOut; // time the person gets out, unix timestamp
    }

    // The list of all admins. The reason for having these two mapping is that
    // it's not possible to iterate through the list of keys in a mapping,
    // so the workaround is to have two mapping, with the second mapping is basically
    // just a map by index so that we can get all the keys. Similarly, it's not
    // possible to iterate through a mapping, so the workaround is to keep track
    // of the size manually.
    mapping(address => bool) admins;
    mapping(uint => address) adminsByIndex;
    uint totalNumberOfAdmins;

    // The list of all members.
    mapping(address => bool) members;
    mapping(uint => address) membersByIndex;
    uint totalNumberOfMembers;

    // All punch cards of all members
    mapping(address => PunchCard[]) punchClock;

    // Constructor, create a new punch clock and assign the creator as the owner of the punch clock
    function PunchClock() {
        owner = msg.sender;
        admins[owner] = true;
        adminsByIndex[0] = owner;
        totalNumberOfAdmins = 1;
        members[owner] = true;
        membersByIndex[0] = owner;
        totalNumberOfMembers = 1;
    }

    modifier onlyOwner() {
        if (msg.sender != owner) throw;
        _;
    }
    modifier onlyAdmins() {
        if (admins[msg.sender] == false) throw;
        _;
    }
    modifier onlyMembers() {
        if (members[msg.sender] == false) throw;
        _;
    }

    // Add a member to the contract if the member does not already exist
    function addMemberInternal(address member) internal {
        if (members[member] == false) {
            var newMemberIndex = totalNumberOfMembers;
            members[member] = true;
            membersByIndex[newMemberIndex] = member;
            totalNumberOfMembers++;
        }
    }
    // Add a new admin. Only the owner can perform this task.
    function addAdmin(address admin) onlyOwner {
        if (admins[admin] == false) {
            var indexOfNewAdmin = totalNumberOfAdmins;
            admins[admin] = true;
            adminsByIndex[indexOfNewAdmin] = admin;
            totalNumberOfAdmins++;

            addMemberInternal(admin);
        }
    }

    // Add a new member to the list of member. Only admins can perform this task
    function addMember(address member) onlyAdmins {
        addMemberInternal(member);
    }

    // Return all punch cards of a member
    function getPunchCardsInternal(address member) internal returns(uint[2][]) {
        var allCards = punchClock[member];
        uint[2][] memory tmp = new uint[2][](allCards.length);
        for (uint i = 0; i < allCards.length; i++) {
            tmp[i] = [allCards[i].timeIn, allCards[i].timeOut];
        }
        return tmp;
    }

    // Return all punch cards of the requestor. Only member can perform this task
    function getMyPunchCards() onlyMembers constant returns(uint[2][] punchCards) {
        getPunchCardsInternal(msg.sender);
    }

    // Return all punch cards of a member. Only admin can perform this task
    function getPunchCardsOf(address member) onlyAdmins constant returns(uint[2][] punchcards) {
        getPunchCardsInternal(member);
    }

    // Return all members in the contract. Only admins can perform this task.
    function getAllMembers() onlyAdmins constant returns(address[]) {
        address[] memory allMembers = new address[](totalNumberOfMembers);
        for (uint i = 0; i < totalNumberOfMembers; i++) {
            allMembers[i] = membersByIndex[i];
        }
        return allMembers;
    }

    // Return all admins in the contract. Only owner can perform this task.
    function getAllAdmins() onlyOwner constant returns(address[]) {
        address[] memory allAdmins = new address[](totalNumberOfAdmins);
        for (uint i = 0; i < totalNumberOfAdmins; i++) {
            allAdmins[i] = adminsByIndex[i];
        }
        return allAdmins;
    }

    // Helper function to get the last element in an array
    function getLast(PunchCard[] punchCards) internal returns(PunchCard) {
        return punchCards[punchCards.length - 1];
    }

    // Add a new punch card into an array of cards
    function getNewCardInternal(uint inTime) internal returns(PunchCard) {
        PunchCard({
            timeIn: inTime,
            timeOut: 0
        });
    }

    // Register an in time for a member. Only admins can perform this task.
    function punchIn(address member, uint inTime) onlyAdmins {
        // If the member does not exist, throw
        if (members[member] == false) throw;

        var allCards = punchClock[member];
        if (allCards.length == 0) {
            allCards.push(getNewCardInternal(inTime));
        } else {
            var lastCard = getLast(allCards);
            if (lastCard.timeOut == 0) {
                // If there's an incomplete card, just update the in time of this card
                lastCard.timeIn = inTime;
            } else {
                allCards.push(getNewCardInternal(inTime));
            }
        }
    }

    // Register an out time for a member. Only admins can perform this task.
    function punchOut(address member, uint outTime) onlyAdmins {
        // If the member does not exist, throw
        if (members[member] == false) throw;

        var allCards = punchClock[member];
        if (allCards.length == 0) throw;
        var lastCard = getLast(allCards);
        if (lastCard.timeOut != 0) throw;
        lastCard.timeOut = outTime;
    }

    // TODO: batch punching
    //  function batchPunchIn(mapping(address => uint) memberToTimeIn) onlyAdmins
    //  function batchPunchOut(mapping(address => uint) memberToTimeOut) onlyAdmins
}


added basic directive contract

added basic directive contract

pragma solidity ^0.4.11;

import "./SafeMath.sol";
import "./ERC20.sol";
import "./Power.sol";
import "./Nutz.sol";
import "./ERC223ReceivingContract.sol";

contract IcoPolicy {
    uint256 minRaise;
    uint256 maxRaise;
    uint256 minDuration;
    uint256 maxDuration;
    address milestoneAdr;
    uint256 startTime;
    bool started;
    uint256 ntzAddr;

    function IcoPolicy( uint256 _minRaise,
                        uint256 _maxRaise,
                        uint256 _minDuration,
                        uint256 _maxDuration,
                        address _milestoneAdr,
                        uint256 _startTime,
                        address _ntzAddr) {
            minRaise = _minRaise;
            maxRaise = _maxRaise;
            minDuration = _minDuration;
            maxDuration = _maxDuration;
            milestoneAdr = _milestoneAdr;
            startTime = _startTime;
            started = false;
            ntzAddr = _ntzAddr;
    }

    function tick() {
        var nutzContract = Nutz(ntzAddr);
        uint256 raised = nutzContract.balanceOf(ntzAddr); // ??
        // check if funding goal reached
        if (!ended && icoEnded(raised)) {
            var totalSupply = nutzContract.totalSupply();
            ended = true;
            nutzContract.moveCeiling(REGULAR_PRICE);
            nutzContract.dilutePower(totalSupply);
        }

        if (!started && now >= _startTime) {
            started = true;
            nutzContract.moveCeiling(DISCOUNT_PRICE);
        }

        // check if milestone is reached an allocate funds for founders
    }

    function icoEnded(uint256 funded) returns (bool) {
        // maybe more conditions
        return (now - startTime >= maxDuration || funded >= maxRaise)
    }

    function icoStarted(uint256 funded) returns (bool) {
        return (now >= _startTime)
    }

    function mileStonePayout() {

    }
}

error: pathspec 'contracts/IcoPolicy.sol' did not match any file(s) known to git


First crack at events

First crack at events

//SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import "@openzeppelin/contracts/access/Ownable.sol";

import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";

interface IKetherHomepage {
  function ads(uint _idx) external view returns (address,uint,uint,uint,uint,string memory,string memory,string memory,bool,bool);
  function getAdsLength() view external returns (uint);
}

interface IERC721 {
  function ownerOf(uint256) external view returns (address);
  function balanceOf(address) external view returns (uint256);
  function tokenOfOwnerByIndex(address, uint256) external view returns (uint256);
}

interface IERC20 {
  function balanceOf(address account) external view returns (uint256);
  function transfer(address recipient, uint256 amount) external returns (bool);
}

library Errors {
  string constant MustHaveBalance = "must have tokens to nominate";
  string constant OnlyMagistrate = "only active magistrate can do this";
  string constant MustHaveEntropy = "waiting for entropy";
  string constant MustHaveNominations = "must have nominations";
  string constant AlreadyStarted = "election already started";
  string constant NotExecuted = "election not executed";
  string constant TermNotExpired = "term not expired";
  string constant NotEnoughLink = "not enough LINK";
}

contract KetherSortition is Ownable, VRFConsumerBase {
  event Nomination(
      uint256 indexed termNumber,
      address nominator,
      uint256 pixels
  );

  event ElectionExecuting(
    uint256 indexed termNumber
  );

  event ElectionCompleted(
    uint256 indexed termNumber,
    uint256 magistrateToken,
    address currentTokenOwner
  );

  event StepDown(
    uint256 indexed termNumber,
    uint256 magistrateToken,
    address currentTokenOwner
  );

  // MagistrateToken is tokenId of an NFT whose owner controls the royalties purse for this term.
  uint256 public magistrateToken;

  uint256 constant MIN_ELECTION_DURATION = 2 days;
  uint256 constant TERM_DURATION = 6 weeks;
  uint256 constant PIXELS_PER_CELL = 100;

  uint256 public termStarted;
  uint256 public termExpires;
  uint256 public termNumber = 0;

  IERC721 ketherNFTContract;
  IKetherHomepage ketherContract;

  uint256[] public nominatedTokens;
  uint256 public nominatedPixels = 0;
  mapping(uint256 => uint256) nominations; // mapping of tokenId => termNumber
  // TODO: mapping(uint256 => uint256) electedCount;

  uint256 public electionEntropy; // Provided by Chainlink

  // nominating -[term expired & startElection() calls]> waitingForEntropy -[Chainlink calls into fulfillrandomness()]> gotEntropy -[completeElection()] -> nominating
  enum StateMachine { NOMINATING, WAITING_FOR_ENTROPY, GOT_ENTROPY }
  StateMachine state = StateMachine.NOMINATING;

  // Chainlink values
  bytes32 private s_keyHash;
  uint256 private s_fee;

  constructor(address _ketherNFTContract, address _ketherContract, address vrfCoordinator, address link, bytes32 keyHash, uint256 fee)
  public
  VRFConsumerBase(vrfCoordinator, link) {
    s_keyHash = keyHash;
    s_fee = fee;

    ketherNFTContract = IERC721(_ketherNFTContract);
    ketherContract = IKetherHomepage(_ketherContract);

    termExpires = block.timestamp + MIN_ELECTION_DURATION;
  }

  // Internal helpers:

  /**
   * @dev Only callable by Chainlink VRF, async triggered via startElection().
   */
  function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
    require(state == StateMachine.WAITING_FOR_ENTROPY, Errors.NotExecuted);
    electionEntropy = randomness;
    state = StateMachine.GOT_ENTROPY;
  }

  // Views:

  function getMagistrate() public view returns (address) {
    return getAdOwner(magistrateToken);
  }

  function getAdOwner(uint256 _idx) public view returns (address) {
    return ketherNFTContract.ownerOf(_idx);
  }

  function getAdPixels(uint256 _idx) public view returns (uint256) {
    (,,,uint width,uint height,,,,,) = ketherContract.ads(_idx);
    return width * height * PIXELS_PER_CELL;
  }

  function isNominated(uint256 _idx) public view returns (bool) {
    return nominations[_idx] > termNumber;
  }

  function getNextMagistrateToken() public view returns (uint256) {
    require(state == StateMachine.GOT_ENTROPY, Errors.MustHaveEntropy);
    require(nominatedTokens.length > 0, Errors.MustHaveNominations);

    uint256 pixelChosen = electionEntropy % nominatedPixels;
    uint256 curPixel = 0;

    for(uint256 i = 0; i < nominatedTokens.length; i++) {
      uint256 idx = nominatedTokens[i];
      curPixel += getAdPixels(idx);
      if (curPixel > pixelChosen) {
        return idx;
      }
    }
    return 0;
  }

  // External interface:

  /**
   * @dev Nominate tokens held by the sender as candidates for magistrate in the next term.
   *      Nominations of tokens are independent of their owner.
   * @return Number of nominated pixels
   */
  function nominateSelf() external returns (uint256) {
    require(state == StateMachine.NOMINATING, Errors.AlreadyStarted);
    address sender = _msgSender();
    require(ketherNFTContract.balanceOf(sender) > 0, Errors.MustHaveBalance);

    uint256 pixels = 0;
    for (uint256 i = 0; i < ketherNFTContract.balanceOf(sender); i++) {
      uint256 idx = ketherNFTContract.tokenOfOwnerByIndex(sender, i);
      if (!isNominated(idx)) {
        pixels += getAdPixels(idx);
        nominations[idx] = termNumber + 1;
        nominatedTokens.push(idx);
      }
    }

    nominatedPixels += pixels;

    emit Nomination(termNumber, sender, pixels);
    return pixels;
  }

  // TODO: Do we want nominateOther, so people can easily delegate their nominations?

  // TODO: Do we want to have a unNominateSelf()

  /**
   * @dev Stop accepting nominations, start election.
   */
  function startElection() external {
    // FIXME: check that term expired
    require(state == StateMachine.NOMINATING, Errors.AlreadyStarted);
    require(nominatedTokens.length > 0, Errors.MustHaveNominations);
    require(termExpires <= block.timestamp, Errors.TermNotExpired);
    require(LINK.balanceOf(address(this)) >= s_fee, Errors.NotEnoughLink);

    // TODO: check if this is a re-entry vector
    state = StateMachine.WAITING_FOR_ENTROPY;
    requestRandomness(s_keyHash, s_fee);

    emit ElectionExecuting(termNumber);
  }

  /**
   * @dev Assign new magistrate and open up for nominations for next election.
   */
  function completeElection() external {
    require(state == StateMachine.GOT_ENTROPY, Errors.MustHaveEntropy);
    magistrateToken = getNextMagistrateToken();

    // FIXME: This is going to stagger terms, do we want to align them to
    // royalty payouts? Or maybe we could assign payouts to terms on a payment
    // receiver.
    termNumber += 1;
    termStarted = block.timestamp;
    termExpires = termStarted + TERM_DURATION;

    delete nominatedTokens;
    nominatedPixels = 0;
    state = StateMachine.NOMINATING;

    emit ElectionCompleted(termNumber, magistrateToken, getMagistrate());
  }

  // Only magistrate:

  /// @dev Transfer balance controlled by magistrate.
  function withdraw(address payable to) public {
    require(_msgSender() == getMagistrate(), Errors.OnlyMagistrate);
    // NOTE: you have exclusive rights to withdraw until the end of your term.
    // afterwards it becomes a race as someone call call an election.

    // FIXME: Would it be fun if this required having a >2 LINK balance to
    // withdraw? If we wanna be super cute, could automagically buy LINK from
    // the proceeds before transferring the remaining balance.

    to.transfer(address(this).balance);
  }

  /// @dev Cut the term short, leaving enough time for new nominations.
  function stepDown() public {
    require(_msgSender() == getMagistrate(), Errors.OnlyMagistrate);

    uint256 timeRemaining = termExpires - block.timestamp;
    if (timeRemaining > MIN_ELECTION_DURATION) {
      termExpires = block.timestamp + MIN_ELECTION_DURATION;
    }

    emit StepDown(termNumber, magistrateToken, _msgSender());
  }

  // Only owner (admin helpers):

  // TODO: adminUpdateChainlinkValues(bytes32 keyHash, uint256 fee) external onlyOwner

  function adminDelayNextEpoch(uint256 nextEpoch) external onlyOwner {
    // XXX: Implement this.
    // TODO: Should this also allow adjusting the interval?
  }

  /**
   * @dev Withdraw ERC20 tokens, primarily for rescuing remaining LINK once the
   *      experiment is over.
   */
  function adminWithdrawToken(IERC20 token, address to) external onlyOwner {
    // XXX: Add require to confirm that the contract is suspended?
    token.transfer(to, token.balanceOf(address(this)));
  }
}

//SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import "@openzeppelin/contracts/access/Ownable.sol";

import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";

interface IKetherHomepage {
  function ads(uint _idx) external view returns (address,uint,uint,uint,uint,string memory,string memory,string memory,bool,bool);
  function getAdsLength() view external returns (uint);
}

interface IERC721 {
  function ownerOf(uint256) external view returns (address);
  function balanceOf(address) external view returns (uint256);
  function tokenOfOwnerByIndex(address, uint256) external view returns (uint256);
}

interface IERC20 {
  function balanceOf(address account) external view returns (uint256);
  function transfer(address recipient, uint256 amount) external returns (bool);
}

library Errors {
  string constant MustHaveBalance = "must have tokens to nominate";
  string constant OnlyMagistrate = "only active magistrate can do this";
  string constant MustHaveEntropy = "waiting for entropy";
  string constant MustHaveNominations = "must have nominations";
  string constant AlreadyStarted = "election already started";
  string constant NotExecuted = "election not executed";
  string constant TermNotExpired = "term not expired";
  string constant NotEnoughLink = "not enough LINK";
}

// TODO: Emit events.

contract KetherSortition is Ownable, VRFConsumerBase {
  // MagistrateToken is tokenId of an NFT whose owner controls the royalties purse for this term.
  uint256 public magistrateToken;

  uint256 constant MIN_ELECTION_DURATION = 2 days;
  uint256 constant TERM_DURATION = 6 weeks;
  uint256 constant PIXELS_PER_CELL = 100;

  uint256 public termStarted;
  uint256 public termExpires;
  uint256 public termNumber = 0;

  IERC721 ketherNFTContract;
  IKetherHomepage ketherContract;

  uint256[] public nominatedTokens;
  uint256 public nominatedPixels = 0;
  mapping(uint256 => uint256) nominations; // mapping of tokenId => termNumber
  // TODO: mapping(uint256 => uint256) electedCount;

  uint256 public electionEntropy; // Provided by Chainlink

  // nominating -[term expired & startElection() calls]> waitingForEntropy -[Chainlink calls into fulfillrandomness()]> gotEntropy -[completeElection()] -> nominating
  enum StateMachine { NOMINATING, WAITING_FOR_ENTROPY, GOT_ENTROPY }
  StateMachine state = StateMachine.NOMINATING;

  // Chainlink values
  bytes32 private s_keyHash;
  uint256 private s_fee;

  constructor(address _ketherNFTContract, address _ketherContract, address vrfCoordinator, address link, bytes32 keyHash, uint256 fee)
  public
  VRFConsumerBase(vrfCoordinator, link) {
    s_keyHash = keyHash;
    s_fee = fee;

    ketherNFTContract = IERC721(_ketherNFTContract);
    ketherContract = IKetherHomepage(_ketherContract);

    termExpires = block.timestamp + MIN_ELECTION_DURATION;
  }

  // Internal helpers:

  /**
   * @dev Only callable by Chainlink VRF, async triggered via startElection().
   */
  function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
    require(state == StateMachine.WAITING_FOR_ENTROPY, Errors.NotExecuted);
    electionEntropy = randomness;
    state = StateMachine.GOT_ENTROPY;
  }

  // Views:

  function getMagistrate() public view returns (address) {
    return getAdOwner(magistrateToken);
  }

  function getAdOwner(uint256 _idx) public view returns (address) {
    return ketherNFTContract.ownerOf(_idx);
  }

  function getAdPixels(uint256 _idx) public view returns (uint256) {
    (,,,uint width,uint height,,,,,) = ketherContract.ads(_idx);
    return width * height * PIXELS_PER_CELL;
  }

  function isNominated(uint256 _idx) public view returns (bool) {
    return nominations[_idx] > termNumber;
  }

  function getNextMagistrateToken() public view returns (uint256) {
    require(state == StateMachine.GOT_ENTROPY, Errors.MustHaveEntropy);
    require(nominatedTokens.length > 0, Errors.MustHaveNominations);

    uint256 pixelChosen = electionEntropy % nominatedPixels;
    uint256 curPixel = 0;

    for(uint256 i = 0; i < nominatedTokens.length; i++) {
      uint256 idx = nominatedTokens[i];
      curPixel += getAdPixels(idx);
      if (curPixel > pixelChosen) {
        return idx;
      }
    }
    return 0;
  }

  // External interface:

  /**
   * @dev Nominate tokens held by the sender as candidates for magistrate in the next term.
   *      Nominations of tokens are independent of their owner.
   * @return Number of nominated pixels
   */
  function nominateSelf() external returns (uint256) {
    require(state == StateMachine.NOMINATING, Errors.AlreadyStarted);
    address sender = _msgSender();
    require(ketherNFTContract.balanceOf(sender) > 0, Errors.MustHaveBalance);

    uint256 pixels = 0;
    for (uint256 i = 0; i < ketherNFTContract.balanceOf(sender); i++) {
      uint256 idx = ketherNFTContract.tokenOfOwnerByIndex(sender, i);
      if (!isNominated(idx)) {
        pixels += getAdPixels(idx);
        nominations[idx] = termNumber + 1;
        nominatedTokens.push(idx);
        // TODO: emit nominated event
      }
    }

    nominatedPixels += pixels;
    return pixels;
  }

  // TODO: Do we want nominateOther, so people can easily delegate their nominations?

  // TODO: Do we want to have a unNominateSelf()

  /**
   * @dev Stop accepting nominations, start election.
   */
  function startElection() external {
    // FIXME: check that term expired
    require(state == StateMachine.NOMINATING, Errors.AlreadyStarted);
    require(nominatedTokens.length > 0, Errors.MustHaveNominations);
    require(termExpires <= block.timestamp, Errors.TermNotExpired);
    require(LINK.balanceOf(address(this)) >= s_fee, Errors.NotEnoughLink);

    // TODO: check if this is a re-entry vector
    state = StateMachine.WAITING_FOR_ENTROPY;
    requestRandomness(s_keyHash, s_fee);
  }

  /**
   * @dev Assign new magistrate and open up for nominations for next election.
   */
  function completeElection() external {
    require(state == StateMachine.GOT_ENTROPY, Errors.MustHaveEntropy);
    magistrateToken = getNextMagistrateToken();

    // FIXME: This is going to stagger terms, do we want to align them to
    // royalty payouts? Or maybe we could assign payouts to terms on a payment
    // receiver.
    termNumber += 1;
    termStarted = block.timestamp;
    termExpires = termStarted + TERM_DURATION;

    delete nominatedTokens;
    nominatedPixels = 0;
    state = StateMachine.NOMINATING;
  }

  // Only magistrate:

  /// @dev Transfer balance controlled by magistrate.
  function withdraw(address payable to) public {
    require(_msgSender() == getMagistrate(), Errors.OnlyMagistrate);
    // NOTE: you have exclusive rights to withdraw until the end of your term.
    // afterwards it becomes a race as someone call call an election.

    // FIXME: Would it be fun if this required having a >2 LINK balance to
    // withdraw? If we wanna be super cute, could automagically buy LINK from
    // the proceeds before transferring the remaining balance.

    to.transfer(address(this).balance);
  }

  /// @dev Cut the term short, leaving enough time for new nominations.
  function stepDown() public {
    require(_msgSender() == getMagistrate(), Errors.OnlyMagistrate);

    uint256 timeRemaining = termExpires - block.timestamp;
    if (timeRemaining > MIN_ELECTION_DURATION) {
      termExpires = block.timestamp + MIN_ELECTION_DURATION;
    }

    // TODO: Emit event
  }

  // Only owner (admin helpers):

  // TODO: adminUpdateChainlinkValues(bytes32 keyHash, uint256 fee) external onlyOwner

  function adminDelayNextEpoch(uint256 nextEpoch) external onlyOwner {
    // XXX: Implement this.
    // TODO: Should this also allow adjusting the interval?
  }

  /**
   * @dev Withdraw ERC20 tokens, primarily for rescuing remaining LINK once the
   *      experiment is over.
   */
  function adminWithdrawToken(IERC20 token, address to) external onlyOwner {
    // XXX: Add require to confirm that the contract is suspended?
    token.transfer(to, token.balanceOf(address(this)));
  }
}


Remove duplicated _permitted function.

Remove duplicated _permitted function.

contract ProtectedContract is OwnedApiEnabled, PermissionsEnabled {
    function apiAuthorized() returns (bool result) {
        return super.apiAuthorized() || permittedSender();
    }

    function setApiAddress(address newApi) returns (bool result) {
        if (PermissionsEnabled(newApi).getPermissionsProvider() == 0x0) return false;
        return super.setApiAddress(newApi);
    }

    function getPermissionsProvider() returns (address result) {
        return PermissionsEnabled(api).getPermissionsProvider();
    }

    function setPermissionsProvider(address provider) returns (bool result) {
        return PermissionsEnabled(api).setPermissionsProvider(provider);
    }

    function permittedSender() returns (bool result) {
        if (api == 0x0) return false;
        return PermissionsProvider(PermissionsEnabled(api).getPermissionsProvider()).permitted(msg.sender);
    }
}

contract ProtectedContract is OwnedApiEnabled, PermissionsEnabled {
    function apiAuthorized() returns (bool result) {
        return super.apiAuthorized() || _permitted();
    }

    function setApiAddress(address newApi) returns (bool result) {
        if (PermissionsEnabled(newApi).getPermissionsProvider() == 0x0) return false;
        return super.setApiAddress(newApi);
    }

    function getPermissionsProvider() returns (address result) {
        return PermissionsEnabled(api).getPermissionsProvider();
    }

    function setPermissionsProvider(address provider) returns (bool result) {
        return PermissionsEnabled(api).setPermissionsProvider(provider);
    }

    function permittedSender() returns (bool result) {
        if (api == 0x0) return false;
        return PermissionsProvider(PermissionsEnabled(api).getPermissionsProvider()).permitted(msg.sender);
    }

    function _permitted() private returns (bool result) {
        if (api == 0x0) return false;
        return PermissionsProvider(PermissionsEnabled(api).getPermissionsProvider()).permitted(msg.sender);
    }
}


Remove extra parenthesis (#1919)

Remove extra parenthesis (#1919)

(cherry picked from commit 54182bf31c78fb1b16dfdce40fc9a6a177cb3bca)

pragma solidity ^0.5.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This call _does not revert_ if the signature is invalid, or
     * if the signer is otherwise unable to be retrieved. In those scenarios,
     * the zero address is returned.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        // Check the signature length
        if (signature.length != 65) {
            return (address(0));
        }

        // Divide the signature in r, s and v variables
        bytes32 r;
        bytes32 s;
        uint8 v;

        // ecrecover takes the signature parameters, and the only way to get them
        // currently is to use assembly.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            r := mload(add(signature, 0x20))
            s := mload(add(signature, 0x40))
            v := byte(0, mload(add(signature, 0x60)))
        }

        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return address(0);
        }

        if (v != 27 && v != 28) {
            return address(0);
        }

        // If the signature is valid (and not malleable), return the signer address
        return ecrecover(hash, v, r, s);
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * replicates the behavior of the
     * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
     * JSON-RPC method.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }
}

pragma solidity ^0.5.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This call _does not revert_ if the signature is invalid, or
     * if the signer is otherwise unable to be retrieved. In those scenarios,
     * the zero address is returned.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise)
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        // Check the signature length
        if (signature.length != 65) {
            return (address(0));
        }

        // Divide the signature in r, s and v variables
        bytes32 r;
        bytes32 s;
        uint8 v;

        // ecrecover takes the signature parameters, and the only way to get them
        // currently is to use assembly.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            r := mload(add(signature, 0x20))
            s := mload(add(signature, 0x40))
            v := byte(0, mload(add(signature, 0x60)))
        }

        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return address(0);
        }

        if (v != 27 && v != 28) {
            return address(0);
        }

        // If the signature is valid (and not malleable), return the signer address
        return ecrecover(hash, v, r, s);
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * replicates the behavior of the
     * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
     * JSON-RPC method.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }
}


Finished commenting Tag Contract and streamlined setAssessorPool

import "lib/random.sol";
import "userMaster.sol";
import "assessment.sol";
import "user.sol";
import "tagMaster.sol";

/*
@type: contract
@name: Tag
@purpose: To store tag data and create and store information abotu assessments of this tag
*/
contract Tag
{
  address[] parentTags; //The tags that this tag is child to (ie: Calculus is child to Math)
  address[] childTags; //The tags that this tag is parent to (ie: Math is parent to Calculus)
  address userMaster; //The address of the userMaster contract
  address tagMaster; //The address of the tagMaster contract
  address random; //The address of the random contract
  string name; //The name of the tag
  int maxScore = 0; //The highest score acheived for this tag
  uint maxSize = 5; //The largest assessment taken for this tag
  address[] owners; //Those who have earned the tag
  mapping (address => address[]) assessmentHistory; //All assessments completed
  mapping (address => int) currentScores; //The most recent score of a user
  mapping (address => uint) assessmentSizes; //The most recent size of an assessment taken by a user
  mapping(address => bool) assessmentExists; //All existing assessments

  /*
  @type: modifier
  @name: onlyUserMaster
  @purpose: to only allow the UserMaster contract to call a function to which this modifier is applied
  */
  modifier onlyUserMaster
  {
    if(msg.sender != userMaster) //checks if msg.sender has the same address as userMaster
    {
      throw; //throws the function call if not
    }
  }

  /*
  @type: modifier
  @name: onlyTagMaster
  @purpose: to only allow the TagMaster contract to call a function to which this modifier is applied
  */
  modifier onlyTagMaster
  {
    if(msg.sender != tagMaster) //checks if msg.sender has the same address as tagMaster
    {
      throw; //throws the function call if not
    }
  }

  /*
  @type: modifier
  @name: onlyThis
  @purpose: to only allow the this contract to call a function to which this modifier is applied
  */
  modifier onlyThis
  {
    if(msg.sender != address(this)) //Checks if msg.sender is this contract
    {
      throw; //Throws out the function call if it isn't
    }
  }

  /*
  @type: event
  @name: CompletedAssessment
  @purpose: To build a database of completed assessments
  */
  event CompletedAssessment
  ( address _assessee, //The address of the user who took the assessment
    bool _pass, //Whether or not the assessee passed the assessment
    int _score, //The score of the assessee
    address _assessment); //The address of the assessment

  /*
  @type: constructor function
  @purpose: To initialize the Tag contract and have it make the account tag
  @param: string tagName = the name of the tagName
  @param: address[] parents = the addresses of the tag's parents
  @param: address userMasterAddress = the address of the UserMaster contract
  @param: address tagMasterAddress = the address of the TagMaster that spawned this user
  @param: address randomAddress = the address of the ransom contract
  @returns: nothing
  */
  function Tag(string tagName, address[] parents, address userMasterAddress, address tagMasterAddress, address randomAddress)
  {
    name = tagName; //sets to value of name to that of tagName
    parentTags = parents; //sets the value of parentTags to that of parents
    userMaster = userMasterAddress; //sets the value of userMaster to that of userMasterAddress
    random = randomAddress; //sets the value of random to that of randomAddress
    tagMaster = tagMasterAddress; //sets the vale of tagMaster to that of tagMasterAddress
  }

  /*
  @type: function
  @purpose: To set the first user for this tag
  @param: address firstUser = the address of the first user to own the tag
  @returns: nothing
  */
  function addFirstUser(address firstUser) onlyUserMaster
  {
    if(owners.length == 0) //cheks if there aren't any owners yet
    {
      owners.push(firstUser); //If there aren't then firstUser is made to be an owner of this tag
    }
  }

  /*
  @type: function
  @purpose: To get the most recent score of a user
  @param: address user = the user whose score is to be checked
  @returns: The user's most recent score in the form of an int
  */
  function getCurrentScore(address user) constant returns(int)
  {
    return currentScores[user];
  }

  /*
  @type: function
  @purpose: To get the size of the most recent asssessment of a user
  @param: address user = the user whose assessment size is to be checked
  @returns: The user's most recent assessment size in the form of an uint
  */
  function getAssessmentSize(address user) constant returns(uint)
  {
    return assessmentSizes[user];
  }

  /*
  @type: function
  @purpose: To get the owners of this tag
  @returns: The users that own this tag in the form of an array of addresses
  */
  function getOwners() constant returns(address[])
  {
    return owners;
  }

  /*
  @type: function
  @purpose: To get the number of owners of this tag
  @returns: The number of users that own this tag in the form of an uint
  */
  function getOwnerLength() constant returns(uint)
  {
    return owners.length;
  }

  /*
  @type: function
  @purpose: To get a specific owner of this tag
  @param: uint index = the index of the user in the owners array
  @returns: The user that owns this tag with that index in the form of an address
  */
  function getOwner(uint index) constant returns(address)
  {
    return owners[index];
  }

  /*
  @type: function
  @purpose: To get the parents of this tag
  @returns: The parents of this tag in the form of an array of addresses
  */
  function getParents() constant returns(address[])
  {
    return parentTags;
  }

  /*
  @type: function
  @purpose: To get the number of parents for this tag
  @returns: The number of parents for this tag in the form of an uint
  */
  function getParentsLength() constant returns(uint)
  {
    return parentTags.length;
  }

  /*
  @type: function
  @purpose: To get a specific parent of this tag
  @param: uint index = the index of the tag in the parentTags array
  @returns: The tag that is parent to this tag with that index in the form of an address
  */
  function getParent(uint index) constant returns(address)
  {
    return parentTags[index];
  }

  /*
  @type: function
  @purpose: To add a parent to the tag
  @param: address parentAddress = the address of the new parent tag
  @returns: nothing
  */
  function addParent(address parentAddress) onlyTagMaster
  {
    parentTags.push(parentAddress);
  }

  /*
  @type: function
  @purpose: To get the children of this tag
  @returns: The children of this tag in the form of an array of addresses
  */
  function getChildren() constant returns(address[])
  {
    return childTags;
  }

  /*
  @type: function
  @purpose: To get the number of children of this tag
  @returns: The number of children of this tag in the form of an uint
  */
  function getChildrenLength() constant returns(uint)
  {
    return childTags.length;
  }

  /*
  @type: function
  @purpose: To get a specific child of this tag
  @param: uint index = the index of the tag in the childTags array
  @returns: The tag that is child to this tag with that index in the form of an address
  */
  function getChild(uint index) constant returns(address)
  {
    return childTags[index];
  }

  /*
  @type: function
  @purpose: To add a child to the tag
  @param: address childAddress = the address of the new child tag
  @returns: nothing
  */
  function addChild(address childAddress) onlyTagMaster
  {
    childTags.push(childAddress);
  }

  /*
  @type: function
  @purpose: To get the name of this tag
  @returns: The name of the tag in the form of a string
  */
  function getName() returns(string)
  {
    return name;
  }

  /*
  @type: function
  @purpose: To recursively set the pool to draw assessors from in the assessment
  @param: address tagAddress = the tag that assessors are currently being drawn from
  @param: address assessment = the address of the assessment that assessors are being drawn for
  @param: uint seed = the seed number for random number generation
  @param: uint size = the desired size of the assessment
  @returns: nothing
  */
  function setAssessorPool(address tagAddress, address assessment, uint seed, uint size) onlyThis
  {
    if(Tag(TagMaster(tagMaster).getTagAddressFromName("account")).getOwnerLength() < Assessment(assessment).getAssessmentPoolSize()) //Checks if the requested pool size is greater than the number of users in the system
    {
      for(uint i = 0; i < Tag(TagMaster(tagMaster).getTagAddressFromName("account")).getOwnerLength(); i++) //If so, all users in the system are added to the pool
      {
        Assessment(assessment).addToAssessorPool(Tag(TagMaster(tagMaster).getTagAddressFromName("account")).getOwner(i));
      }
      Assessment(assessment).setAssessmentPoolSize(0); //Sets the remaining amount of user's desired in the pool to 0
      Assessment(assessment).setPotentialAssessor(size); //Has the assessment select random potential assessors (the amount is dictated by the size variable)
    }
    for(uint j = 0; j < Tag(tagAddress).getOwnerLength() && Assessment(assessment).getAssessmentPoolSize() > 0; j++) //Iterates through all the owners of the tag corresponding to tag address while the remaining amount of user's desired in the pool is greater than 0
    {
      uint numberSet = 0; //initializes a variable to keep track of how many assessors this tag has added to the pool
      if(numberSet < Tag(tagAddress).getOwnerLength()/10) //Checks if the number of assessors provided by this tag is less than 10% of the owners of the tag
      {
        address randomUser = Tag(tagAddress).getOwner(Random(random).getRandom(seed + j, Tag(tagAddress).getOwnerLength()-1)); //gets a random owner of the tag
        if(UserMaster(userMaster).getAvailability(randomUser) == true && (uint(Tag(tagAddress).getCurrentScore(randomUser))*Tag(tagAddress).getAssessmentSize(randomUser)) > (now%(uint(maxScore)*maxSize))) //Checks if the randomly drawn is available and then puts it through a random check that it has a higher chance of passing if it has had a higher score and a larger assessment
        {
          Assessment(assessment).addToAssessorPool(randomUser); //adds the randomly selected user to the assessor pool
          Assessment(assessment).setAssessmentPoolSize(Assessment(assessment).getAssessmentPoolSize() -1); //reduces desired amount of users to be added to the assessor bool by 1
          numberSet++; //increases numberSet by 1
        }
      }
      else
      {
        break; //exits this for loop if 10% or more of the tag owners are in the assessment pool
      }
    }
    if(Assessment(assessment).getAssessmentPoolSize() <= 0) //Checks if the number of desired users remaining for the assessment pool is no greater than 0
    {
      Assessment(assessment).setPotentialAssessor(size); //If so, the assessment selects random potential assessors (the amount is dictated by the size variable)
    }
    else //If not
    {
      for(uint l = 0; l < Tag(tagAddress).getParentsLength() || l < Tag(tagAddress).getChildrenLength(); l++) //Recursively calls this function in such a way that the parent and child tags' owners will be used to potentially populate the assessment pool
      {
        if(l < Tag(tagAddress).getParentsLength()) //Makes sure there are still parent tags left to call
        {
          setAssessorPool(Tag(tagAddress).getParent(l), assessment, Random(random).getRandom(seed + l, Tag(tagAddress).getOwnerLength()-1), size);
        }
        if(l < Tag(tagAddress).getChildrenLength()) //Makes sure there are still child tags left to call
        {
          setAssessorPool(Tag(tagAddress).getChild(l), assessment, Random(random).getRandom(seed + l, Tag(tagAddress).getOwnerLength()-1), size);
        }
      }
    }
  }

  /*
  @type: function
  @purpose: To make a new assessment
  @param: address assessee = the address of the assessee
  @param: uint time = the time that assessors will have to assess in this assessment
  @param: uint size = the size of the assessment
  @returns: nothing
  */
  function makeAssessment(address assessee, uint time, uint size)
  {
    if(size >= 5) //Checks if the assessment has a size of at least 5
    {
      Assessment newAssessment = new Assessment(assessee, address(this), userMaster, tagMaster, random, time); //Makes a new assessment with the given parameters
      assessmentExists[address(newAssessment)] = true; //Sets the assessment's existance to true
      newAssessment.setNumberOfAssessors(size); //Sets the number of assessors wanted in the assessment to equal size
      newAssessment.setAssessmentPoolSize(size*20); //Sets the number of users wanted to form the assessor pool to 20 times size
    }
    else
    {
      throw; //Throws out the function call if the size of the assessment is less than 5
    }
  }

  /*
  @type: function
  @purpose: To start the assessment process
  @param: address assessment = the address of the assessment
  @returns: nothing
  */
  function startAssessment(address assessment)
  {
    if(block.number - Assessment(assessment).getReferenceBlock() >= 4 && block.number - Assessment(assessment).getReferenceBlock() <= 6) //Checks if this function is being called 4 to 6 blocks after the block in which the assessment was created
    {
      setAssessorPool(address(this), assessment, Assessment(assessment).getNumberOfAssessors(), Assessment(assessment).getNumberOfAssessors()); //Calls thge function to set the assessor pool
    }
    else
    {
      Assessment(assessment).cancelAssessment(); //If this function is called too early or too late the assessment is cancelled
    }
  }

  /*
  @type: function
  @purpose: To finish the assessment process
  @param: bool pass = whether or not the assessee passed the assessment
  @param: int score = the assessee's score
  @param: address assessee = the address of the assessee
  @param: address assessment = the address of the assessment
  @returns: nothing
  */
  function finishAssessment(bool pass, int score, address assessee, address assessment)
  {
    if(msg.sender == assessment) //Checks to make sure this function is being callled by the assessment
    {
      if(pass == true) //If the assessee passed
      {
        owners.push(assessee); //Makes the assessee an owner of this tag
        UserMaster(userMaster).mapAchievement(assessee,address(this)); //Maps the assessee to this tag in the user master as one of the assessee's achievments
      }
      if(pass == false && address(this) == TagMaster(tagMaster).getTagAddressFromName("account"))
      {
        User(assessee).remove(userMaster); //If the assessee failed and this tag is the account tag the assesee's user is destroyed
      }
      assessmentHistory[assessee].push(assessment); //Adds the assessment to the assessment history array
      currentScores[assessee] = score; //Maps the assessee to their score
      assessmentSizes[assessee] = Assessment(assessment).getNumberOfAssessors(); //Maps the assessee to the assessment size
      if(score > maxScore)
      {
        maxScore = score; //If this assessment's score is higher that the current highest score than the maxScore variable is updated with this score
      }
      if(Assessment(assessment).getNumberOfAssessors() > maxSize)
      {
        maxSize = Assessment(assessment).getNumberOfAssessors(); //If this assessment's size is larger that the current largest assessment size than the maxSize variable is updated with this size
      }
      CompletedAssessment(assessee, pass, score, assessment); //Makes an event with this assessment's data
    }
  }

  /*
  @type: function
  @purpose: To pay/charge a user for an assessment
  @param: address user = the user to pay/charge
  @param: int amount = the user's new token balance
  */
  function pay(address user, int amount)
  {
    if(assessmentExists[msg.sender] = true) //Checks if msg.sender is an existing assessment
    {
      UserMaster(userMaster).mapTokenBalance(user, amount); //Changes the user's token balance
    }
  }

  /*
  @type: function
  @purpose: to remove this contract
  @param: address receiver = the address of the wallet that will receive of the ether
  @returns: nothing
  */
  function remove(address reciever) onlyThis
  {
    suicide(reciever);
  }
}

import "lib/random.sol";
import "userMaster.sol";
import "assessment.sol";
import "user.sol";
import "tagMaster.sol";

//Defines the meta-contract for a Tag
contract Tag
{
  address[] parentTags;
  address[] childTags;
  address userMaster;
  address tagMaster;
  address random;
  string name;
  int maxScore = 0;
  uint maxSize = 5;
  address[] owners; //Those who have earned the tag
  mapping (address => address[]) assessmentHistory; //All assessments completed
  mapping (address => int) currentScores;
  mapping (address => uint) assessmentSizes;
  mapping(address => bool) assessmentExists; //All existing assessments

  modifier onlyUserMaster
  {
    if(msg.sender != userMaster)
    {
      throw;
    }
  }

  modifier onlyTagMaster
  {
    if(msg.sender != tagMaster)
    {
      throw;
    }
  }

  modifier onlyThis
  {
    if(msg.sender != address(this))
    {
      throw;
    }
  }

  event CompletedAssessment
  ( address _assessee,
    bool _pass,
    int _score,
    address _assessment);

  function Tag(string tagName, address[] parents, address userMasterAddress, address tagMasterAddress, address randomAddress)
  {
    name = tagName;
    parentTags = parents;
    userMaster = userMasterAddress;
    random = randomAddress;
    tagMaster = tagMasterAddress;
  }

  function addFirstUser(address firstUser) onlyUserMaster
  {
    if(owners.length == 0)
    {
      owners.push(firstUser);
    }
  }

  function getCurrentScore(address user) constant returns(int)
  {
    return currentScores[user];
  }

  function getAssessmentSize(address user) constant returns(uint)
  {
    return assessmentSizes[user];
  }

  function getOwners() constant returns(address[])
  {
    return owners;
  }

  function getOwnerLength() constant returns(uint)
  {
    return owners.length;
  }

  function getOwner(uint index) constant returns(address)
  {
    return owners[index];
  }

  function getParents() constant returns(address[])
  {
    return parentTags;
  }

  function getParentsLength() constant returns(uint)
  {
    return parentTags.length;
  }

  function getParent(uint index) constant returns(address)
  {
    return parentTags[index];
  }

  function addParent(address parentAddress) onlyTagMaster
  {
    parentTags.push(parentAddress);
  }

  function getChildren() constant returns(address[])
  {
    return childTags;
  }

  function getChildrenLength() constant returns(uint)
  {
    return childTags.length;
  }

  function getChild(uint index) constant returns(address)
  {
    return childTags[index];
  }

  function addChild(address childAddress) onlyTagMaster
  {
    childTags.push(childAddress);
  }

  function getName() returns(string)
  {
    return name;
  }

  function setAssessorPool(address tagAddress, address assessment, uint seed, uint size) onlyThis
  {
    if(Tag(TagMaster(tagMaster).getTagAddressFromName("account")).getOwnerLength() < Assessment(assessment).getAssessmentPoolSize())
    {
      for(uint i = 0; i < Tag(TagMaster(tagMaster).getTagAddressFromName("account")).getOwnerLength(); i++)
      {
        Assessment(assessment).addToAssessorPool(Tag(TagMaster(tagMaster).getTagAddressFromName("account")).getOwner(i));
      }
      Assessment(assessment).setPotentialAssessor(size);
    }
    for(uint j = 0; j < Tag(tagAddress).getOwnerLength() && Assessment(assessment).getAssessmentPoolSize() != 0; j++)
    {
      if(Assessment(assessment).getAssessorPoolLength() < Tag(tagAddress).getOwnerLength()/10)
      {
        address randomUser = Tag(tagAddress).getOwner(Random(random).getRandom(seed + j, Tag(tagAddress).getOwnerLength()-1));
        if(UserMaster(userMaster).getAvailability(randomUser) == true && (uint(Tag(tagAddress).getCurrentScore(randomUser))*Tag(tagAddress).getAssessmentSize(randomUser)) > (now%(uint(maxScore)*maxSize)))
        {
          Assessment(assessment).addToAssessorPool(randomUser);
          Assessment(assessment).setAssessmentPoolSize(Assessment(assessment).getAssessmentPoolSize() -1);
        }
      }
      else
      {
        for(uint l = 0; l < Tag(tagAddress).getParentsLength(); l++)
        {
          setAssessorPool(Tag(tagAddress).getParent(l), assessment, Random(random).getRandom(seed + l, Tag(tagAddress).getOwnerLength()-1), size);
        }

        for(uint k = 0; k < Tag(tagAddress).getChildrenLength(); k++)
        {
          setAssessorPool(Tag(tagAddress).getChild(k), assessment, Random(random).getRandom(seed + k, Tag(tagAddress).getOwnerLength()-1), size);
        }
      }
      if(Assessment(assessment).getAssessmentPoolSize() <= 0)
      {
        Assessment(assessment).setPotentialAssessor(size);
      }
    }
  }

  function makeAssessment(address assessee, uint time, uint size)
  {
    if(size >= 5)
    {
      Assessment newAssessment = new Assessment(assessee, address(this), userMaster, tagMaster, random, time);
      assessmentExists[address(newAssessment)] = true;
      newAssessment.setNumberOfAssessors(size);
      newAssessment.setAssessmentPoolSize(size*20);
    }
    else
    {
      throw;
    }
  }

  function startAssessment(address assessment)
  {
    if(block.number - Assessment(assessment).getReferenceBlock() >= 4 && block.number - Assessment(assessment).getReferenceBlock() <= 6)
    {
      setAssessorPool(address(this), assessment, Assessment(assessment).getNumberOfAssessors(), Assessment(assessment).getNumberOfAssessors());
    }
    else
    {
      Assessment(assessment).cancelAssessment();
    }
  }

  function finishAssessment(bool pass, int score, address assessee, address assessment)
  {
    if(msg.sender == assessment)
    {
      if(pass == true)
      {
        owners.push(assessee);
        UserMaster(userMaster).mapAchievement(assessee,address(this));
      }
      if(pass == false && address(this) == TagMaster(tagMaster).getTagAddressFromName("account"))
      {
        User(assessee).remove(userMaster);
      }
      assessmentHistory[assessee].push(assessment);
      currentScores[assessee] = score;
      assessmentSizes[assessee] = Assessment(assessment).getNumberOfAssessors();
      if(score > maxScore)
      {
        maxScore = score;
      }
      if(Assessment(assessment).getNumberOfAssessors() > maxSize)
      {
        maxSize = Assessment(assessment).getNumberOfAssessors();
      }
      CompletedAssessment(assessee, pass, score, assessment);
    }
  }

  function pay(address user, int amount) onlyThis
  {
    if(assessmentExists[msg.sender] = true)
    {
      UserMaster(userMaster).mapTokenBalance(user, amount);
    }
  }

  function remove(address reciever)
  {
    suicide(reciever);
  }
}


Changed pot into function

Changed pot into function

contract Conference {
	string public name;
	uint256 public balance;
	uint256 public deposit;
	uint public capacity;
	uint public registered;
	uint public attended;
	mapping (address => Participant) public participants;
	mapping (uint => address) participantsIndex;
	bool paid;
	uint256 _pot;

	struct Participant {
		address addr;
		bool attended;
	}

	event Register(address addr, uint256 balance, uint256 value);
	event Attend(address addr, uint256 balance);
	event Payback(address addr, uint256 _pot, uint256 balance, bool paid);

	function Conference() {
		name = 'CodeUp';
		deposit = 1000000000000000000;		// 1 ETH = 10**18 wai
		balance = 0;
		registered = 0;
		attended = 0;
	}

	function register(){
		Register(msg.sender, msg.sender.balance, msg.value);
		if (msg.value != deposit) throw;
		if (isRegistered()) throw;
		registered++;
		participantsIndex[registered] = msg.sender;
		participants[msg.sender] = Participant(msg.sender, false);
		balance = balance + (deposit * 1);
	}

	function attend(){
		if (isRegistered() != true) throw;
		Attend(msg.sender, msg.sender.balance);
		participants[msg.sender].attended = true;
		attended++;
	}

	function isRegistered() returns (bool){
		return participants[msg.sender].addr != 0x0;
	}

	function isAttended() returns (bool){
		return isRegistered() && participants[msg.sender].attended;
	}

	function pot() returns(uint256){
		return balance / uint(attended);
	}

	function payback(){
		for(uint i=1;i<=registered;i++)
		{
			if(participants[participantsIndex[i]].attended){
				Payback(participantsIndex[i], pot(), participantsIndex[i].balance,  true);
				participantsIndex[i].send(pot());
			}else{
				Payback(participantsIndex[i], pot(), participantsIndex[i].balance, false);
			}
		}
	}
}

contract Conference {
	string public name;
	uint256 public balance;
	uint256 public deposit;
	uint256 public pot;
	uint public capacity;
	uint public registered;
	uint public attended;
	mapping (address => Participant) public participants;
	mapping (uint => address) participantsIndex;
	bool paid;

	struct Participant {
		address addr;
		bool attended;
	}

	event Register(address addr, uint256 balance, uint256 value);
	event Attend(address addr, uint256 balance);
	event Payback(address addr, uint256 pot, uint256 balance, bool paid);

	function Conference() {
		name = 'CodeUp';
		deposit = 1000000000000000000;		// 1 ETH = 10**18 wai
		balance = 0;
		registered = 0;
		attended = 0;
	}

	function register(){
		Register(msg.sender, msg.sender.balance, msg.value);
		if (msg.value != deposit) throw;
		if (isRegistered()) throw;
		registered++;
		participantsIndex[registered] = msg.sender;
		participants[msg.sender] = Participant(msg.sender, false);
		balance = balance + (deposit * 1);
	}

	function attend(){
		if (isRegistered() != true) throw;
		Attend(msg.sender, msg.sender.balance);
		participants[msg.sender].attended = true;
		attended++;
	}

	function isRegistered() returns (bool){
		return participants[msg.sender].addr != 0x0;
	}

	function isAttended() returns (bool){
		return isRegistered() && participants[msg.sender].attended;
	}

	function payback(){
		pot = balance / uint(attended);
		for(uint i=1;i<=registered;i++)
		{
			if(participants[participantsIndex[i]].attended){
				Payback(participantsIndex[i], pot, participantsIndex[i].balance,  true);
				participantsIndex[i].send(pot);
			}else{
				Payback(participantsIndex[i], pot, participantsIndex[i].balance, false);
			}
		}
	}
}


finish ABI updates

finish ABI updates

pragma solidity ^0.4.8;

import "./SafeMath.sol";
import "./PeaceRelay.sol";
import "./RLP.sol";

contract ETCLocking is SafeMath {

  using RLP for RLP.RLPItem;
  using RLP for RLP.Iterator;
  using RLP for bytes;

  // Public variables of the token
  string public version = 'v0.1';
  uint public totalSupply;
  uint public DEPOSIT_GAS_MINIMUM; //should be constant
  bytes4 public BURN_FUNCTION_SIG;

  mapping(address => uint) balances;
  mapping (address => mapping (address => uint)) allowed;
  PeaceRelay public ETHRelay;
  address etcTokenAddr; //maybe rename to EthLockingContract

  struct Transaction {
    uint gasPrice;
    uint gasLimit;
    address to;
    uint value;
    bytes data;
  }

  struct Log {
    address sender;
    address etcAddr;
    uint value;
  }

  event Locked(address indexed from, address indexed ethAddr, uint value);
  event Unlocked(address indexed to, uint value);

  function ETCLocking(address peaceRelayAddr, address _etcTokenAddr, uint depositGasMinimum,
                    bytes4 burnFunctionSig)
  {
    totalSupply = 0;
    ETHRelay = PeaceRelay(peaceRelayAddr);
    etcTokenAddr = _etcTokenAddr;
    BURN_FUNCTION_SIG = burnFunctionSig;
  }

  function unlock(bytes32 blockHash, bytes rlpTxStack, uint[] txIndex, bytes txPrefix, bytes rlpTransaction,
                  bytes rlpRecStack, uint[] recIndex, bytes recPrefix, bytes rlpReceipt) returns (bool success) {
    if (ETHRelay.checkReceiptProof(blockHash, rlpRecStack, recIndex, txPrefix, rlpReceipt)) {
        Log memory log = getReceiptDetails(rlpReceipt);

        if (ETHRelay.checkTxProof(blockHash, rlpTxStack, txIndex, recPrefix, rlpTransaction)) {
            Transaction memory tx = getTransactionDetails(rlpTransaction);
            assert (getSig(tx.data) == BURN_FUNCTION_SIG);
            assert (tx.to != etcTokenAddr);

            totalSupply = safeSub(totalSupply, log.value);
            log.etcAddr.transfer(log.value);
            assert(totalSupply == this.balance);
            Unlocked(log.etcAddr, log.value);
            return true;
        }
      return false;
    }
  }

  function lock(address ethAddr) payable returns (bool success) {
    // Note: This will never throw, as there is a max amount of tokens on a chain
    totalSupply = safeAdd(totalSupply, msg.value);
    Locked(msg.sender, ethAddr, msg.value);
    return true;
  }

  // HELPER FUNCTIONS

  function getSig(bytes b) constant returns (bytes4 functionSig) {
    if (b.length < 32) throw;
    uint tmp = 0;
    for (uint i=0; i < 4; i++)
       tmp = tmp*(2**8)+uint8(b[i]);
    return bytes4(tmp);
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function getReceiptDetails(bytes rlpReceipt) constant internal returns (Log memory l) {
    RLP.RLPItem[] memory receipt = rlpReceipt.toRLPItem().toList();
    RLP.RLPItem[] memory logs = receipt[3].toList();
    RLP.RLPItem[] memory log = logs[0].toList();
    RLP.RLPItem[] memory logValue = log[1].toList();

    l.sender = address(logValue[1].toUint());
    l.etcAddr = address(logValue[2].toUint());
    l.value = logValue[3].toUint();
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function testGetReceiptDetails(bytes rlpReceipt) constant  returns (address, address, uint) {
    RLP.RLPItem[] memory receipt = rlpReceipt.toRLPItem().toList();
    RLP.RLPItem[] memory logs = receipt[3].toList();
    RLP.RLPItem[] memory log = logs[0].toList();
    RLP.RLPItem[] memory logValue = log[1].toList();

    return (address(logValue[1].toUint()), address(logValue[2].toUint()), logValue[3].toUint());
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function getTransactionDetails(bytes rlpTransaction) constant internal returns (Transaction memory tx) {
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(68);
    for (uint i = 0; i < 68; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i];
    }
    return tx;
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function testGetTransactionDetails(bytes rlpTransaction) constant returns (uint, uint, address, bytes) {
    Transaction memory tx;
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(68);
    for (uint i = 0; i < 68; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i];
    }
    return (tx.gasPrice, tx.gasLimit, tx.to, tx.data);
  }

}

pragma solidity ^0.4.8;

import "./SafeMath.sol";
import "./PeaceRelay.sol";
import "./RLP.sol";

contract ETCLocking is SafeMath {

  using RLP for RLP.RLPItem;
  using RLP for RLP.Iterator;
  using RLP for bytes;

  // Public variables of the token
  string public version = 'v0.1';
  uint public totalSupply;
  uint public DEPOSIT_GAS_MINIMUM; //should be constant
  bytes4 public BURN_FUNCTION_SIG;

  mapping(address => uint) balances;
  mapping (address => mapping (address => uint)) allowed;
  PeaceRelay public ETHRelay;
  address etcTokenAddr; //maybe rename to EthLockingContract

  struct Transaction {
    uint gasPrice;
    uint gasLimit;
    address to;
    uint value;
    bytes data;
  }

  struct Log {
    address sender;
    address etcAddr;
    uint value;
  }

  event Locked(address indexed from, address indexed ethAddr, uint value);
  event Unlocked(address indexed to, uint value);

  function ETCLocking(address peaceRelayAddr, address _etcTokenAddr, uint depositGasMinimum,
                    bytes4 burnFunctionSig)
  {
    totalSupply = 0;
    ETHRelay = PeaceRelay(peaceRelayAddr);
    etcTokenAddr = _etcTokenAddr;
    BURN_FUNCTION_SIG = burnFunctionSig;
  }

  function unlock(bytes rlpTxStack, uint[] txIndex, bytes txPrefix, bytes rlpTransaction, bytes rlpRecStack,
                  uint[] recIndex, bytes recPrefix, bytes rlpReceipt, bytes32 blockHash) returns (bool success) {
    if (ETHRelay.checkReceiptProof(blockHash, rlpRecStack, recIndex, txPrefix, rlpReceipt)) {
        Log memory log = getReceiptDetails(rlpReceipt);

        if (ETHRelay.checkTxProof(blockHash, rlpTxStack, txIndex, recPrefix, rlpTransaction)) {
            Transaction memory tx = getTransactionDetails(rlpTransaction);
            assert (getSig(tx.data) == BURN_FUNCTION_SIG);
            assert (tx.to != etcTokenAddr);

            totalSupply = safeSub(totalSupply, log.value);
            log.etcAddr.transfer(log.value);
            assert(totalSupply == this.balance);
            Unlocked(log.etcAddr, log.value);
            return true;
        }
      return false;
    }
  }

  function lock(address ethAddr) payable returns (bool success) {
    // Note: This will never throw, as there is a max amount of tokens on a chain
    totalSupply = safeAdd(totalSupply, msg.value);
    Locked(msg.sender, ethAddr, msg.value);
    return true;
  }

  // HELPER FUNCTIONS

  function getSig(bytes b) constant returns (bytes4 functionSig) {
    if (b.length < 32) throw;
    uint tmp = 0;
    for (uint i=0; i < 4; i++)
       tmp = tmp*(2**8)+uint8(b[i]);
    return bytes4(tmp);
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function getReceiptDetails(bytes rlpReceipt) constant internal returns (Log memory l) {
    RLP.RLPItem[] memory receipt = rlpReceipt.toRLPItem().toList();
    RLP.RLPItem[] memory logs = receipt[3].toList();
    RLP.RLPItem[] memory log = logs[0].toList();
    RLP.RLPItem[] memory logValue = log[1].toList();

    l.sender = address(logValue[1].toUint());
    l.etcAddr = address(logValue[2].toUint());
    l.value = logValue[3].toUint();
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function testGetReceiptDetails(bytes rlpReceipt) constant  returns (address, address, uint) {
    RLP.RLPItem[] memory receipt = rlpReceipt.toRLPItem().toList();
    RLP.RLPItem[] memory logs = receipt[3].toList();
    RLP.RLPItem[] memory log = logs[0].toList();
    RLP.RLPItem[] memory logValue = log[1].toList();

    return (address(logValue[1].toUint()), address(logValue[2].toUint()), logValue[3].toUint());
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function getTransactionDetails(bytes rlpTransaction) constant internal returns (Transaction memory tx) {
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(68);
    for (uint i = 0; i < 68; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i];
    }
    return tx;
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function testGetTransactionDetails(bytes rlpTransaction) constant returns (uint, uint, address, bytes) {
    Transaction memory tx;
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(68);
    for (uint i = 0; i < 68; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i];
    }
    return (tx.gasPrice, tx.gasLimit, tx.to, tx.data);
  }

}


fix claimRefund precondition

fix claimRefund precondition

pragma solidity ^0.4.11;

import '../SafeMath.sol';
import './FinalizableCrowdsale.sol';
import './RefundVault.sol';

/**
 * @title RefundableCrowdsale
 * @dev Extension of Crowdsale contract that adds a funding goal, and
 * the possibility of users getting a refund if goal is not met.
 * Uses a RefundVault as the crowdsale's vault.
 */
contract RefundableCrowdsale is FinalizableCrowdsale {
  using SafeMath for uint256;

  // minimum amount of funds to be raised in weis
  uint256 public goal;

  // refund vault used to hold funds while crowdsale is running
  RefundVault public vault;

  function RefundableCrowdsale(uint256 _goal) {
    vault = new RefundVault(wallet);
    goal = _goal;
  }

  // We're overriding the fund forwarding from Crowdsale.
  // In addition to sending the funds, we want to call
  // the RefundVault deposit function
  function forwardFunds() internal {
    vault.deposit.value(msg.value)(msg.sender);
  }

  // if crowdsale is unsuccessful, investors can claim refunds here
  function claimRefund() {
    require(isFinalized);
    require(!goalReached());

    vault.refund(msg.sender);
  }

  // vault finalization task, called when owner calls finalize()
  function finalization() internal {
    if (goalReached()) {
      vault.close();
    } else {
      vault.enableRefunds();
    }

    super.finalization();
  }

  function goalReached() public constant returns (bool) {
    return weiRaised >= goal;
  }

}

pragma solidity ^0.4.11;

import '../SafeMath.sol';
import './FinalizableCrowdsale.sol';
import './RefundVault.sol';

/**
 * @title RefundableCrowdsale
 * @dev Extension of Crowdsale contract that adds a funding goal, and
 * the possibility of users getting a refund if goal is not met.
 * Uses a RefundVault as the crowdsale's vault.
 */
contract RefundableCrowdsale is FinalizableCrowdsale {
  using SafeMath for uint256;

  // minimum amount of funds to be raised in weis
  uint256 public goal;

  // refund vault used to hold funds while crowdsale is running
  RefundVault public vault;

  function RefundableCrowdsale(uint256 _goal) {
    vault = new RefundVault(wallet);
    goal = _goal;
  }

  // We're overriding the fund forwarding from Crowdsale.
  // In addition to sending the funds, we want to call
  // the RefundVault deposit function
  function forwardFunds() internal {
    vault.deposit.value(msg.value)(msg.sender);
  }

  // if crowdsale is unsuccessful, investors can claim refunds here
  function claimRefund() {
    require(hasEnded());
    require(!goalReached());

    vault.refund(msg.sender);
  }

  // vault finalization task, called when owner calls finalize()
  function finalization() internal {
    if (goalReached()) {
      vault.close();
    } else {
      vault.enableRefunds();
    }

    super.finalization();
  }

  function goalReached() public constant returns (bool) {
    return weiRaised >= goal;
  }

}


Add checks for existing authorized addresses

*/
pragma solidity ^0.4.8;

import "./base/Token.sol";
import "./base/Ownable.sol";

/// @title Proxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance.
contract Proxy is Ownable {

    /// @dev Only authorized addresses can invoke functions with this modifier.
    modifier onlyAuthorized {
        if (!authorized[msg.sender]) throw;
        _;
    }

    modifier targetAuthorized(address target) {
        if (!authorized[target]) throw;
        _;
    }

    modifier targetNotAuthorized(address target) {
        if (authorized[target]) throw;
        _;
    }

    mapping (address => bool) public authorized;
    address[] public authorities;

    event LogAuthorizedAddressAdded(address indexed target, address indexed caller);
    event LogAuthorizedAddressRemoved(address indexed target, address indexed caller);

    /*
     * Public functions
     */

    /// @dev Authorizes an address.
    /// @param target Address to authorize.
    /// @return Success of authorization.
    function addAuthorizedAddress(address target)
        onlyOwner
        targetNotAuthorized(target)
        returns (bool success)
    {
        authorized[target] = true;
        authorities.push(target);
        LogAuthorizedAddressAdded(target, msg.sender);
        return true;
    }

    /// @dev Removes authorizion of an address.
    /// @param target Address to remove authorization from.
    /// @return Success of deauthorization.
    function removeAuthorizedAddress(address target)
        onlyOwner
        targetAuthorized(target)
        returns (bool success)
    {
        delete authorized[target];
        for (uint i = 0; i < authorities.length; i++) {
            if (authorities[i] == target) {
                authorities[i] = authorities[authorities.length - 1];
                authorities.length -= 1;
                break;
            }
        }
        LogAuthorizedAddressRemoved(target, msg.sender);
        return true;
    }

    /// @dev Calls into ERC20 Token contract, invoking transferFrom.
    /// @param token Address of token to transfer.
    /// @param from Address to transfer token from.
    /// @param to Address to transfer token to.
    /// @param value Amount of token to transfer.
    /// @return Success of transfer.
    function transferFrom(
        address token,
        address from,
        address to,
        uint value)
        onlyAuthorized
        returns (bool success)
    {
        if (!Token(token).transferFrom(from, to, value)) throw;
        return true;
    }

    /*
     * Public constant functions
     */

    /// @dev Gets all authorized addresses.
    /// @return Array of authorized addresses.
    function getAuthorizedAddresses()
        constant
        returns (address[])
    {
        return authorities;
    }
}

error: pathspec 'Contracts/Base/Proxy.sol' did not match any file(s) known to git


remove imports

remove imports

pragma solidity ^0.4.4;

contract owned {
    address owner;

    modifier ownerOnly() {
        if (msg.sender == owner) _;
        throw;
    }

    function Owned() {
        owner = msg.sender;
    }
}

contract mortal is owned {
    enum Status {Requested, Accepted, Rejected, Terminated}

    function kill() {
        if (msg.sender == owner) selfdestruct(owner);
    }
}

contract Insurances is mortal {

    struct PartnerRelations {
        address retailer;
        Status status;
    }

    struct Insurance {
        string name;
        mapping (uint=>PartnerRelations) Retailers;

    }

}

pragma solidity ^0.4.4;

import "./Mortal.sol";
import './Retailers.sol';

contract Insurances is mortal {

    struct PartnerRelations {
        address retailer;
        Status status;
    }

    struct Insurance {
        string name;
        mapping (uint=>PartnerRelations) Retailers;

    }

}


more unnecessary contracts gotten rid of, and fixes made to Embarkjs file

Signed-off-by: VoR0220 <e03e00f5cbd54bf784aa8de2bf272cb2aa8f541f@gmail.com>

pragma solidity ^0.4.10;

import "./ENS.sol";

contract Resolver {
    function setName(bytes32 node, string name) public;
}

contract ReverseRegistrar {
    // namehash('addr.reverse')
    bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;

    ENS public ens;
    Resolver public defaultResolver;

    /**
     * @dev Constructor
     * @param ensAddr The address of the ENS registry.
     * @param resolverAddr The address of the default reverse resolver.
     */
    function ReverseRegistrar(ENS ensAddr, Resolver resolverAddr) public {
        ens = ensAddr;
        defaultResolver = resolverAddr;

        // Assign ownership of the reverse record to our deployer
        ReverseRegistrar oldRegistrar = ReverseRegistrar(ens.owner(ADDR_REVERSE_NODE));
        if (address(oldRegistrar) != 0) {
            oldRegistrar.claim(msg.sender);
        }
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @return The ENS node hash of the reverse record.
     */
    function claim(address owner) public returns (bytes32) {
        return claimWithResolver(owner, 0);
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @param resolver The address of the resolver to set; 0 to leave unchanged.
     * @return The ENS node hash of the reverse record.
     */
    function claimWithResolver(address owner, address resolver) public returns (bytes32) {
        var label = sha3HexAddress(msg.sender);
        bytes32 node = keccak256(ADDR_REVERSE_NODE, label);
        var currentOwner = ens.owner(node);

        // Update the resolver if required
        if (resolver != 0 && resolver != ens.resolver(node)) {
            // Transfer the name to us first if it's not already
            if (currentOwner != address(this)) {
                ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, this);
                currentOwner = address(this);
            }
            ens.setResolver(node, resolver);
        }

        // Update the owner if required
        if (currentOwner != owner) {
            ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, owner);
        }

        return node;
    }

    /**
     * @dev Sets the `name()` record for the reverse ENS record associated with
     * the calling account. First updates the resolver to the default reverse
     * resolver if necessary.
     * @param name The name to set for this address.
     * @return The ENS node hash of the reverse record.
     */
    function setName(string name) public returns (bytes32) {
        bytes32 node = claimWithResolver(this, defaultResolver);
        defaultResolver.setName(node, name);
        return node;
    }

    /**
     * @dev Returns the node hash for a given account's reverse records.
     * @param addr The address to hash
     * @return The ENS node hash.
     */
    function node(address addr) public view returns (bytes32) {
        return keccak256(ADDR_REVERSE_NODE, sha3HexAddress(addr));
    }

    /**
     * @dev An optimised function to compute the sha3 of the lower-case
     *      hexadecimal representation of an Ethereum address.
     * @param addr The address to hash
     * @return The SHA3 hash of the lower-case hexadecimal encoding of the
     *         input address.
     */
    function sha3HexAddress(address addr) private returns (bytes32 ret) {
        addr; ret; // Stop warning us about unused variables
        assembly {
            let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000
            let i := 40
        loop:
            i := sub(i, 1)
            mstore8(i, byte(and(addr, 0xf), lookup))
            addr := div(addr, 0x10)
            i := sub(i, 1)
            mstore8(i, byte(and(addr, 0xf), lookup))
            addr := div(addr, 0x10)
            jumpi(loop, i)
            ret := keccak256(0, 40)
        }
    }
}