cosmetic updates to VestingTrustee.sol

cosmetic updates to VestingTrustee.sol

pragma solidity ^0.4.15;

import './SafeMath.sol';
import './Ownable.sol';
import './KinToken.sol';

/// @title Vesting trustee contract for Kin token.
contract VestingTrustee is Ownable {
    using SafeMath for uint256;

    // Kin token contract.
    KinToken public kin;

    // Vesting grant for a speicifc holder.
    struct Grant {
        uint256 value;
        uint256 start;
        uint256 cliff;
        uint256 end;
        uint256 installmentLength; // In seconds.
        uint256 transferred;
        bool revokable;
    }

    // Holder to grant information mapping.
    mapping (address => Grant) public grants;

    // Total tokens available for vesting.
    uint256 public totalVesting;

    event NewGrant(address indexed _from, address indexed _to, uint256 _value);
    event TokensUnlocked(address indexed _to, uint256 _value);
    event GrantRevoked(address indexed _holder, uint256 _refund);

    /// @dev Constructor that initializes the address of the Kin token contract.
    /// @param _kin KinToken The address of the previously deployed Kin token contract.
    function VestingTrustee(KinToken _kin) {
        require(_kin != address(0));

        kin = _kin;
    }

    /// @dev Grant tokens to a specified address.
    /// @param _to address The holder address.
    /// @param _value uint256 The amount of tokens to be granted.
    /// @param _start uint256 The beginning of the vesting period.
    /// @param _cliff uint256 Duration of the cliff period (when the first installment is made).
    /// @param _end uint256 The end of the vesting period.
    /// @param _installmentLength uint256 The length of each vesting installment (in seconds).
    /// @param _revokable bool Whether the grant is revokable or not.
    function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,
        uint256 _installmentLength, bool _revokable)
        external onlyOwner {

        require(_to != address(0));
        require(_to != address(this)); // Don't allow holder to be this contract.
        require(_value > 0);

        // Require that every holder can be granted tokens only once.
        require(grants[_to].value == 0);

        // Require for time ranges to be consistent and valid.
        require(_start <= _cliff && _cliff <= _end);

        // Require installment length to be valid and no longer than (end - start).
        require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));

        // Grant must not exceed the total amount of tokens currently available for vesting.
        require(totalVesting.add(_value) <= kin.balanceOf(address(this)));

        // Assign a new grant.
        grants[_to] = Grant({
            value: _value,
            start: _start,
            cliff: _cliff,
            end: _end,
            installmentLength: _installmentLength,
            transferred: 0,
            revokable: _revokable
        });

        // Since tokens have been granted, reduce the total amount available for vesting.
        totalVesting = totalVesting.add(_value);

        NewGrant(msg.sender, _to, _value);
    }

    /// @dev Revoke the grant of tokens of a specifed address.
    /// @param _holder The address which will have its tokens revoked.
    function revoke(address _holder) public onlyOwner {
        Grant memory grant = grants[_holder];

        // Grant must be revokable.
        require(grant.revokable);

        // Calculate amount of remaining tokens that are still available to be
        // returned to owner.
        uint256 refund = grant.value.sub(grant.transferred);

        // Remove grant information.
        delete grants[_holder];

        // Update total vesting amount and transfer previously calculated tokens to owner.
        totalVesting = totalVesting.sub(refund);
        kin.transfer(msg.sender, refund);

        GrantRevoked(_holder, refund);
    }

    /// @dev Calculate the total amount of vested tokens of a holder at a given time.
    /// @param _holder address The address of the holder.
    /// @param _time uint256 The specific time to calculate against.
    /// @return a uint256 Representing a holder's total amount of vested tokens.
    function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) {
        Grant memory grant = grants[_holder];
        if (grant.value == 0) {
            return 0;
        }

        return calculateVestedTokens(grant, _time);
    }

    /// @dev Calculate amount of vested tokens at a specifc time.
    /// @param _grant Grant The vesting grant.
    /// @param _time uint256 The time to be checked
    /// @return a uint256 Representing the amount of vested tokens of a specific grant.
    function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) {
        // If we're before the cliff, then nothing is vested.
        if (_time < _grant.cliff) {
            return 0;
        }

        // If we're after the end of the vesting period - everything is vested;
        if (_time >= _grant.end) {
            return _grant.value;
        }

        // Calculate amount of installments past until now.
        //
        // NOTE result gets floored because of integer division.
        uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength);

        // Calculate amount of days in entire vesting period.
        uint256 vestingDays = _grant.end.sub(_grant.start);

        // Calculate and return installments that have passed according to vesting days that have passed.
        return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays);
    }

    /// @dev Unlock vested tokens and transfer them to their holder.
    /// @return a uint256 Representing the amount of vested tokens transferred to their holder.
    function unlockVestedTokens() external {
        Grant storage grant = grants[msg.sender];

        // Require that there will be funds left in grant to tranfser to holder.
        require(grant.value != 0);

        // Get the total amount of vested tokens, acccording to grant.
        uint256 vested = calculateVestedTokens(grant, now);
        if (vested == 0) {
            return;
        }

        // Make sure the holder doesn't transfer more than what he already has.
        uint256 transferable = vested.sub(grant.transferred);
        if (transferable == 0) {
            return;
        }

        // Update transferred and total vesting amount,
        // then transfer remaining vested funds to holder.
        grant.transferred = grant.transferred.add(transferable);
        totalVesting = totalVesting.sub(transferable);
        kin.transfer(msg.sender, transferable);

        TokensUnlocked(msg.sender, transferable);
    }
}

pragma solidity ^0.4.15;

import './SafeMath.sol';
import './Ownable.sol';
import './KinToken.sol';

/// @title Vesting trustee contract for Kin token.
contract VestingTrustee is Ownable {
    using SafeMath for uint256;

    // Kin token contract.
    KinToken public kin;

    // Vesting grant for a speicifc holder.
    struct Grant {
        uint256 value;
        uint256 start;
        uint256 cliff;
        uint256 end;
        uint256 installmentLength; // In seconds.
        uint256 transferred;
        bool revokable;
    }

    // Holder to grant information mapping.
    mapping (address => Grant) public grants;

    // Total tokens available for vesting.
    uint256 public totalVesting;

    event NewGrant(address indexed _from, address indexed _to, uint256 _value);
    event TokensUnlocked(address indexed _to, uint256 _value);
    event GrantRevoked(address indexed _holder, uint256 _refund);

    /// @dev Constructor that initializes the address of the Kin token contract.
    /// @param _kin KinToken The address of the previously deployed Kin token contract.
    function VestingTrustee(KinToken _kin) {
        require(_kin != address(0));

        kin = _kin;
    }

    /// @dev Grant tokens to a specified address. Please note, that the trustee must have enough ungranted tokens to
    /// accomodate the new grant. Otherwise, the call with fail.
    /// @param _to address The holder address.
    /// @param _value uint256 The amount of tokens to be granted.
    /// @param _start uint256 The beginning of the vesting period.
    /// @param _cliff uint256 Duration of the cliff period (when the first installment is made).
    /// @param _end uint256 The end of the vesting period.
    /// @param _installmentLength uint256 The length of each vesting installment (in seconds).
    /// @param _revokable bool Whether the grant is revokable or not.
    function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,
        uint256 _installmentLength, bool _revokable)
        external onlyOwner {

        require(_to != address(0));
        require(_to != address(this)); // Protect this contract from receiving a grant.
        require(_value > 0);

        // Require that every holder can be granted tokens only once.
        require(grants[_to].value == 0);

        // Require for time ranges to be consistent and valid.
        require(_start <= _cliff && _cliff <= _end);

        // Require installment length to be valid and no longer than (end - start).
        require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));

        // Grant must not exceed the total amount of tokens currently available for vesting.
        require(totalVesting.add(_value) <= kin.balanceOf(address(this)));

        // Assign a new grant.
        grants[_to] = Grant({
            value: _value,
            start: _start,
            cliff: _cliff,
            end: _end,
            installmentLength: _installmentLength,
            transferred: 0,
            revokable: _revokable
        });

        // Since tokens have been granted, reduce the total amount available for vesting.
        totalVesting = totalVesting.add(_value);

        NewGrant(msg.sender, _to, _value);
    }

    /// @dev Revoke the grant of tokens of a specifed address.
    /// @param _holder The address which will have its tokens revoked.
    function revoke(address _holder) public onlyOwner {
        Grant memory grant = grants[_holder];

        // Grant must be revokable.
        require(grant.revokable);

        // Calculate amount of remaining tokens that can still be returned.
        uint256 refund = grant.value.sub(grant.transferred);

        // Remove the grant.
        delete grants[_holder];

        // Update total vesting amount and transfer previously calculated tokens to owner.
        totalVesting = totalVesting.sub(refund);
        kin.transfer(msg.sender, refund);

        GrantRevoked(_holder, refund);
    }

    /// @dev Calculate the total amount of vested tokens of a holder at a given time.
    /// @param _holder address The address of the holder.
    /// @param _time uint256 The specific time to calculate against.
    /// @return a uint256 Representing a holder's total amount of vested tokens.
    function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) {
        Grant memory grant = grants[_holder];
        if (grant.value == 0) {
            return 0;
        }

        return calculateVestedTokens(grant, _time);
    }

    /// @dev Calculate amount of vested tokens at a specifc time.
    /// @param _grant Grant The vesting grant.
    /// @param _time uint256 The time to be checked
    /// @return An uint256 Representing the amount of vested tokens of a specific grant.
    function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) {
        // If we're before the cliff, then nothing is vested.
        if (_time < _grant.cliff) {
            return 0;
        }

        // If we're after the end of the vesting period - everything is vested;
        if (_time >= _grant.end) {
            return _grant.value;
        }

        // Calculate amount of installments past until now.
        //
        // NOTE result gets floored because of integer division.
        uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength);

        // Calculate amount of days in entire vesting period.
        uint256 vestingDays = _grant.end.sub(_grant.start);

        // Calculate and return the number of tokens according to vesting days that have passed.
        return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays);
    }

    /// @dev Unlock vested tokens and transfer them to the grantee.
    function unlockVestedTokens() external {
        Grant storage grant = grants[msg.sender];

        // Make sure the grant has tokens available.
        require(grant.value != 0);

        // Get the total amount of vested tokens, acccording to grant.
        uint256 vested = calculateVestedTokens(grant, now);
        if (vested == 0) {
            return;
        }

        // Make sure the holder doesn't transfer more than what he already has.
        uint256 transferable = vested.sub(grant.transferred);
        if (transferable == 0) {
            return;
        }

        // Update transferred and total vesting amount, then transfer remaining vested funds to holder.
        grant.transferred = grant.transferred.add(transferable);
        totalVesting = totalVesting.sub(transferable);
        kin.transfer(msg.sender, transferable);

        TokensUnlocked(msg.sender, transferable);
    }
}


Add game to gamesOfPlayer in joinGame (#30)

/**
 * Chess contract
 * Stores any amount of games with two players and current state.
 * State encoding:
 *    positive numbers for white, negative numbers for black
 *    <TODO>
 */

contract Chess {
    int8[64] defaultState; // this should be constant if possible

    struct Game {
        address player1;
        address player2;
        string player1Alias;
        string player2Alias;
        address nextPlayer;
        address winner;
        int[64] state;
    }

    mapping (bytes32 => Game) public games;
    mapping (address => mapping (int => bytes32)) public gamesOfPlayers;
    mapping (address => int) public numberGamesOfPlayers;

    function Chess() {
        // Just a test to see some output, this should be more storage/cost efficient
        defaultState[0] = 1;
        defaultState[1] = 1;
        defaultState[0x38] = -1;
        defaultState[0x39] = -1;
    }

    event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias);
    event GameJoined(bytes32 indexed gameId, address indexed player1, string player1Alias, address indexed player2, string player2Alias);
    event GameStateChanged(bytes32 indexed gameId, int[64] state);
    event Move(bytes32 indexed gameId, bool indexed moveSuccesful);

    /* Initialize a game */
    function initGame(string player1Alias) public {
        // Generate game id based on player's addresses and current timestamp
        bytes32 gameId = sha3(msg.sender, now);

        // Initialize participants
        games[gameId].player1 = msg.sender;
        games[gameId].player1Alias = player1Alias;

        // Initialize state
        games[gameId].state = defaultState;

        // Game starts with P2
        games[gameId].nextPlayer = games[gameId].player1;

        // Add game to gamesOfPlayer
        gamesOfPlayers[msg.sender][numberGamesOfPlayers[msg.sender]] = gameId;
        numberGamesOfPlayers[msg.sender]++;

        // Sent notification events
        GameInitialized(gameId, games[gameId].player1, player1Alias);
        GameStateChanged(gameId, games[gameId].state);
    }

    /* Join a game */
    function joinGame(bytes32 gameId, string player2Alias) public {
      if (games[gameId].player2 != 0) {
        throw;
      }

      games[gameId].player2 = msg.sender;
      games[gameId].player2Alias = player2Alias;
      gamesOfPlayers[msg.sender][numberGamesOfPlayers[msg.sender]] = gameId;
      numberGamesOfPlayers[msg.sender]++;
      GameJoined(gameId, games[gameId].player1, games[gameId].player1Alias, games[gameId].player2, player2Alias);
    }

    /* Move a figure */
    function move(bytes32 gameId) public {
        // Check that it is this player's turn
        if (games[gameId].nextPlayer != msg.sender) {
            throw;
        }

        // TODO: Validate move

        // TODO: Update state

        // TODO: Set nextPlayer

        // GameStateChanged(gameId, games[gameId].state);
        Move(gameId, true);
    }

    function getGameId(address player, int index) constant returns (bytes32) {
      return gamesOfPlayers[player][index];
    }
    /* This unnamed function is called whenever someone tries to send ether to it */
    function () {
        throw;     // Prevents accidental sending of ether
    }
}

/**
 * Chess contract
 * Stores any amount of games with two players and current state.
 * State encoding:
 *    positive numbers for white, negative numbers for black
 *    <TODO>
 */

contract Chess {
    int8[64] defaultState; // this should be constant if possible

    struct Game {
        address player1;
        address player2;
        string player1Alias;
        string player2Alias;
        address nextPlayer;
        address winner;
        int[64] state;
    }

    mapping (bytes32 => Game) public games;
    mapping (address => mapping (int => bytes32)) public gamesOfPlayers;
    mapping (address => int) public numberGamesOfPlayers;

    function Chess() {
        // Just a test to see some output, this should be more storage/cost efficient
        defaultState[0] = 1;
        defaultState[1] = 1;
        defaultState[0x38] = -1;
        defaultState[0x39] = -1;
    }

    event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias);
    event GameJoined(bytes32 indexed gameId, address indexed player1, string player1Alias, address indexed player2, string player2Alias);
    event GameStateChanged(bytes32 indexed gameId, int[64] state);
    event Move(bytes32 indexed gameId, bool indexed moveSuccesful);

    /* Initialize a game */
    function initGame(string player1Alias) public {
        // Generate game id based on player's addresses and current timestamp
        bytes32 gameId = sha3(msg.sender, now);

        // Initialize participants
        games[gameId].player1 = msg.sender;
        games[gameId].player1Alias = player1Alias;

        // Initialize state
        games[gameId].state = defaultState;

        // Game starts with P2
        games[gameId].nextPlayer = games[gameId].player1;

        // Add game to gamesOfPlayer
        gamesOfPlayers[msg.sender][numberGamesOfPlayers[msg.sender]] = gameId;
        numberGamesOfPlayers[msg.sender]++;

        // Sent notification events
        GameInitialized(gameId, games[gameId].player1, player1Alias);
        GameStateChanged(gameId, games[gameId].state);
    }

    /* Join a game */
    function joinGame(bytes32 gameId, string player2Alias) public {
      if (games[gameId].player2 != 0) {
        throw;
      }

      games[gameId].player2 = msg.sender;
      games[gameId].player2Alias = player2Alias;
      GameJoined(gameId, games[gameId].player1, games[gameId].player1Alias, games[gameId].player2, player2Alias);
    }

    /* Move a figure */
    function move(bytes32 gameId) public {
        // Check that it is this player's turn
        if (games[gameId].nextPlayer != msg.sender) {
            throw;
        }

        // TODO: Validate move

        // TODO: Update state

        // TODO: Set nextPlayer

        // GameStateChanged(gameId, games[gameId].state);
        Move(gameId, true);
    }

    function getGameId(address player, int index) constant returns (bytes32) {
      return gamesOfPlayers[player][index];
    }
    /* This unnamed function is called whenever someone tries to send ether to it */
    function () {
        throw;     // Prevents accidental sending of ether
    }
}


Added check for hash collisions

Added check for hash collisions

pragma solidity 0.4.15;

import "./Owned.sol";
import "./MarketHub.sol";
import "./Stoppable.sol";
import "./ERC20.sol";

contract Shop is Owned,Stoppable {

    event LogAddProduct(bytes32 indexed id);
    event LogStockChanged(bytes32 indexed id);
    event LogBuy(bytes32 indexed id);
    event LogDeleteProduct(bytes32 indexed id);

    struct Product{
        uint amount;
        uint price;
        bytes32 name;
        address token;
        uint index;
        bool exists;
    }

    bytes32[] public productIds;

    uint fee;

    address seller;

    mapping(bytes32=>Product) public products;

    modifier onlySeller(address account){
        require(seller == account);
        _;
    }

    modifier onlyAllowedToken(address account){
        require(isAllowedToken(account)||account==address(0));
        _;
    }

    modifier productExists(bytes32 id){
        require(productIds[products[id].index]==id);
        _;
    }

    function Shop(uint _fee,address _seller) {
        seller = _seller;
        fee = _fee;
    }

    function isAllowedToken(address tokenAddress)
    returns (bool isIndeed){
        MarketHub hub = MarketHub(owner);
        return hub.isAllowedToken(tokenAddress);
    }

    function addProductInternal(Product memory newProduct)
    internal
    returns (bytes32 id){
        id = sha3(newProduct.name,newProduct.token,newProduct.price);
        require(!products[id].exists); //Check for hash collisions
        productIds.push(id);
        newProduct.index = productIds.length-1;
        newProduct.exists = true;
        products[id] = newProduct;
    }

    function deleteProductInternal(bytes32 id)
    internal
    productExists(id){
        uint index = products[id].index;
        delete products[id];
        delete productIds[index];
        if(index!=productIds.length-1){
            bytes32 idToSwap = productIds[productIds.length-1];
            products[idToSwap].index = index;
            productIds[index] = idToSwap;
        }
        productIds.length--;
    }

    function addProduct(uint price,uint amount,bytes32 name,address tokenAddress)
    public
    isRunning
    onlySeller(msg.sender)
    onlyAllowedToken(tokenAddress)
    returns(bool success){
        require(price>fee);
        require(amount>0);

        Product memory newProduct;
        newProduct.price = price;
        newProduct.amount = amount;
        newProduct.name = name;
        newProduct.token = tokenAddress;

        bytes32 id = addProductInternal(newProduct);

        LogAddProduct(id);

        return true;
    }

    function deleteProduct(bytes32 id)
    public
    onlySeller(msg.sender)
    productExists(id)
    returns(bool success){
        require(msg.sender==seller);
        deleteProductInternal(id);

        LogDeleteProduct(id);
        return true;
    }

    function setProductStock(bytes32 id,uint amount)
    public
    onlySeller(msg.sender)
    productExists(id)
    returns (bool success){
        Product storage savedProduct = products[id];

        savedProduct.amount = amount;

        LogStockChanged(id);

        return true;
    }

    function buyWithTokens(bytes32 id)
    public
    isRunning
    productExists(id)
    returns (bool success){
        Product storage savedProduct = products[id];
        require(savedProduct.amount>0);
        require(currentTokenTransfer.sender!=address(0));
        require(savedProduct.token != address(0));
        require(currentTokenTransfer.value==savedProduct.price);

        savedProduct.amount--;

        ERC20 token = ERC20(msg.sender);
        token.approveAndCall(owner,currentTokenTransfer.value,"");

        LogBuy(id);
        return true;
    }

    function buy(bytes32 id)
    public
    payable
    isRunning
    productExists(id)
    returns (bool success){
        require(savedProduct.amount>0);
        Product storage savedProduct = products[id];
        require(savedProduct.token == address(0));
        require(msg.value==savedProduct.price);

        savedProduct.amount--;

        MarketHub hub = MarketHub(owner);

        hub.registerBuy.value(msg.value)();

        LogBuy(id);
        return true;
    }

    function setRunning(bool running)
    public
    onlyOwner
    returns (bool success){
        setRunningInternal(running);
        return true;
    }

    function getProductsCount()
    public
    constant
    returns (uint amount){
        return productIds.length;
    }

    function getProduct(bytes32 id)
    public
    constant
    productExists(id)
    returns(uint amount,uint price,bytes32 name){
        Product memory product = products[id];
        return (product.amount,product.price,product.name);
    }

    struct TokenTransfer{
        address sender;
        uint value;
    }

    TokenTransfer currentTokenTransfer;

    function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData)
    public
    isRunning
    onlyAllowedToken(msg.sender){
        require(_token == msg.sender);
        ERC20 token = ERC20(_token);
        token.transferFrom( _from, this, _value);
        require(_extraData.length!=0);
        currentTokenTransfer = TokenTransfer({
            sender:_from,
            value:_value
        });
        require(this.delegatecall(_extraData));
        delete currentTokenTransfer;

    }

    function tokenFallback(address _from, uint _value, bytes _data)
    public
    isRunning
    onlyAllowedToken(msg.sender){
        require(_data.length!=0);
        currentTokenTransfer = TokenTransfer({
            sender:_from,
            value:_value
        });
        require(this.delegatecall(_data));
        delete currentTokenTransfer;
    }

    function getPrice(bytes32 productId)
    public
    constant
    returns(uint price){
        return products[productId].price;
    }

    function getSeller()
    public
    constant
    returns(address _seller){
        return seller;
    }

}

pragma solidity 0.4.15;

import "./Owned.sol";
import "./MarketHub.sol";
import "./Stoppable.sol";
import "./ERC20.sol";

contract Shop is Owned,Stoppable {

    event LogAddProduct(bytes32 indexed id);
    event LogStockChanged(bytes32 indexed id);
    event LogBuy(bytes32 indexed id);
    event LogDeleteProduct(bytes32 indexed id);

    struct Product{
        uint amount;
        uint price;
        bytes32 name;
        address token;
        uint index;
    }

    bytes32[] public productIds;

    uint fee;

    address seller;

    mapping(bytes32=>Product) public products;

    modifier onlySeller(address account){
        require(seller == account);
        _;
    }

    modifier onlyAllowedToken(address account){
        require(isAllowedToken(account)||account==address(0));
        _;
    }

    modifier productExists(bytes32 id){
        require(productIds[products[id].index]==id);
        _;
    }

    function Shop(uint _fee,address _seller) {
        seller = _seller;
        fee = _fee;
    }

    function isAllowedToken(address tokenAddress)
    returns (bool isIndeed){
        MarketHub hub = MarketHub(owner);
        return hub.isAllowedToken(tokenAddress);
    }

    function addProductInternal(Product memory newProduct)
    internal
    returns (bytes32 id){
        id = sha3(newProduct.name,newProduct.token,newProduct.price);
        //require(productIds[products[id].index]!=id); Check for hash collisions
        productIds.push(id);
        newProduct.index = productIds.length-1;
        products[id] = newProduct;
    }

    function deleteProductInternal(bytes32 id)
    internal
    productExists(id){
        uint index = products[id].index;
        delete products[id];
        delete productIds[index];
        if(index!=productIds.length-1){
            bytes32 idToSwap = productIds[productIds.length-1];
            products[idToSwap].index = index;
            productIds[index] = idToSwap;
        }
        productIds.length--;
    }

    function addProduct(uint price,uint amount,bytes32 name,address tokenAddress)
    public
    isRunning
    onlySeller(msg.sender)
    onlyAllowedToken(tokenAddress)
    returns(bool success){
        require(price>fee);
        require(amount>0);

        Product memory newProduct;
        newProduct.price = price;
        newProduct.amount = amount;
        newProduct.name = name;
        newProduct.token = tokenAddress;

        bytes32 id = addProductInternal(newProduct);

        LogAddProduct(id);

        return true;
    }

    function deleteProduct(bytes32 id)
    public
    onlySeller(msg.sender)
    productExists(id)
    returns(bool success){
        require(msg.sender==seller);
        deleteProductInternal(id);

        LogDeleteProduct(id);
        return true;
    }

    function setProductStock(bytes32 id,uint amount)
    public
    onlySeller(msg.sender)
    productExists(id)
    returns (bool success){
        Product storage savedProduct = products[id];

        savedProduct.amount = amount;

        LogStockChanged(id);

        return true;
    }

    function buyWithTokens(bytes32 id)
    public
    isRunning
    productExists(id)
    returns (bool success){
        Product storage savedProduct = products[id];
        require(savedProduct.amount>0);
        require(currentTokenTransfer.sender!=address(0));
        require(savedProduct.token != address(0));
        require(currentTokenTransfer.value==savedProduct.price);

        savedProduct.amount--;

        ERC20 token = ERC20(msg.sender);
        token.approveAndCall(owner,currentTokenTransfer.value,"");

        LogBuy(id);
        return true;
    }

    function buy(bytes32 id)
    public
    payable
    isRunning
    productExists(id)
    returns (bool success){
        require(savedProduct.amount>0);
        Product storage savedProduct = products[id];
        require(savedProduct.token == address(0));
        require(msg.value==savedProduct.price);

        savedProduct.amount--;

        MarketHub hub = MarketHub(owner);

        hub.registerBuy.value(msg.value)();

        LogBuy(id);
        return true;
    }

    function setRunning(bool running)
    public
    onlyOwner
    returns (bool success){
        setRunningInternal(running);
        return true;
    }

    function getProductsCount()
    public
    constant
    returns (uint amount){
        return productIds.length;
    }

    function getProduct(bytes32 id)
    public
    constant
    productExists(id)
    returns(uint amount,uint price,bytes32 name){
        Product memory product = products[id];
        return (product.amount,product.price,product.name);
    }

    struct TokenTransfer{
        address sender;
        uint value;
    }

    TokenTransfer currentTokenTransfer;

    function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData)
    public
    isRunning
    onlyAllowedToken(msg.sender){
        require(_token == msg.sender);
        ERC20 token = ERC20(_token);
        token.transferFrom( _from, this, _value);
        require(_extraData.length!=0);
        currentTokenTransfer = TokenTransfer({
            sender:_from,
            value:_value
        });
        require(this.delegatecall(_extraData));
        delete currentTokenTransfer;

    }

    function tokenFallback(address _from, uint _value, bytes _data)
    public
    isRunning
    onlyAllowedToken(msg.sender){
        require(_data.length!=0);
        currentTokenTransfer = TokenTransfer({
            sender:_from,
            value:_value
        });
        require(this.delegatecall(_data));
        delete currentTokenTransfer;
    }

    function getPrice(bytes32 productId)
    public
    constant
    returns(uint price){
        return products[productId].price;
    }

    function getSeller()
    public
    constant
    returns(address _seller){
        return seller;
    }

}


EarningsPool: Fix test cases for feePoolShare() and rewardPoolShare() when claimableStake = 0

pragma solidity ^0.4.17;

import "../../contracts/test/EarningsPoolFixture.sol";
import "truffle/Assert.sol";

contract TestEarningsPool {
    EarningsPoolFixture fixture;

    function beforeEach() public {
        fixture = new EarningsPoolFixture();
        fixture.init(1000, 500000, 500000);
    }

    function test_init() public {
        var (rewardPool, feePool, totalStake, claimableStake, rewardCut, feeShare) = fixture.getEarningsPool();
        Assert.equal(rewardPool, 0, "wrong rewardPool");
        Assert.equal(feePool, 0, "wrong feePool");
        Assert.equal(totalStake, 1000, "wrong totalStake");
        Assert.equal(claimableStake, 1000, "wrong claimableStake");
        Assert.equal(rewardCut, 500000, "wrong transcoderRewardCut");
        Assert.equal(feeShare, 500000, "wrong transcoderFeeShare");
    }

    function test_claimShare_notTranscoder() public {
        fixture.setFeePool(1000);
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 250, "should claim delegator's share of fee pool");
        Assert.equal(rewards, 250, "should claim delegator's share of reward pool");
        Assert.equal(fixture.getFeePool(), 750, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getRewardPool(), 750, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShare_isTranscoder() public {
        fixture.setFeePool(1000);
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, true);
        Assert.equal(fees, 750, "should claim transcoder's share of fee pool which includes its share as a delegator");
        Assert.equal(rewards, 750, "should claim transcoder's share of reward pool which includes its share as a delegator");
        Assert.equal(fixture.getFeePool(), 250, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getRewardPool(), 250, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyFeePool_notTranscoder() public {
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 0, "should claim 0 fees when fee pool is empty");
        Assert.equal(rewards, 250, "should claim delegator's share of reward pool");
        Assert.equal(fixture.getRewardPool(), 750, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyFeePool_isTranscoder() public {
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, true);
        Assert.equal(fees, 0, "should claim 0 fees when fee pool is empty");
        Assert.equal(rewards, 750, "should claim transcoder's share of reward pool which includes its share as a delegator");
        Assert.equal(fixture.getRewardPool(), 250, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyRewardPool_notTranscoder() public {
        fixture.setFeePool(1000);
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 250, "should claim delegator's share of fee pool");
        Assert.equal(rewards, 0, "should claim 0 rewards when reward pool is empty");
        Assert.equal(fixture.getFeePool(), 750, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyRewardPool_isTranscoder() public {
        fixture.setFeePool(1000);
        var (fees, rewards) = fixture.claimShare(500, true);
        Assert.equal(fees, 750, "should claim transcoder's share of fee pool which includes its share as a delegator");
        Assert.equal(rewards, 0, "should claim 0 rewards when reward pool is empty");
        Assert.equal(fixture.getFeePool(), 250, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShare_emptyFeeAndRewardPools() public {
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 0, "should claim 0 fees when fee pool is empty");
        Assert.equal(rewards, 0, "should claim 0 rewards when reward pool is empty");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_feePoolShare_noClaimableStake() public {
        fixture.init(0, 0, 0);
        Assert.equal(fixture.feePoolShare(500, false), 0, "should return 0 if no claimble stake");
    }

    function test_feePoolShare_notTranscoder() public {
        fixture.setFeePool(1000);
        Assert.equal(fixture.feePoolShare(500, false), 250, "should return delegator's share of fee pool");
    }

    function test_feePoolShare_isTranscoder() public {
        fixture.setFeePool(1000);
        Assert.equal(fixture.feePoolShare(500, true), 750, "should return transcoder's share of fee pool which includes its share as a delegator");
    }

    function test_rewardPoolShare_noClaimableStake() public {
        fixture.init(0, 0, 0);
        Assert.equal(fixture.rewardPoolShare(500, false), 0, "should return 0 if no claimable stake");
    }

    function test_rewardPoolShare_notTranscoder() public {
        fixture.setRewardPool(1000);
        Assert.equal(fixture.rewardPoolShare(500, false), 250, "should return delegator's share of reward pool");
    }

    function test_rewardPoolShare_isTranscoder() public {
        fixture.setRewardPool(1000);
        Assert.equal(fixture.rewardPoolShare(500, true), 750, "should return transcoder's share of reward pool which includes its share as a delegator");
    }

    function test_hasClaimableShares_nonZeroClaimableStake() public {
        Assert.equal(fixture.hasClaimableShares(), true, "should return true when pool has non-zero claimable stake");
    }

    function test_hasClaimableShares_zeroClaimableStake() public {
        fixture.init(0, 0, 0);
        Assert.equal(fixture.hasClaimableShares(), false, "should return false when pool has zero claimable stake");
    }
}

pragma solidity ^0.4.17;

import "../../contracts/test/EarningsPoolFixture.sol";
import "truffle/Assert.sol";

contract TestEarningsPool {
    EarningsPoolFixture fixture;

    function beforeEach() public {
        fixture = new EarningsPoolFixture();
        fixture.init(1000, 500000, 500000);
    }

    function test_init() public {
        var (rewardPool, feePool, totalStake, claimableStake, rewardCut, feeShare) = fixture.getEarningsPool();
        Assert.equal(rewardPool, 0, "wrong rewardPool");
        Assert.equal(feePool, 0, "wrong feePool");
        Assert.equal(totalStake, 1000, "wrong totalStake");
        Assert.equal(claimableStake, 1000, "wrong claimableStake");
        Assert.equal(rewardCut, 500000, "wrong transcoderRewardCut");
        Assert.equal(feeShare, 500000, "wrong transcoderFeeShare");
    }

    function test_claimShare_notTranscoder() public {
        fixture.setFeePool(1000);
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 250, "should claim delegator's share of fee pool");
        Assert.equal(rewards, 250, "should claim delegator's share of reward pool");
        Assert.equal(fixture.getFeePool(), 750, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getRewardPool(), 750, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShare_isTranscoder() public {
        fixture.setFeePool(1000);
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, true);
        Assert.equal(fees, 750, "should claim transcoder's share of fee pool which includes its share as a delegator");
        Assert.equal(rewards, 750, "should claim transcoder's share of reward pool which includes its share as a delegator");
        Assert.equal(fixture.getFeePool(), 250, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getRewardPool(), 250, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyFeePool_notTranscoder() public {
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 0, "should claim 0 fees when fee pool is empty");
        Assert.equal(rewards, 250, "should claim delegator's share of reward pool");
        Assert.equal(fixture.getRewardPool(), 750, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyFeePool_isTranscoder() public {
        fixture.setRewardPool(1000);
        var (fees, rewards) = fixture.claimShare(500, true);
        Assert.equal(fees, 0, "should claim 0 fees when fee pool is empty");
        Assert.equal(rewards, 750, "should claim transcoder's share of reward pool which includes its share as a delegator");
        Assert.equal(fixture.getRewardPool(), 250, "should decrease reward pool by claimant's share of rewards");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyRewardPool_notTranscoder() public {
        fixture.setFeePool(1000);
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 250, "should claim delegator's share of fee pool");
        Assert.equal(rewards, 0, "should claim 0 rewards when reward pool is empty");
        Assert.equal(fixture.getFeePool(), 750, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShares_emptyRewardPool_isTranscoder() public {
        fixture.setFeePool(1000);
        var (fees, rewards) = fixture.claimShare(500, true);
        Assert.equal(fees, 750, "should claim transcoder's share of fee pool which includes its share as a delegator");
        Assert.equal(rewards, 0, "should claim 0 rewards when reward pool is empty");
        Assert.equal(fixture.getFeePool(), 250, "should decrease fee pool by claimant's share of fees");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_claimShare_emptyFeeAndRewardPools() public {
        var (fees, rewards) = fixture.claimShare(500, false);
        Assert.equal(fees, 0, "should claim 0 fees when fee pool is empty");
        Assert.equal(rewards, 0, "should claim 0 rewards when reward pool is empty");
        Assert.equal(fixture.getClaimableStake(), 500, "should decrease claimable stake by stake of claimant");
    }

    function test_feePoolShare_noClaimableStake() public {
        Assert.equal(fixture.feePoolShare(500, false), 0, "should return 0 if no claimble stake");
    }

    function test_feePoolShare_notTranscoder() public {
        fixture.setFeePool(1000);
        Assert.equal(fixture.feePoolShare(500, false), 250, "should return delegator's share of fee pool");
    }

    function test_feePoolShare_isTranscoder() public {
        fixture.setFeePool(1000);
        Assert.equal(fixture.feePoolShare(500, true), 750, "should return transcoder's share of fee pool which includes its share as a delegator");
    }

    function test_rewardPoolShare_noClaimableStake() public {
        Assert.equal(fixture.rewardPoolShare(500, false), 0, "should return 0 if no claimable stake");
    }

    function test_rewardPoolShare_notTranscoder() public {
        fixture.setRewardPool(1000);
        Assert.equal(fixture.rewardPoolShare(500, false), 250, "should return delegator's share of reward pool");
    }

    function test_rewardPoolShare_isTranscoder() public {
        fixture.setRewardPool(1000);
        Assert.equal(fixture.rewardPoolShare(500, true), 750, "should return transcoder's share of reward pool which includes its share as a delegator");
    }

    function test_hasClaimableShares_nonZeroClaimableStake() public {
        Assert.equal(fixture.hasClaimableShares(), true, "should return true when pool has non-zero claimable stake");
    }

    function test_hasClaimableShares_zeroClaimableStake() public {
        fixture.init(0, 0, 0);
        Assert.equal(fixture.hasClaimableShares(), false, "should return false when pool has zero claimable stake");
    }
}


Add my attempt at creating a root contract for a democratically-administered dapp.

contract root {
    // PoC-8

    uint public currentVersion;
    mapping (uint => address) public api;
    mapping (address => address) public owners;
    address _ownersTail;
    uint _numOwners;
    uint public quorum;
    uint8 public quorumPercent;
    uint public marginForVictory;
    uint8 public marginForVictoryPercent;
    mapping (address => ProposalCollection) public proposals;

    enum ProposalType {
        AddOwner, RemoveOwner,
        SetQuorumPercent, SetMarginForVictoryPercent,
        SetContract, SetVersion, SetApi, WipeProposals,
        Spend
    }

    enum Vote {
        Null, Yes, No, Abstain
    }

    struct ProposalCollection {
        mapping (uint => Proposal) proposals;
        mapping (uint => uint) timestamps;
        uint timestampsTail;
        uint8 numProposals;
    }

    struct Proposal {
        mapping (address => Vote) votes;
        uint numVotes;
        ProposalType type;
        address targetAddress;
        string32 targetFunction;
        address proposedContract;
        uint8 proposedPercent;
        uint value;
    }

    function root() {
        quorum = 1;
        quorumPercent = 60;
        marginForVictory = 0;
        owners[msg.sender] = msg.sender;
        _ownersTail = msg.sender;
    }

    function withdrawProposal(uint timestamp) {
        _removeProposal(msg.sender, timestamp);
    }

    function addOwner(address proposedOwner) {
        _createProposal(msg.sender, ProposalType.AddOwner);
        proposals[msg.sender].proposals[block.timestamp].targetAddress = proposedOwner;
    }

    function removeOwner(address proposedOwner) {
        _createProposal(msg.sender, ProposalType.RemoveOwner);
        proposals[msg.sender].proposals[block.timestamp].targetAddress = proposedOwner;
    }

    function setQuorumPercent(uint8 proposedQuorum) {
        _createProposal(msg.sender, ProposalType.SetQuorumPercent);
        proposals[msg.sender].proposals[block.timestamp].proposedPercent = proposedQuorum;
    }

    function setMarginForVictoryPercent(uint8 proposedMargin) {
        _createProposal(msg.sender, ProposalType.SetMarginForVictoryPercent);
        proposals[msg.sender].proposals[block.timestamp].proposedPercent = proposedMargin;
    }

    function setContract(address targetContract, string32 targetFunction, address proposedContract) {
        _createProposal(msg.sender, ProposalType.SetContract);
        var proposal = proposals[msg.sender].proposals[block.timestamp];
        proposal.targetAddress = targetContract;
        proposal.targetFunction = targetFunction;
        proposal.proposedContract = proposedContract;
    }

    function setVersion(uint version) {
        _createProposal(msg.sender, ProposalType.SetVersion);
        proposals[msg.sender].proposals[block.timestamp].value = version;
    }

    function setApi(uint version, address proposedApi) {
        _createProposal(msg.sender, ProposalType.SetVersion);
        var proposal = proposals[msg.sender].proposals[block.timestamp];
        proposal.value = version;
        proposal.proposedContract = proposedApi;
    }

    function wipeProposals() {
        _createProposal(msg.sender, ProposalType.WipeProposals);
    }

    function vote(address owner, uint timestamp, Vote vote) {
        if (proposals[owner].numProposals == 0 || proposals[owner].timestamps[timestamp] == 0) return;

        proposals[owner].proposals[timestamp].votes[msg.sender] = vote;
        proposals[owner].proposals[timestamp].numVotes += 1;

        _checkVotes(owner, timestamp);
    }

    function execute(address owner, uint timestamp) {
        if (proposals[owner].numProposals == 0 || proposals[owner].timestamps[timestamp] == 0) return;
        _checkVotes(owner, timestamp);
    }

    function _removeProposal(address owner, uint timestamp) private {
        var collection = proposals[owner];
        if (collection.numProposals == 0 || collection.timestamps[timestamp] == 0) return;

        uint iter = timestamp;
        for (uint8 i=0; i < collection.numProposals-1; i += 1) {
            iter = collection.timestamps[iter];
        }
        collection.timestamps[iter] = collection.timestamps[timestamp];

        delete collection.proposals[timestamp];
        collection.numProposals -= 1;
    }

    function _addOwner(address owner) private {
        owners[owner] = owners[_ownersTail];
        owners[_ownersTail] = owner;
        _ownersTail = owner;
        _numOwners += 1;
        proposals[owner].numProposals = 0;

        _updateMargins();
    }

    function _removeOwner(address owner) private {
        if (owners[owner] == address(0)) return;

        uint timestamp;
        address iter = owner;

        for (uint i=0; i < _numOwners-1; i+=1) {
            iter = owners[iter];

            var collection = proposals[iter];

            if (collection.numProposals == 0) continue;

            timestamp = collection.timestampsTail;

            for (uint8 j=0; j < collection.numProposals; j+=1) {
                if (collection.proposals[timestamp].votes[owner] != Vote.Null) {
                    delete collection.proposals[timestamp].votes[owner];
                    collection.proposals[timestamp].numVotes -= 1;
                }
                timestamp = collection.timestamps[timestamp];
            }
        }

        owners[iter] = owners[owner];
        delete owners[owner];
        delete proposals[owner];
        _numOwners -= 1;

        _updateMargins();
    }

    function _setQuorumPercent(uint8 percent) private {
        quorumPercent = percent;
        _updateMargins();
    }

    function _setMarginForVictoryPercent(uint8 percent) private {
        marginForVictoryPercent = percent;
        _updateMargins();
    }

    function _setContract(address targetContract, string32 targetFunction, address newContract) private {
        targetContract.call(string4(string32(sha3("setFunction(string32, address)"))), targetFunction, newContract);
    }

    function _setVersion(uint version) private {
        currentVersion = version;
    }

    function _setApi(uint version, address proposedApi) private {
        api[version] = proposedApi;
    }

    function _wipeProposals() private {
        address iter = _ownersTail;
        for (uint i=0; i < _numOwners; i += 1) {
            delete proposals[iter];
        }
        iter = owners[iter];
    }

    function _spend(address recipient, uint amount) private {
        recipient.send(amount);
    }

    function _updateMargins() private {
        quorum = (_numOwners * 100) / quorumPercent;
        marginForVictory = (_numOwners * 100) / marginForVictoryPercent;
    }

    function _createProposal(address owner, ProposalType type) internal {
        var collection = proposals[owner];

        if (collection.numProposals == 0) {
            collection.timestampsTail = block.timestamp;
            collection.timestamps[block.timestamp] = block.timestamp;

        } else {
            collection.timestamps[block.timestamp] = collection.timestamps[collection.timestampsTail];
            collection.timestamps[collection.timestampsTail] = block.timestamp;
            collection.timestampsTail = block.timestamp;
        }
        collection.numProposals += 1;

        var proposal = collection.proposals[block.timestamp];
        proposal.type = type;
        proposal.numVotes = 1;
        proposal.votes[owner] = Vote.Yes;
    }

    function _checkVotes(address owner, uint timestamp) private {
        var proposal = proposals[owner].proposals[timestamp];

        if (proposal.numVotes < quorum) return;

        uint yesTally = 0;
        uint noTally = 0;
        address iter = _ownersTail;

        for (uint i=0; i < _numOwners; i+=1) {
            if (proposal.votes[iter] == Vote.Abstain || proposal.votes[iter] == Vote.Null) {
                 continue;
            }

            if (proposal.votes[iter] == Vote.Yes) {
                yesTally += 1;
            } else {
                noTally -= 1;
            }
        }

        if (yesTally > noTally && (yesTally - noTally) >= marginForVictory) {
            _execute(owner, timestamp);
        } else if (noTally > yesTally && (noTally - yesTally) >= marginForVictory) {
            _removeProposal(owner, timestamp);
        }
    }

    function _execute(address owner, uint timestamp) private {
        var proposal = proposals[owner].proposals[timestamp];

        if (proposal.type == ProposalType.AddOwner) {
            _addOwner(proposal.targetAddress);

        } else if (proposal.type == ProposalType.RemoveOwner) {
            _removeOwner(proposal.targetAddress);

        } else if (proposal.type == ProposalType.SetQuorumPercent) {
            _setQuorumPercent(proposal.proposedPercent);

        } else if (proposal.type == ProposalType.SetMarginForVictoryPercent) {
            _setQuorumPercent(proposal.proposedPercent);

        } else if (proposal.type == ProposalType.SetContract) {
            _setContract(proposal.targetAddress, proposal.targetFunction,
                              proposal.proposedContract);

        } else if (proposal.type == ProposalType.SetVersion) {
            _setVersion(proposal.value);

        } else if (proposal.type == ProposalType.SetApi) {
            _setApi(proposal.value, proposal.proposedContract);

        } else if (proposal.type == ProposalType.WipeProposals) {
            _wipeProposals();

        } else if (proposal.type == ProposalType.Spend) {
            _spend(proposal.targetAddress, proposal.value);
        }
        _removeProposal(owner, timestamp);
    }
}

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


fix indentation in tests

fix indentation in tests

pragma solidity ^0.4.0;

// This is a contract
contract SimpleStorage {
    uint storedData;

    // This is a setter
    function set(uint x) public {
        storedData = x;
    }

    // This is a getter
    function get() public view returns (uint) {
        return storedData;
    }
}


comment fixes

comment fixes

pragma solidity ^0.4.15;

import './SafeMath.sol';
import './Ownable.sol';
import './TokenHolder.sol';
import './KinToken.sol';
import './VestingTrustee.sol';

/// @title Kin token sale contract.
contract KinTokenSale is Ownable, TokenHolder {
    using SafeMath for uint256;

    // External parties:

    // KIN token contract.
    KinToken public kin;

    // Vesting contract for pre-sale participants.
    VestingTrustee public trustee;

    // Received funds are forwarded to this address.
    address public fundingRecipient;

    // Kin token unit.
    // Using same decimal value as ETH (makes ETH-KIN conversion much easier).
    // This is the same as in Kin token contract.
    uint256 public constant TOKEN_UNIT = 10 ** 18;

    // Maximum number of tokens in circulation: 10 trillion.
    uint256 public constant MAX_TOKENS = 10 ** 13 * TOKEN_UNIT;

    // Maximum tokens offered in the sale.
    uint256 public constant MAX_TOKENS_SOLD = 512192121951 * TOKEN_UNIT;

    // Wei to 1 USD ratio.
    //
    // TODO update to the real ETH price before sale launch.
    uint256 public constant WEI_PER_USD = uint256(1 ether) / 360;

    // KIN to 1 USD ratio,
    // such that MAX_TOKENS_SOLD / KIN_PER_USD is the $75M cap.
    uint256 public constant KIN_PER_USD = 6829 * TOKEN_UNIT;

    // KIN to 1 wei ratio.
    uint256 public constant KIN_PER_WEI = KIN_PER_USD / WEI_PER_USD;

    // Sale start and end timestamps.
    uint256 public constant SALE_DURATION = 14 days;
    uint256 public startTime;
    uint256 public endTime;

    // Amount of tokens sold until now in the sale.
    uint256 public tokensSold = 0;

    // Participation caps, according to KYC tiers.
    uint256 public constant TIER_1_CAP = 100000 * WEI_PER_USD;
    uint256 public constant TIER_2_CAP = uint256(-1); // Maximum uint256 value

    // Accumulated amount each participant has contributed so far.
    mapping (address => uint256) public participationHistory;

    // Maximum amount that each participant is allowed to contribute (in WEI).
    mapping (address => uint256) public participationCaps;

    // Maximum amount ANYBODY is currently allowed to contribute.
    uint256 public hardParticipationCap = 5000 * WEI_PER_USD;

    // Vesting information for special addresses:
    struct TokenGrant {
        uint256 value;
        uint256 startOffset;
        uint256 cliffOffset;
        uint256 endOffset;
        uint256 installmentLength;
        uint8 percentVested;
    }

    address[] public tokenGrantees;
    mapping (address => TokenGrant) public tokenGrants;
    uint256 public lastGrantedIndex = 0;
    uint256 public constant MAX_TOKEN_GRANTEES = 100;
    uint256 public constant GRANT_BATCH_SIZE = 10;

    // Post-TDE multisig addresses.
    //
    // TODO: add real addresses here.
    address public constant KIN_FOUNDATION_ADDRESS = 0xa8F769B88d6D74FB2Bd3912F6793F75625228baF;
    address public constant KIK_ADDRESS = 0x7a029DC995f87B5cA060975b9A8A1b4bdB33cDC5;

    event TokensIssued(address indexed _to, uint256 _tokens);

    /// @dev Reverts if called when not during sale.
    modifier onlyDuringSale() {
        require(!saleEnded() && now >= startTime);

        _;
    }

    /// @dev Reverts if called before sale ends.
    modifier onlyAfterSale() {
        require(saleEnded());

        _;
    }

    /// @dev Constructor that initializes the sale conditions.
    /// @param _fundingRecipient address The address of the funding recipient.
    /// @param _startTime uint256 The start time of the token sale.
    function KinTokenSale(address _fundingRecipient, uint256 _startTime) {
        require(_fundingRecipient != address(0));
        require(_startTime > now);

        // Deploy new KinToken contract.
        kin = new KinToken();

        // Deploy new VestingTrustee contract.
        trustee = new VestingTrustee(kin);

        fundingRecipient = _fundingRecipient;
        startTime = _startTime;
        endTime = startTime + SALE_DURATION;

        // Initialize special vesting grants.
        initTokenGrants();
    }

    /// @dev Initialize token grants.
    ///
    /// TODO: add real values here.
    function initTokenGrants() private onlyOwner {
        // Issue the remaining 60% to Kin Foundation's multisig wallet. In a few days, after the token sale is
        // finalized, these tokens will be loaded into the KinVestingTrustee smart contract, according to the white
        // paper. Please note, that this is implied by setting a 0% vesting percent.
        tokenGrantees.push(KIN_FOUNDATION_ADDRESS);
        tokenGrants[KIN_FOUNDATION_ADDRESS] = TokenGrant(MAX_TOKENS.mul(60).div(100), 0, 0, 3 years, 1 days, 0);

        // Kik, 30%
        tokenGrantees.push(KIK_ADDRESS);
        tokenGrants[KIK_ADDRESS] = TokenGrant(MAX_TOKENS.mul(30).div(100), 0, 0, 120 weeks, 12 weeks, 100);
    }

    /// @dev Adds a Kin token vesting grant.
    /// @param _grantee address The address of the token grantee. Can be granted only once.
    /// @param _value uint256 The value of the grant.
    function addTokenGrant(address _grantee, uint256 _value) external onlyOwner {
        require(_grantee != address(0));
        require(_value > 0);
        require(tokenGrantees.length + 1 <= MAX_TOKEN_GRANTEES);

        // Verify the grant doesn't already exist.
        require(tokenGrants[_grantee].value == 0);
        for (uint i = 0; i < tokenGrantees.length; i++) {
            require(tokenGrantees[i] != _grantee);
        }

        // Add grant and add to grantee list.
        tokenGrantees.push(_grantee);
        tokenGrants[_grantee] = TokenGrant(_value, 0, 1 years, 1 years, 1 days, 50);
    }

    /// @dev Deletes a Kin token grant.
    /// @param _grantee address The address of the token grantee.
    function deleteTokenGrant(address _grantee) external onlyOwner {
        require(_grantee != address(0));

        // Delete the grant from the keys array.
        for (uint i = 0; i < tokenGrantees.length; i++) {
            if (tokenGrantees[i] == _grantee) {
                delete tokenGrantees[i];

                break;
            }
        }

        // Delete the grant from the mapping.
        delete tokenGrants[_grantee];
    }

    /// @dev Add a list of participants to a capped participation tier.
    /// @param _participants address[] The list of participant addresses.
    /// @param _cap uint256 The cap amount (in ETH).
    function setParticipationCap(address[] _participants, uint256 _cap) private onlyOwner {
        for (uint i = 0; i < _participants.length; i++) {
            participationCaps[_participants[i]] = _cap;
        }
    }

    /// @dev Add a list of participants to cap tier #1.
    /// @param _participants address[] The list of participant addresses.
    function setTier1Participants(address[] _participants) external onlyOwner {
        setParticipationCap(_participants, TIER_1_CAP);
    }

    /// @dev Add a list of participants to tier #2.
    /// @param _participants address[] The list of participant addresses.
    function setTier2Participants(address[] _participants) external onlyOwner {
        setParticipationCap(_participants, TIER_2_CAP);
    }

    /// @dev Set hard participation cap for all participants.
    /// @param _cap uint256 The hard cap amount.
    function setHardParticipationCap(uint256 _cap) external onlyOwner {
        require(_cap > 0);

        hardParticipationCap = _cap;
    }

    /// @dev Fallback function that will delegate the request to create().
    function () external payable onlyDuringSale {
        create(msg.sender);
    }

    /// @dev Create and sell tokens to the caller.
    /// @param _recipient address The address of the recipient receiving the tokens.
    function create(address _recipient) public payable onlyDuringSale {
        require(_recipient != address(0));

        // Enforce participation cap (in Wei received).
        uint256 weiAlreadyParticipated = participationHistory[msg.sender];
        uint256 participationCap = SafeMath.min256(participationCaps[msg.sender], hardParticipationCap);
        uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated));
        require(cappedWeiReceived > 0);

        // Accept funds and transfer to funding recipient.
        uint256 weiLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold).div(KIN_PER_WEI);
        uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale);
        participationHistory[msg.sender] = weiAlreadyParticipated.add(weiToParticipate);
        fundingRecipient.transfer(weiToParticipate);

        // Issue tokens and transfer to recipient.
        uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
        uint256 tokensToIssue = weiToParticipate.mul(KIN_PER_WEI);
        if (tokensLeftInSale.sub(tokensToIssue) < KIN_PER_WEI) {
            // If purchase would cause less than KIN_PER_WEI tokens left then nobody could ever buy them.
            // So, gift them to the last buyer.
            tokensToIssue = tokensLeftInSale;
        }
        tokensSold = tokensSold.add(tokensToIssue);
        issueTokens(_recipient, tokensToIssue);

        // Partial refund if full participation not possible
        // e.g. due to cap being reached.
        uint256 refund = msg.value.sub(weiToParticipate);
        if (refund > 0) {
            msg.sender.transfer(refund);
        }
    }

    /// @dev Finalizes the token sale event, by stopping token minting.
    function finalize() external onlyAfterSale onlyOwner {
        if (!kin.isMinting()) {
            revert();
        }

        require(lastGrantedIndex == tokenGrantees.length);

        // Finish minting.
        kin.endMinting();
    }

    /// @dev Grants pre-configured token grants in batches. When the method is called, it'll resume from the last grant,
    /// from its previous run, and will finish either after granting GRANT_BATCH_SIZE grants or finishing the whole list
    /// of grants.
    function grantTokens() external onlyAfterSale onlyOwner {
        uint endIndex = SafeMath.min256(tokenGrantees.length, lastGrantedIndex + GRANT_BATCH_SIZE);
        for (uint i = lastGrantedIndex; i < endIndex; i++) {
            address grantee = tokenGrantees[i];

            // Calculate how many tokens have been granted, vested, and issued such that: granted = vested + issued.
            TokenGrant memory tokenGrant = tokenGrants[grantee];
            uint256 tokensGranted = tokenGrant.value.mul(tokensSold).div(MAX_TOKENS_SOLD);
            uint256 tokensVesting = tokensGranted.mul(tokenGrant.percentVested).div(100);
            uint256 tokensIssued = tokensGranted.sub(tokensVesting);

            // Transfer issued tokens that have yet to be transferred to grantee.
            if (tokensIssued > 0) {
                issueTokens(grantee, tokensIssued);
            }

            // Transfer vested tokens that have yet to be transferred to vesting trustee, and initialize grant.
            if (tokensVesting > 0) {
                issueTokens(trustee, tokensVesting);
                trustee.grant(grantee, tokensVesting, now.add(tokenGrant.startOffset), now.add(tokenGrant.cliffOffset),
                    now.add(tokenGrant.endOffset), tokenGrant.installmentLength, true);
            }

            lastGrantedIndex++;
        }
    }

    /// @dev Issues tokens for the recipient.
    /// @param _recipient address The address of the recipient.
    /// @param _tokens uint256 The amount of tokens to issue.
    function issueTokens(address _recipient, uint256 _tokens) private {
        // Request Kin token contract to mint the requested tokens for the buyer.
        kin.mint(_recipient, _tokens);

        TokensIssued(_recipient, _tokens);
    }

    /// @dev Returns whether the sale has ended.
    /// @return bool Whether the sale has ended or not.
    function saleEnded() private constant returns (bool) {
        return tokensSold >= MAX_TOKENS_SOLD || now >= endTime;
    }

    /// @dev Requests to transfer control of the Kin token contract to a new owner.
    /// @param _newOwnerCandidate address The address to transfer ownership to.
    ///
    /// NOTE:
    ///   1. The new owner will need to call Kin token contract's acceptOwnership directly in order to accept the ownership.
    ///   2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of
    ///      the Kin token contract can issue new tokens.
    function requestKinTokenOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
        kin.requestOwnershipTransfer(_newOwnerCandidate);
    }

    /// @dev Accepts new ownership on behalf of the Kin token contract.
    // This can be used by the sale contract itself to claim back ownership of the Kin token contract.
    function acceptKinTokenOwnership() external onlyOwner {
        kin.acceptOwnership();
    }

    /// @dev Requests to transfer control of the VestingTrustee contract to a new owner.
    /// @param _newOwnerCandidate address The address to transfer ownership to.
    ///
    /// NOTE:
    ///   1. The new owner will need to call VestingTrustee's acceptOwnership directly in order to accept the ownership.
    ///   2. Calling this method during the token sale will prevent the token sale from finalizaing, since only the owner
    ///      of the VestingTrustee contract can issue new token grants.
    function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
        trustee.requestOwnershipTransfer(_newOwnerCandidate);
    }

    /// @dev Accepts new ownership on behalf of the VestingTrustee contract.
    /// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract.
    function acceptVestingTrusteeOwnership() external onlyOwner {
        trustee.acceptOwnership();
    }
}

pragma solidity ^0.4.15;

import './SafeMath.sol';
import './Ownable.sol';
import './TokenHolder.sol';
import './KinToken.sol';
import './VestingTrustee.sol';

/// @title Kin token sale contract.
contract KinTokenSale is Ownable, TokenHolder {
    using SafeMath for uint256;

    // External parties:

    // KIN token contract.
    KinToken public kin;

    // Vesting contract for pre-sale participants.
    VestingTrustee public trustee;

    // Received funds are forwarded to this address.
    address public fundingRecipient;

    // Kin token unit.
    // Using same decimal value as ETH (makes ETH-KIN conversion much easier).
    // This is the same as in Kin token contract.
    uint256 public constant TOKEN_UNIT = 10 ** 18;

    // Maximum number of tokens in circulation: 10 trillion.
    uint256 public constant MAX_TOKENS = 10 ** 13 * TOKEN_UNIT;

    // Maximum tokens offered in the sale.
    uint256 public constant MAX_TOKENS_SOLD = 512192121951 * TOKEN_UNIT;

    // Wei to 1 USD ratio.
    //
    // TODO update to the real ETH price before sale launch.
    uint256 public constant WEI_PER_USD = uint256(1 ether) / 360;

    // KIN to 1 USD ratio,
    // such MAX_TOKENS_SOLD * KIN_PER_USD is the $75M cap.
    uint256 public constant KIN_PER_USD = 6829 * TOKEN_UNIT;

    // KIN to 1 wei ratio.
    uint256 public constant KIN_PER_WEI = KIN_PER_USD / WEI_PER_USD;

    // Sale start and end timestamps.
    uint256 public constant SALE_DURATION = 14 days;
    uint256 public startTime;
    uint256 public endTime;

    // Amount of tokens sold until now in the sale.
    uint256 public tokensSold = 0;

    // Participation caps, according to KYC tiers.
    uint256 public constant TIER_1_CAP = 100000 * WEI_PER_USD;
    uint256 public constant TIER_2_CAP = uint256(-1); // Maximum uint256 value

    // Accumulated amount each participant have contributed so far.
    mapping (address => uint256) public participationHistory;

    // Maximum amount that each particular is allowed to contribute (in WEI).
    mapping (address => uint256) public participationCaps;

    // Maximum amount ANYBODY is currently allowed to contribute.
    uint256 public hardParticipationCap = 5000 * WEI_PER_USD;

    // Vesting information for special addresses:
    struct TokenGrant {
        uint256 value;
        uint256 startOffset;
        uint256 cliffOffset;
        uint256 endOffset;
        uint256 installmentLength;
        uint8 percentVested;
    }

    address[] public tokenGrantees;
    mapping (address => TokenGrant) public tokenGrants;
    uint256 public lastGrantedIndex = 0;
    uint256 public constant MAX_TOKEN_GRANTEES = 100;
    uint256 public constant GRANT_BATCH_SIZE = 10;

    // Post-TDE multisig addresses.
    //
    // TODO: add real addresses here.
    address public constant KIN_FOUNDATION_ADDRESS = 0xa8F769B88d6D74FB2Bd3912F6793F75625228baF;
    address public constant KIK_ADDRESS = 0x7a029DC995f87B5cA060975b9A8A1b4bdB33cDC5;

    event TokensIssued(address indexed _to, uint256 _tokens);

    /// @dev Reverts if called when not during sale.
    modifier onlyDuringSale() {
        require(!saleEnded() && now >= startTime);

        _;
    }

    /// @dev Reverts if called before sale ends.
    modifier onlyAfterSale() {
        require(saleEnded());

        _;
    }

    /// @dev Constructor that initializes the sale conditions.
    /// @param _fundingRecipient address The address of the funding recipient.
    /// @param _startTime uint256 The start time of the token sale.
    function KinTokenSale(address _fundingRecipient, uint256 _startTime) {
        require(_fundingRecipient != address(0));
        require(_startTime > now);

        // Deploy new KinToken contract.
        kin = new KinToken();

        // Deploy new VestingTrustee contract.
        trustee = new VestingTrustee(kin);

        fundingRecipient = _fundingRecipient;
        startTime = _startTime;
        endTime = startTime + SALE_DURATION;

        // Initialize special vesting grants.
        initTokenGrants();
    }

    /// @dev Initialize token grants.
    ///
    /// TODO: add real values here.
    function initTokenGrants() private onlyOwner {
        // Issue the remaining 60% to Kin Foundation's multisig wallet. In a few days, after the token sale is
        // finalized, these tokens will be loaded into the KinVestingTrustee smart contract, according to the white
        // paper. Please note, that this is implied by setting a 0% vesting percent.
        tokenGrantees.push(KIN_FOUNDATION_ADDRESS);
        tokenGrants[KIN_FOUNDATION_ADDRESS] = TokenGrant(MAX_TOKENS.mul(60).div(100), 0, 0, 3 years, 1 days, 0);

        // Kik, 30%
        tokenGrantees.push(KIK_ADDRESS);
        tokenGrants[KIK_ADDRESS] = TokenGrant(MAX_TOKENS.mul(30).div(100), 0, 0, 120 weeks, 12 weeks, 100);
    }

    /// @dev Adds a Kin token vesting grant.
    /// @param _grantee address The address of the token grantee. Can be granted only once.
    /// @param _value uint256 The value of the grant.
    function addTokenGrant(address _grantee, uint256 _value) external onlyOwner {
        require(_grantee != address(0));
        require(_value > 0);
        require(tokenGrantees.length + 1 <= MAX_TOKEN_GRANTEES);

        // Verify the grant doesn't already exist.
        require(tokenGrants[_grantee].value == 0);
        for (uint i = 0; i < tokenGrantees.length; i++) {
            require(tokenGrantees[i] != _grantee);
        }

        // Add grant and add to grantee list.
        tokenGrantees.push(_grantee);
        tokenGrants[_grantee] = TokenGrant(_value, 0, 1 years, 1 years, 1 days, 50);
    }

    /// @dev Deletes a Kin token grant.
    /// @param _grantee address The address of the token grantee.
    function deleteTokenGrant(address _grantee) external onlyOwner {
        require(_grantee != address(0));

        // Delete the grant from the keys array.
        for (uint i = 0; i < tokenGrantees.length; i++) {
            if (tokenGrantees[i] == _grantee) {
                delete tokenGrantees[i];

                break;
            }
        }

        // Delete the grant from the mapping.
        delete tokenGrants[_grantee];
    }

    /// @dev Add a list of participants to a capped participation tier.
    /// @param _participants address[] The list of participant addresses.
    /// @param _cap uint256 The cap amount (in ETH).
    function setParticipationCap(address[] _participants, uint256 _cap) private onlyOwner {
        for (uint i = 0; i < _participants.length; i++) {
            participationCaps[_participants[i]] = _cap;
        }
    }

    /// @dev Add a list of participants to cap tier #1.
    /// @param _participants address[] The list of participant addresses.
    function setTier1Participants(address[] _participants) external onlyOwner {
        setParticipationCap(_participants, TIER_1_CAP);
    }

    /// @dev Add a list of participants to tier #2.
    /// @param _participants address[] The list of participant addresses.
    function setTier2Participants(address[] _participants) external onlyOwner {
        setParticipationCap(_participants, TIER_2_CAP);
    }

    /// @dev Set hard participation cap for all participants.
    /// @param _cap uint256 The hard cap amount.
    function setHardParticipationCap(uint256 _cap) external onlyOwner {
        require(_cap > 0);

        hardParticipationCap = _cap;
    }

    /// @dev Fallback function that will delegate the request to create().
    function () external payable onlyDuringSale {
        create(msg.sender);
    }

    /// @dev Create and sell tokens to the caller.
    /// @param _recipient address The address of the recipient receiving the tokens.
    function create(address _recipient) public payable onlyDuringSale {
        require(_recipient != address(0));

        // Enforce participation cap (in Wei received).
        uint256 weiAlreadyParticipated = participationHistory[msg.sender];
        uint256 participationCap = SafeMath.min256(participationCaps[msg.sender], hardParticipationCap);
        uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated));
        require(cappedWeiReceived > 0);

        // Accept funds and transfer to funding recipient.
        uint256 weiLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold).div(KIN_PER_WEI);
        uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale);
        participationHistory[msg.sender] = weiAlreadyParticipated.add(weiToParticipate);
        fundingRecipient.transfer(weiToParticipate);

        // Issue tokens and transfer to recipient.
        uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
        uint256 tokensToIssue = weiToParticipate.mul(KIN_PER_WEI);
        if (tokensLeftInSale.sub(tokensToIssue) < KIN_PER_WEI) {
            // If purchase would cause less than KIN_PER_WEI tokens left then nobody could ever buy them.
            // So, gift them to the last buyer.
            tokensToIssue = tokensLeftInSale;
        }
        tokensSold = tokensSold.add(tokensToIssue);
        issueTokens(_recipient, tokensToIssue);

        // Partial refund if full participation not possible
        // e.g. due to cap being reached.
        uint256 refund = msg.value.sub(weiToParticipate);
        if (refund > 0) {
            msg.sender.transfer(refund);
        }
    }

    /// @dev Finalizes the token sale event, by stopping token minting.
    function finalize() external onlyAfterSale onlyOwner {
        if (!kin.isMinting()) {
            revert();
        }

        require(lastGrantedIndex == tokenGrantees.length);

        // Finish minting.
        kin.endMinting();
    }

    /// @dev Grants pre-configured token grants in batches. When the method is called, it'll resume from the last grant,
    /// from its previous run, and will finish either after granting GRANT_BATCH_SIZE grants or finishing the whole list
    /// of grants.
    function grantTokens() external onlyAfterSale onlyOwner {
        uint endIndex = SafeMath.min256(tokenGrantees.length, lastGrantedIndex + GRANT_BATCH_SIZE);
        for (uint i = lastGrantedIndex; i < endIndex; i++) {
            address grantee = tokenGrantees[i];

            // Calculate how many tokens have been granted, vested, and issued such that: granted = vested + issued.
            TokenGrant memory tokenGrant = tokenGrants[grantee];
            uint256 tokensGranted = tokenGrant.value.mul(tokensSold).div(MAX_TOKENS_SOLD);
            uint256 tokensVesting = tokensGranted.mul(tokenGrant.percentVested).div(100);
            uint256 tokensIssued = tokensGranted.sub(tokensVesting);

            // Transfer issued tokens that have yet to be transferred to grantee.
            if (tokensIssued > 0) {
                issueTokens(grantee, tokensIssued);
            }

            // Transfer vested tokens that have yet to be transferred to vesting trustee, and initialize grant.
            if (tokensVesting > 0) {
                issueTokens(trustee, tokensVesting);
                trustee.grant(grantee, tokensVesting, now.add(tokenGrant.startOffset), now.add(tokenGrant.cliffOffset),
                    now.add(tokenGrant.endOffset), tokenGrant.installmentLength, true);
            }

            lastGrantedIndex++;
        }
    }

    /// @dev Issues tokens for the recipient.
    /// @param _recipient address The address of the recipient.
    /// @param _tokens uint256 The amount of tokens to issue.
    function issueTokens(address _recipient, uint256 _tokens) private {
        // Request Kin token contract to mint the requested tokens for the buyer.
        kin.mint(_recipient, _tokens);

        TokensIssued(_recipient, _tokens);
    }

    /// @dev Returns whether the sale has ended.
    /// @return bool Whether the sale has ended or not.
    function saleEnded() private constant returns (bool) {
        return tokensSold >= MAX_TOKENS_SOLD || now >= endTime;
    }

    /// @dev Requests to transfer control of the Kin token contract to a new owner.
    /// @param _newOwnerCandidate address The address to transfer ownership to.
    ///
    /// NOTE:
    ///   1. The new owner will need to call Kin token contract's acceptOwnership directly in order to accept the ownership.
    ///   2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of
    ///      the Kin token contract can issue new tokens.
    function requestKinTokenOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
        kin.requestOwnershipTransfer(_newOwnerCandidate);
    }

    /// @dev Accepts new ownership on behalf of the Kin token contract.
    // This can be used by the sale contract itself to claim back ownership of the Kin token contract.
    function acceptKinTokenOwnership() external onlyOwner {
        kin.acceptOwnership();
    }

    /// @dev Requests to transfer control of the VestingTrustee contract to a new owner.
    /// @param _newOwnerCandidate address The address to transfer ownership to.
    ///
    /// NOTE:
    ///   1. The new owner will need to call VestingTrustee's acceptOwnership directly in order to accept the ownership.
    ///   2. Calling this method during the token sale will prevent the token sale from finalizaing, since only the owner
    ///      of the VestingTrustee contract can issue new token grants.
    function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
        trustee.requestOwnershipTransfer(_newOwnerCandidate);
    }

    /// @dev Accepts new ownership on behalf of the VestingTrustee contract.
    /// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract.
    function acceptVestingTrusteeOwnership() external onlyOwner {
        trustee.acceptOwnership();
    }
}


Clean up naming and comments in ManagerProxy

pragma solidity ^0.4.17;

import "./ManagerProxyTarget.sol";

contract ManagerProxy is ManagerProxyTarget {
    function ManagerProxy(address _controller, bytes32 _targetContractId) public Manager(_controller) {
        targetContractId = _targetContractId;
    }

    // Based on https://github.com/AugurProject/augur-core/blob/develop/src/libraries/Delegator.sol
    function() public payable {
        address target = controller.getContract(targetContractId);
        // Target contract must be registered
        require(target > 0);

        assembly {
            // Solidity keeps a free memory pointer at position 0x40 in memory
            let freeMemoryPtrPosition := 0x40
            // Load the free memory pointer
            let calldataMemoryOffset := mload(freeMemoryPtrPosition)
            // Update free memory pointer to after memory space we reserve for calldata
            mstore(freeMemoryPtrPosition, add(calldataMemoryOffset, calldatasize))
            // Copy calldata (method signature and params of the call) to memory
            calldatacopy(calldataMemoryOffset, 0x0, calldatasize)

            // Call method on target contract using calldata which is loaded into memory
            let ret := delegatecall(gas, target, calldataMemoryOffset, calldatasize, 0, 0)

            // Load the free memory pointer
            let returndataMemoryOffset := mload(freeMemoryPtrPosition)
            // Update free memory pointer to after memory space we reserve for returndata
            mstore(freeMemoryPtrPosition, add(returndataMemoryOffset, returndatasize))
            // Copy returndata (result of the method invoked by the delegatecall) to memory
            returndatacopy(returndataMemoryOffset, 0x0, returndatasize)

            switch ret
            case 0 {
                // Method call failed - revert
                // Return any error message stored in mem[returndataMemoryOffset..(returndataMemoryOffset + returndatasize)]
                revert(returndataMemoryOffset, returndatasize)
            } default {
                // Return result of method call stored in mem[returndataMemoryOffset..(returndataMemoryOffset + returndatasize)]
                return(returndataMemoryOffset, returndatasize)
            }
        }
    }
}

pragma solidity ^0.4.17;

import "./ManagerProxyTarget.sol";

contract ManagerProxy is ManagerProxyTarget {
    function ManagerProxy(address _controller, bytes32 _targetContractId) public Manager(_controller) {
        targetContractId = _targetContractId;
    }

    // Based on https://github.com/AugurProject/augur-core/blob/develop/src/libraries/Delegator.sol
    function() public payable {
        address target = controller.getContract(targetContractId);
        // Target contract must be registered
        require(target > 0);

        assembly {
            // Load the free memory pointer at 0x40
            let calldataMemoryOffset := mload(0x40)
            // Update free memory pointer to after memory space we reserve for calldata
            mstore(0x40, add(calldataMemoryOffset, calldatasize))
            // Copy method signature and params of the call to memory
            calldatacopy(calldataMemoryOffset, 0x0, calldatasize)

            // Call method on target contract and store result starting at calldataMemoryOffset
            let ret := delegatecall(gas, target, calldataMemoryOffset, calldatasize, 0, 0)

            // Load the free memory pointer at 0x40
            let returndataOffset := mload(0x40)
            // Update free memory pointer to after memory space we reserve for returndata
            mstore(0x40, add(returndataOffset, returndatasize))
            // Copy returndata to memory
            returndatacopy(returndataOffset, 0, returndatasize)

            switch ret
            case 0 {
                // Method call failed - revert
                // Return any error message contained in returndata
                revert(returndataOffset, returndatasize)
            } default {
                // Return result of method call stored in mem[returndataOffset..(returndataOffset + returndatasize)]
                return(returndataOffset, returndatasize)
            }
        }
    }
}


add onlyConcept modifier to add and subtract balance

pragma solidity ^0.4.0;

import "./Concept.sol";
import "./User.sol";
import "./ConceptRegistry.sol";

/*
@type: contract
@name: UserRegistry
@purpose: To store data about users for easy and secure access
*/
contract UserRegistry {
  address public conceptRegistry; //The address of the conceptRegistry contract
  mapping (address => uint) public balances; //Maps the addresses of users to their token balances
  mapping (address => address) public users; //Maps the addresses of the users to their account
  bool firstUserMade = false; //Keeps track of whether or not the first user has been made yet
  event UserCreation(address _userAddress); //address of the created user contract

  modifier onlyConcept() {
    if(ConceptRegistry(conceptRegistry).conceptExists(msg.sender) == false) //checks if the address calling the function is not a concept
    {
      throw; //throws out the fucntion call
    }
    _;
  }

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

  //Constructor
  function UserRegistry(address _conceptRegistry) {
    conceptRegistry = _conceptRegistry;
  }

  /*
  @type: function
  @purpose: To create a user contract
  @param: address userAddress = the address of the user's wallet
  @param: address masterAddress = the address of the master contract that stores this user's address
  @returns: nothing
  */
  function addUser(address userAddress) {
    User newUser = new User(userAddress, address(this)); //Makes a new user that represents the address from userAddress and uses the master from masterAddress as its datastore
    Concept(ConceptRegistry(conceptRegistry).mewAddress()).addUser(address(newUser));
    users[userAddress] = newUser;
    UserCreation(address(newUser)); //Makes a new UserCreation event with the address of the newly created user
  }

  function firstUser(address userAddress) {
    if(firstUserMade == false) {
      User newUser = new User(userAddress, address(this)); //Makes a new user that represents the address from userAddress
      Concept(ConceptRegistry(conceptRegistry).mewAddress()).addUser(address(newUser));
      users[userAddress] = newUser;
      balances[newUser] = 1000;
      UserCreation(address(newUser)); //Makes a new UserCreation event with the address of the newly created user
    }
  }

  function addBalance(address _to, uint _amount) onlyConcept() returns(bool) {
    if(balances[_to] + _amount > balances[_to]){
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

  function subtractBalance(address _from, uint _amount) onlyConcept() returns(bool) {
    if(balances[_from] > _amount){
      balances[_from] -= _amount;
      return true;
    }
    return false;
  }

  function transfer(address _to, uint _amount) returns(bool) {
    if(balances[msg.sender] > _amount &&
       balances[_to] + _amount > balances[_to]) {
      balances[msg.sender] -= _amount;
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

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

pragma solidity ^0.4.0;

import "./Concept.sol";
import "./User.sol";
import "./ConceptRegistry.sol";

/*
@type: contract
@name: UserRegistry
@purpose: To store data about users for easy and secure access
*/
contract UserRegistry {
  address public conceptRegistry; //The address of the conceptRegistry contract
  mapping (address => uint) public balances; //Maps the addresses of users to their token balances
  mapping (address => address) public users; //Maps the addresses of the users to their account
  bool firstUserMade = false; //Keeps track of whether or not the first user has been made yet
  event UserCreation(address _userAddress); //address of the created user contract

  modifier onlyConcept() {
    if(ConceptRegistry(conceptRegistry).conceptExists(msg.sender) == false) //checks if the address calling the function is not a concept
    {
      throw; //throws out the fucntion call
    }
    _;
  }

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

  //Constructor
  function UserRegistry(address _conceptRegistry) {
    conceptRegistry = _conceptRegistry;
  }

  /*
  @type: function
  @purpose: To create a user contract
  @param: address userAddress = the address of the user's wallet
  @param: address masterAddress = the address of the master contract that stores this user's address
  @returns: nothing
  */
  function addUser(address userAddress) {
    User newUser = new User(userAddress, address(this)); //Makes a new user that represents the address from userAddress and uses the master from masterAddress as its datastore
    Concept(ConceptRegistry(conceptRegistry).mewAddress()).addUser(address(newUser));
    users[userAddress] = newUser;
    UserCreation(address(newUser)); //Makes a new UserCreation event with the address of the newly created user
  }

  function firstUser(address userAddress) {
    if(firstUserMade == false) {
      User newUser = new User(userAddress, address(this)); //Makes a new user that represents the address from userAddress
      Concept(ConceptRegistry(conceptRegistry).mewAddress()).addUser(address(newUser));
      users[userAddress] = newUser;
      balances[newUser] = 1000;
      UserCreation(address(newUser)); //Makes a new UserCreation event with the address of the newly created user
    }
  }

  function addBalance(address _to, uint _amount) returns(bool) {
    if(balances[_to] + _amount > balances[_to]){
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

  function subtractBalance(address _from, uint _amount) returns(bool) {
    if(balances[_from] > _amount){
      balances[_from] -= _amount;
      return true;
    }
    return false;
  }

  function transfer(address _to, uint _amount) returns(bool) {
    if(balances[msg.sender] > _amount &&
       balances[_to] + _amount > balances[_to]) {
      balances[msg.sender] -= _amount;
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

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


Rearrange function declaration order

Rearrange function declaration order

/*
 * Partial src: https://github.com/eris-ltd/hello-eris/blob/master/contracts/DealManager.sol
 */

import "Task.sol";
import "SequenceList.sol";

contract TaskManager {
    SequenceList list = new SequenceList();

    /*modifier onlyOwner() {
        if (msg.sender != owner)
        throw;

        _ // `_` is synonymous to JS middleware's `next()`
    }*/

    // TODO extend with eventObject if possible; `bytes32[]`?
    event ActionEvent(address indexed userAddr, bytes32 actionType);
    function registerActionEvent(bytes32 actionType) {
      ActionEvent(msg.sender, actionType);
    }

    /**
     * Adds a new task with the specified attributes
     */
    function addTask(
        bytes32 _id,
        bytes32 _title,
        bytes32 _desc,
        bytes32 _status,
        bytes32 _complete,
        bytes32 _reward,
        bytes32 _participants,
        bytes32 _creator
        )
        returns (Task t)
    {
        t = new Task(_id, _title, _desc, _status, _complete, _reward, _participants, _creator);

        bool isOverwrite = list.insert(_id, t);
        registerActionEvent("ADD TASK");
        // TODO needs a verification of insert success
        return t;
    }

    function getTaskAtIndex(uint _idx) constant returns (address, uint) {
        registerActionEvent("GET TASK AT INDEX");
        return list.valueAtIndexHasNext(_idx);
    }

    function getTaskAddress(bytes32 _id) constant returns (address) {
        registerActionEvent("GET TASK ADDRESS");
        return list.value(_id);
    }

    function getTaskKeyAtIndex(uint _idx) constant returns (bytes32) {
        return list.keyAtIndex(_idx);
    }

    function getTaskListSize() constant returns (uint) {
        registerActionEvent("GET TASKLIST SIZE");
        return list.size();

    }
}

/*
 * Partial src: https://github.com/eris-ltd/hello-eris/blob/master/contracts/DealManager.sol
 */

import "Task.sol";
import "SequenceList.sol";

contract TaskManager {
    SequenceList list = new SequenceList();

    /*modifier onlyOwner() {
        if (msg.sender != owner)
        throw;

        _ // `_` is synonymous to JS middleware's `next()`
    }*/

    // TODO extend with eventObject if possible; `bytes32[]`?
    event ActionEvent(address indexed userAddr, bytes32 actionType);
    function registerActionEvent(bytes32 actionType) {
      ActionEvent(msg.sender, actionType);
    }

    /**
     * Adds a new task with the specified attributes
     */
    function addTask(
        bytes32 _id,
        bytes32 _title,
        bytes32 _desc,
        bytes32 _status,
        bytes32 _complete,
        bytes32 _reward,
        bytes32 _participants,
        bytes32 _creator
        )
        returns (Task t)
    {
        t = new Task(_id, _title, _desc, _status, _complete, _reward, _participants, _creator);

        bool isOverwrite = list.insert(_id, t);
        registerActionEvent("ADD TASK");
        // TODO needs a verification of insert success
        return t;
    }

    function getTaskAtIndex(uint _idx) constant returns (address, uint) {
        registerActionEvent("GET TASK");
        return list.valueAtIndexHasNext(_idx);
    }

    function getTaskListSize() constant returns (uint) {
        registerActionEvent("GET TASKLIST SIZE");
        return list.size();

    }

    function getTaskKeyAtIndex(uint _idx) constant returns (bytes32) {
        return list.keyAtIndex(_idx);
    }

    function getTaskAddress(bytes32 _id) constant returns (address) {
        return list.value(_id);
    }
}