remove another global var for some small gas savings

/*
    Copyright 2017-2018 Phillip A. Elsasser

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

pragma solidity ^0.4.18;

import "./oraclizeAPI.sol";
import "../libraries/MathLib.sol";
import "../MarketContract.sol";

/// @title MarketContract first example of a MarketProtocol contract using Oraclize services
/// @author Phil Elsasser <phil@marketprotocol.io>
contract MarketContractOraclize is MarketContract, usingOraclize {
    using MathLib for uint;

    // constants
    string public ORACLE_DATA_SOURCE;
    string public ORACLE_QUERY;
    uint constant public QUERY_CALLBACK_GAS = 150000;
    //uint constant public QUERY_CALLBACK_GAS_PRICE = 20000000000 wei; // 20 gwei - need to make this dynamic!

    // state variables
    string public lastPriceQueryResult;
    mapping(bytes32 => bool) validQueryIDs;

    /// @param contractName viewable name of this contract (BTC/ETH, LTC/ETH, etc)
    /// @param marketTokenAddress address of our member token
    /// @param baseTokenAddress address of the ERC20 token that will be used for collateral and pricing
    /// @param contractSpecs array of unsigned integers including:
    /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached
    /// capPrice maximum tradeable price of this contract, contract enters settlement if breached
    /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to
    /// an integer
    /// qtyMultiplier multiply traded qty by this value from base units of collateral token.
    /// expirationTimeStamp - seconds from epoch that this contract expires and enters settlement
    /// @param oracleDataSource a data-source such as "URL", "WolframAlpha", "IPFS"
    /// see http://docs.oraclize.it/#ethereum-quick-start-simple-query
    /// @param oracleQuery see http://docs.oraclize.it/#ethereum-quick-start-simple-query for examples
    function MarketContractOraclize(
        string contractName,
        address marketTokenAddress,
        address baseTokenAddress,
        uint[5] contractSpecs,
        string oracleDataSource,
        string oracleQuery
    ) MarketContract(
        contractName,
        marketTokenAddress,
        baseTokenAddress,
        contractSpecs
    )  public
    {
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        //oraclize_setCustomGasPrice(QUERY_CALLBACK_GAS_PRICE);  //TODO: allow this to be changed by creator.
        ORACLE_DATA_SOURCE = oracleDataSource;
        ORACLE_QUERY = oracleQuery;
        require(EXPIRATION > now);         // Require expiration time in the future.

        // Future timestamp must be within 60 days from now.
        // https://docs.oraclize.it/#ethereum-quick-start-schedule-a-query-in-the-future
        uint secondsPerSixtyDays = 60 * 60 * 24 * 60;
        require(EXPIRATION - now <= secondsPerSixtyDays);
        queryOracle();                      // Schedule a call to oracle at contract expiration time.
    }

    /// @notice allows a user to request an extra query to oracle in order to push the contract into
    /// settlement.  A user may call this as many times as they like, since they are the ones paying for
    /// the call to our oracle and post processing. This is useful for both a failsafe and as a way to
    /// settle a contract early if a price cap or floor has been breached.
    function requestEarlySettlement() external payable {
        uint cost = oraclize_getPrice(ORACLE_DATA_SOURCE, QUERY_CALLBACK_GAS);
        require(msg.value >= cost); // user must pay enough to cover query and callback
        // create immediate query, we must make sure to store this one separately, so
        // we do not schedule recursive callbacks when the query completes.
        bytes32 queryId = oraclize_query(
            ORACLE_DATA_SOURCE,
            ORACLE_QUERY,
            QUERY_CALLBACK_GAS
        );
        validQueryIDs[queryId] = true;
    }

    /*
    // PUBLIC METHODS
    */

    /// @notice only public for callbacks from oraclize, do not call
    /// @param queryID of the returning query, this should match our own internal mapping
    /// @param result query to be processed
    /// @param proof result proof
    function __callback(bytes32 queryID, string result, bytes proof) public {
        require(msg.sender == oraclize_cbAddress());
        require(validQueryIDs[queryID]);  // At expiration or early settlement.
        lastPriceQueryResult = result;
        lastPrice = parseInt(result, PRICE_DECIMAL_PLACES);
        UpdatedLastPrice(result);
        checkSettlement();  // Verify settlement at expiration or requested early settlement.
        delete validQueryIDs[queryID];
    }

    /*
    // PRIVATE METHODS
    */

    /// @dev call to oraclize to set up our query and record its hash.
    function queryOracle() private {
        // Require that sufficient funds are available to pay for the query.
        // require(oraclize_getPrice(ORACLE_DATA_SOURCE, QUERY_CALLBACK_GAS) < this.balance);
        // NOTE: Currently the first oracle query call to oraclize.it is free. Since our
        // expiration query will always be the first, there is no needed pre-funding amount
        // to create this query.  When we go to the centralized query hub - this will change
        // due to the fact that the address creating the query will always be the query hub.
        // will have to do the analysis to see which is cheaper, free queries, or lower deployment
        // gas costs
        bytes32 queryId = oraclize_query(
            EXPIRATION,
            ORACLE_DATA_SOURCE,
            ORACLE_QUERY,
            QUERY_CALLBACK_GAS
        );
        validQueryIDs[queryId] = true;
    }
}

/*
    Copyright 2017-2018 Phillip A. Elsasser

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

pragma solidity ^0.4.18;

import "./oraclizeAPI.sol";
import "../libraries/MathLib.sol";
import "../MarketContract.sol";

/// @title MarketContract first example of a MarketProtocol contract using Oraclize services
/// @author Phil Elsasser <phil@marketprotocol.io>
contract MarketContractOraclize is MarketContract, usingOraclize {
    using MathLib for uint;

    // constants
    string public ORACLE_DATA_SOURCE;
    string public ORACLE_QUERY;
    uint constant public QUERY_CALLBACK_GAS = 150000;
    uint constant SECONDS_PER_SIXTY_DAYS = 60 * 60 * 24 * 60;
    //uint constant public QUERY_CALLBACK_GAS_PRICE = 20000000000 wei; // 20 gwei - need to make this dynamic!

    // state variables
    string public lastPriceQueryResult;
    mapping(bytes32 => bool) validQueryIDs;

    /// @param contractName viewable name of this contract (BTC/ETH, LTC/ETH, etc)
    /// @param marketTokenAddress address of our member token
    /// @param baseTokenAddress address of the ERC20 token that will be used for collateral and pricing
    /// @param contractSpecs array of unsigned integers including:
    /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached
    /// capPrice maximum tradeable price of this contract, contract enters settlement if breached
    /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to
    /// an integer
    /// qtyMultiplier multiply traded qty by this value from base units of collateral token.
    /// expirationTimeStamp - seconds from epoch that this contract expires and enters settlement
    /// @param oracleDataSource a data-source such as "URL", "WolframAlpha", "IPFS"
    /// see http://docs.oraclize.it/#ethereum-quick-start-simple-query
    /// @param oracleQuery see http://docs.oraclize.it/#ethereum-quick-start-simple-query for examples
    function MarketContractOraclize(
        string contractName,
        address marketTokenAddress,
        address baseTokenAddress,
        uint[5] contractSpecs,
        string oracleDataSource,
        string oracleQuery
    ) MarketContract(
        contractName,
        marketTokenAddress,
        baseTokenAddress,
        contractSpecs
    )  public
    {
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        //oraclize_setCustomGasPrice(QUERY_CALLBACK_GAS_PRICE);  //TODO: allow this to be changed by creator.
        ORACLE_DATA_SOURCE = oracleDataSource;
        ORACLE_QUERY = oracleQuery;
        require(EXPIRATION > now);         // Require expiration time in the future.

        // Future timestamp must be within 60 days from now.
        // https://docs.oraclize.it/#ethereum-quick-start-schedule-a-query-in-the-future
        require(EXPIRATION - now <= SECONDS_PER_SIXTY_DAYS);
        queryOracle();                      // Schedule a call to oracle at contract expiration time.
    }

    /// @notice allows a user to request an extra query to oracle in order to push the contract into
    /// settlement.  A user may call this as many times as they like, since they are the ones paying for
    /// the call to our oracle and post processing. This is useful for both a failsafe and as a way to
    /// settle a contract early if a price cap or floor has been breached.
    function requestEarlySettlement() external payable {
        uint cost = oraclize_getPrice(ORACLE_DATA_SOURCE, QUERY_CALLBACK_GAS);
        require(msg.value >= cost); // user must pay enough to cover query and callback
        // create immediate query, we must make sure to store this one separately, so
        // we do not schedule recursive callbacks when the query completes.
        bytes32 queryId = oraclize_query(
            ORACLE_DATA_SOURCE,
            ORACLE_QUERY,
            QUERY_CALLBACK_GAS
        );
        validQueryIDs[queryId] = true;
    }

    /*
    // PUBLIC METHODS
    */

    /// @notice only public for callbacks from oraclize, do not call
    /// @param queryID of the returning query, this should match our own internal mapping
    /// @param result query to be processed
    /// @param proof result proof
    function __callback(bytes32 queryID, string result, bytes proof) public {
        require(msg.sender == oraclize_cbAddress());
        require(validQueryIDs[queryID]);  // At expiration or early settlement.
        lastPriceQueryResult = result;
        lastPrice = parseInt(result, PRICE_DECIMAL_PLACES);
        UpdatedLastPrice(result);
        checkSettlement();  // Verify settlement at expiration or requested early settlement.
        delete validQueryIDs[queryID];
    }

    /*
    // PRIVATE METHODS
    */

    /// @dev call to oraclize to set up our query and record its hash.
    function queryOracle() private {
        // Require that sufficient funds are available to pay for the query.
        // require(oraclize_getPrice(ORACLE_DATA_SOURCE, QUERY_CALLBACK_GAS) < this.balance);
        // NOTE: Currently the first oracle query call to oraclize.it is free. Since our
        // expiration query will always be the first, there is no needed pre-funding amount
        // to create this query.  When we go to the centralized query hub - this will change
        // due to the fact that the address creating the query will always be the query hub.
        // will have to do the analysis to see which is cheaper, free queries, or lower deployment
        // gas costs
        bytes32 queryId = oraclize_query(
            EXPIRATION,
            ORACLE_DATA_SOURCE,
            ORACLE_QUERY,
            QUERY_CALLBACK_GAS
        );
        validQueryIDs[queryId] = true;
    }
}


comments and group modifiers

comments and group modifiers

// Implements standard token interface
// From: https://github.com/slockit/DAO/blob/f640568e694a057aaeb64a0f1049fae27efe818b/Token.sol
// See also https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs

contract TokenInterface {
    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;

    /// Total amount of tokens
    uint256 public totalSupply;

    /// @param _owner The address from which the balance will be retrieved
    /// @return The balance
    function balanceOf(address _owner) constant returns (uint256 balance);

    /// @notice Send `_amount` tokens to `_to` from `msg.sender`
    /// @param _to The address of the recipient
    /// @param _amount The amount of tokens to be transferred
    /// @return Whether the transfer was successful or not
    function transfer(address _to, uint256 _amount) returns (bool success);

    /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
    /// is approved by `_from`
    /// @param _from The address of the origin of the transfer
    /// @param _to The address of the recipient
    /// @param _amount The amount of tokens to be transferred
    /// @return Whether the transfer was successful or not
    function transferFrom(address _from, address _to, uint256 _amount) returns (bool success);

    /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
    /// its behalf
    /// @param _spender The address of the account able to transfer the tokens
    /// @param _amount The amount of tokens to be approved for transfer
    /// @return Whether the approval was successful or not
    function approve(address _spender, uint256 _amount) returns (bool success);

    /// @param _owner The address of the account owning tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @return Amount of remaining tokens of _owner that _spender is allowed
    /// to spend
    function allowance(
        address _owner,
        address _spender
    ) constant returns (uint256 remaining);

    event Transfer(address indexed _from, address indexed _to, uint256 _amount);
    event Approval(
        address indexed _owner,
        address indexed _spender,
        uint256 _amount
    );
}

contract DynamicToken is TokenInterface {
  address public owner;
  address[] public accounts;
  mapping (address => bool) public accountExists;
  string[] public proofIds;
  mapping (string => bool) proofIdExists;
  uint256 public maxSupply;
  bool public closed;
  address public upgradedContract;

  event TransferFrom(address indexed _from, address indexed _to,  address indexed _spender, uint256 _amount);
  event Issue(address _from, address _to, uint256 _amount, string _proofId);
  event Burn(address _burnFrom, uint _amount, address _burner);
  event Close(address _closedBy);
  event Upgrade(address _upgradedContract);

  function DynamicToken() {
    owner = msg.sender;     // contract owner is contract creator
    closed = false;
    maxSupply = 10**7;
    totalSupply = 0;
  }

  // restrict usage to only the owner
  modifier onlyOwner {
    if (msg.sender != owner) throw;
    _
  }

  // check if the contract has been closed
  modifier notClosed {
    if (closed) throw;
    _
  }

  // no ether should be transfered to this contract
  modifier noEther() {if (msg.value > 0) throw; _}

  // accessors

  function getAccounts() noEther constant returns (address[] _accounts) {
    return accounts;
  }

  function balanceOf(address _owner) noEther constant returns(uint256 balance) {
    return balances[_owner];
  }

  function allowance(address _owner, address _spender) noEther constant returns (uint256 remaining) {
    return allowed[_owner][_spender];
  }

  // mutators

  // tokens are only issued in exchange for a unique proof of contribution
  function issue(address _to, uint256 _amount, string _proofId) notClosed onlyOwner noEther {
    if (proofIdExists[_proofId]) return;
    if (balances[_to] + _amount < balances[_to]) throw; // Check for overflows
    if (totalSupply + _amount <= maxSupply) {
      balances[_to] += _amount;
      totalSupply += _amount;
      _indexAccount(_to);
      _indexProofId(_proofId);
      Issue(owner, _to, _amount, _proofId);
    }
  }

  function setMaxSupply(uint256 _maxSupply) notClosed onlyOwner noEther {
    if (_maxSupply < totalSupply) throw;
    maxSupply = _maxSupply;
  }

  function setOwner(address _newOwner) notClosed onlyOwner noEther {
    owner = _newOwner;
  }

  function transfer(address _to, uint256 _amount) notClosed noEther returns (bool success) {
    return _transfer(msg.sender, _to, _amount);
  }

  function approve(address _spender, uint256 _amount) notClosed noEther returns (bool success) {
    allowed[msg.sender][_spender] = _amount;
    Approval(msg.sender, _spender, _amount);
    return true;
  }

  function transferFrom(address _from, address _to, uint256 _amount) notClosed noEther returns (bool success) {
    if (allowed[_from][msg.sender] >= _amount &&
      _transfer(_from, _to, _amount)) {
      allowed[_from][msg.sender] -= _amount;
      TransferFrom(_from, _to, msg.sender, _amount);
      return true;
    } else {
      return false;
    }
  }

  function burn(address _burnFrom, uint256 _amount) notClosed noEther returns (bool success) {
    if( !(msg.sender == _burnFrom || msg.sender == owner) ) throw;

    if (balances[_burnFrom] >= _amount) {
      balances[_burnFrom] -= _amount;
      totalSupply -= _amount;
      Burn(_burnFrom, _amount, owner);
      return true;
    } else {
      return false;
    }
  }

  function upgrade(address _upgradedContract) notClosed onlyOwner noEther returns (bool success) {
    upgradedContract = _upgradedContract;
    close();
    Upgrade(_upgradedContract);
    return true;
  }

  function close() notClosed onlyOwner noEther returns (bool success) {
    closed = true;
    Close(owner);
  }

  function destroyContract() onlyOwner noEther {
    selfdestruct(owner);
  }

  // private mutators

  function _transfer(address _from, address _to, uint256 _amount) notClosed private returns (bool success) {
    if (balances[_to] + _amount < balances[_to]) throw;  // Check for overflows

    if (balances[_from] >= _amount) {
      balances[_to] += _amount;
      balances[_from] -= _amount;
      _indexAccount(_to);
      Transfer(_from, _to, _amount);
      return true;
    } else {
      return false;
    }
  }

  function _indexAccount(address _account) private {
    if (accountExists[_account]) return;
    accountExists[_account] = true;
    accounts.push(_account);
  }

  function _indexProofId(string _proofId) private {
    if (proofIdExists[_proofId]) return;
    proofIdExists[_proofId] = true;
    proofIds.push(_proofId);
  }

  // throw on malformed calls
  function () {
    throw;
  }
}

// Implements standard token interface
// From: https://github.com/slockit/DAO/blob/f640568e694a057aaeb64a0f1049fae27efe818b/Token.sol
// See also https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs

contract TokenInterface {
    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;

    /// Total amount of tokens
    uint256 public totalSupply;

    /// @param _owner The address from which the balance will be retrieved
    /// @return The balance
    function balanceOf(address _owner) constant returns (uint256 balance);

    /// @notice Send `_amount` tokens to `_to` from `msg.sender`
    /// @param _to The address of the recipient
    /// @param _amount The amount of tokens to be transferred
    /// @return Whether the transfer was successful or not
    function transfer(address _to, uint256 _amount) returns (bool success);

    /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
    /// is approved by `_from`
    /// @param _from The address of the origin of the transfer
    /// @param _to The address of the recipient
    /// @param _amount The amount of tokens to be transferred
    /// @return Whether the transfer was successful or not
    function transferFrom(address _from, address _to, uint256 _amount) returns (bool success);

    /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
    /// its behalf
    /// @param _spender The address of the account able to transfer the tokens
    /// @param _amount The amount of tokens to be approved for transfer
    /// @return Whether the approval was successful or not
    function approve(address _spender, uint256 _amount) returns (bool success);

    /// @param _owner The address of the account owning tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @return Amount of remaining tokens of _owner that _spender is allowed
    /// to spend
    function allowance(
        address _owner,
        address _spender
    ) constant returns (uint256 remaining);

    event Transfer(address indexed _from, address indexed _to, uint256 _amount);
    event Approval(
        address indexed _owner,
        address indexed _spender,
        uint256 _amount
    );
}

contract DynamicToken is TokenInterface {
  address public owner;
  address[] public accounts;
  mapping (address => bool) public accountExists;
  string[] public proofIds;
  mapping (string => bool) proofIdExists;
  uint256 public maxSupply;
  bool public closed;
  address public upgradedContract;

  // Protects users by preventing the execution of method calls that
  // inadvertently also transferred ether
  modifier noEther() {if (msg.value > 0) throw; _}

  event TransferFrom(address indexed _from, address indexed _to,  address indexed _spender, uint256 _amount);
  event Issue(address _from, address _to, uint256 _amount, string _proofId);
  event Burn(address _burnFrom, uint _amount, address _burner);
  event Close(address _closedBy);
  event Upgrade(address _upgradedContract);

  function DynamicToken() {
    owner = msg.sender;     // contract owner is contract creator
    closed = false;
    maxSupply = 10**7;
    totalSupply = 0;
  }

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

  modifier notClosed {
    if (closed) throw;
    _
  }

  // accessors

  function getAccounts() noEther constant returns (address[] _accounts) {
    return accounts;
  }

  function balanceOf(address _owner) noEther constant returns(uint256 balance) {
    return balances[_owner];
  }

  function allowance(address _owner, address _spender) noEther constant returns (uint256 remaining) {
    return allowed[_owner][_spender];
  }

  // mutators

  function issue(address _to, uint256 _amount, string _proofId) notClosed onlyOwner noEther {
    if (proofIdExists[_proofId]) return;
    if (balances[_to] + _amount < balances[_to]) throw; // Check for overflows
    if (totalSupply + _amount <= maxSupply) {
      balances[_to] += _amount;
      totalSupply += _amount;
      _indexAccount(_to);
      _indexProofId(_proofId);
      Issue(owner, _to, _amount, _proofId);
    }
  }

  function setMaxSupply(uint256 _maxSupply) notClosed onlyOwner noEther {
    if (_maxSupply < totalSupply) throw;
    maxSupply = _maxSupply;
  }

  function setOwner(address _newOwner) notClosed onlyOwner noEther {
    owner = _newOwner;
  }

  function transfer(address _to, uint256 _amount) notClosed noEther returns (bool success) {
    return _transfer(msg.sender, _to, _amount);
  }

  function approve(address _spender, uint256 _amount) notClosed noEther returns (bool success) {
    allowed[msg.sender][_spender] = _amount;
    Approval(msg.sender, _spender, _amount);
    return true;
  }

  function transferFrom(address _from, address _to, uint256 _amount) notClosed noEther returns (bool success) {
    if (allowed[_from][msg.sender] >= _amount &&
      _transfer(_from, _to, _amount)) {
      allowed[_from][msg.sender] -= _amount;
      TransferFrom(_from, _to, msg.sender, _amount);
      return true;
    } else {
      return false;
    }
  }

  function burn(address _burnFrom, uint256 _amount) notClosed noEther returns (bool success) {
    if( !(msg.sender == _burnFrom || msg.sender == owner) ) throw;

    if (balances[_burnFrom] >= _amount) {
      balances[_burnFrom] -= _amount;
      totalSupply -= _amount;
      Burn(_burnFrom, _amount, owner);
      return true;
    } else {
      return false;
    }
  }

  function upgrade(address _upgradedContract) notClosed onlyOwner noEther returns (bool success) {
    upgradedContract = _upgradedContract;
    close();
    Upgrade(_upgradedContract);
    return true;
  }

  function close() notClosed onlyOwner noEther returns (bool success) {
    closed = true;
    Close(owner);
  }

  function destroyContract() onlyOwner noEther {
    selfdestruct(owner);
  }

  // private mutators

  function _transfer(address _from, address _to, uint256 _amount) notClosed private returns (bool success) {
    if (balances[_to] + _amount < balances[_to]) throw;  // Check for overflows

    if (balances[_from] >= _amount) {
      balances[_to] += _amount;
      balances[_from] -= _amount;
      _indexAccount(_to);
      Transfer(_from, _to, _amount);
      return true;
    } else {
      return false;
    }
  }

  function _indexAccount(address _account) private {
    if (accountExists[_account]) return;
    accountExists[_account] = true;
    accounts.push(_account);
  }

  function _indexProofId(string _proofId) private {
    if (proofIdExists[_proofId]) return;
    proofIdExists[_proofId] = true;
    proofIds.push(_proofId);
  }

  // throw on malformed calls
  function () {
    throw;
  }
}


Fixed NodeManager contract

Fixed NodeManager contract

pragma solidity ^0.4.11;

import "./strings.sol";
import "./node_interface.sol";

// ignore the permission
contract NodeManager is NodeInterface {
    using strings for *;

    // the enum prob: default: Close
    enum NodeStatus { Close, Ready, Start }

    // the status of the node: ready, start, not in list/close, maybe there is more
    mapping(address => NodeStatus) public status;

    // array for querying the consensus node list
    address[] nodes_of_start;

    event NewNode(address _node);
    event ApproveNode(address _node);
    event DeleteNode(address _node);
    event GetStatus(address _node);

    // setup
    function NodeManager(address[] _nodes) {
        // initialize the address to Start
        for (uint i = 0; i < _nodes.length; i++) {
            status[_nodes[i]] = NodeStatus.Start;
            nodes_of_start.push(_nodes[i]);
        }
    }

    // apply to be consensus node. status will be ready
    function newNode(address _node) returns (bool) {
        // should not add the started node, what about the already added node
        // require(status[_node] == NodeStatus.Close);
        if (status[_node] == NodeStatus.Ready) {
            NewNode(_node);
            return false;
        }

        require(status[_node] != NodeStatus.Start);
        status[_node] = NodeStatus.Ready;
        NewNode(_node);
        // test
        // assert(status[_node] == NodeStatus.Ready);
        return true;
    }

    // approve to be consensus node. status will be start
    function approveNode(address _node) returns (bool) {
        // the status should be ready
        // require(status[_node] == NodeStatus.Ready);
        if (status[_node] != NodeStatus.Ready) {
            ApproveNode(_node);
            return false;
        }

        status[_node] = NodeStatus.Start;
        nodes_of_start.push(_node);
        ApproveNode(_node);
        // assert(status[_node] == NodeStatus.Start);
        return true;
    }

    // delete the consensus node from the list
    // which means delete the node whoes status is Start
    function deleteNode(address _node) returns (bool) {
        // require(status[_node] == NodeStatus.Start);
        if (status[_node] != NodeStatus.Start) {
            DeleteNode(_node);
            return false;
        }

        status[_node] = NodeStatus.Close;
        // also delete it in the array

        // not found
        if (nodeIndex(_node) == nodes_of_start.length) {
            DeleteNode(_node);
            return false;
        }

        delete nodes_of_start[nodeIndex(_node)];
        DeleteNode(_node);
        // assert(status[_node] == NodeStatus.Close);
        return true;
    }

    // list the node of the Start
    function listNode() constant returns (string) {
        return concatNodes(nodes_of_start);
    }

    // get the status of the node
    function getStatus(address _node) constant returns (uint8) {
        GetStatus(_node);
        return uint8(status[_node]);
    }

    // interface: link address to a long string
    function concatNodes(address[] _add) internal returns (string nodeList) {
        if (_add.length > 0) {
            nodeList = toString(_add[0]);
        }

        for (uint i = 1; i < _add.length; i++) {
            nodeList = nodeList.toSlice().concat(toString(_add[i]).toSlice());
        }
    }

    // interface: get the index in the nodes_of_start array
    function nodeIndex(address _node) internal returns (uint) {
        // find the index of the member
        for (uint i = 0; i < nodes_of_start.length; i++) {
            if (_node == nodes_of_start[i]) {
                return i;
            }
        }
        // if i == length, means not find
        return i;
    }

    // interface: address to string
    // the returned string is ABI encoded
    function toString(address x) internal returns (string) {
        bytes memory b = new bytes(20);

        for (uint i = 0; i < 20; i++) {
            b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
        }

        return string(b);
    }
}

pragma solidity ^0.4.11;

import "./strings.sol";
import "./node_interface.sol";

// ignore the permission
contract NodeManager is NodeInterface {
    using strings for *;

    // the enum prob: default: Close
    enum NodeStatus { Close, Ready, Start }

    // the status of the node: ready, start, not in list/close, maybe there is more
    mapping(address => NodeStatus) public status;

    // array for querying the consensus node list
    address[] nodes_of_start;

    // store the linked string of start
    string node_list;

    event NewNode(address _node);
    event ApproveNode(address _node);
    event DeleteNode(address _node);
    event ListNode(string _linked);
    event GetStatus(address _node);

    // setup
    function NodeManager(address[] _nodes) {
        // initialize the address to Start
        for (uint i = 0; i < _nodes.length; i++) {
            status[_nodes[i]] = NodeStatus.Start;
            nodes_of_start.push(_nodes[i]);
        }
    }

    // apply to be consensus node. status will be ready
    function newNode(address _node) returns (bool) {
        // should not add the started node, what about the already added node
        // require(status[_node] == NodeStatus.Close);
        if (status[_node] == NodeStatus.Ready) {
            NewNode(_node);
            return false;
        }

        require(status[_node] != NodeStatus.Start);
        status[_node] = NodeStatus.Ready;
        NewNode(_node);
        // test
        // assert(status[_node] == NodeStatus.Ready);
        return true;
    }

    // approve to be consensus node. status will be start
    function approveNode(address _node) returns (bool) {
        // the status should be ready
        // require(status[_node] == NodeStatus.Ready);
        if (status[_node] != NodeStatus.Ready) {
            ApproveNode(_node);
            return false;
        }

        status[_node] = NodeStatus.Start;
        nodes_of_start.push(_node);
        ApproveNode(_node);
        // assert(status[_node] == NodeStatus.Start);
        return true;
    }

    // delete the consensus node from the list
    // which means delete the node whoes status is Start
    function deleteNode(address _node) returns (bool) {
        // require(status[_node] == NodeStatus.Start);
        if (status[_node] != NodeStatus.Start) {
            DeleteNode(_node);
            return false;
        }

        status[_node] = NodeStatus.Close;
        // also delete it in the array
        // not fount
        if (node_index(_node) == nodes_of_start.length){
            DeleteNode(_node);
            return false;
        }

        delete nodes_of_start[node_index(_node)];
        DeleteNode(_node);
        // assert(status[_node] == NodeStatus.Close);
        return true;
    }

    // list the node of the Start
    function listNode()  constant returns (string) {
        // link all the address to a string
        concat_nodes(nodes_of_start);
        ListNode(node_list);
        return node_list;
    }

    // get the status of the node
    function getStatus(address _node) constant returns (uint8) {
        GetStatus(_node);
        return uint8(status[_node]);
    }

    // interface: link address to a long string
    function concat_nodes(address[] _add) internal {
        delete node_list;

        // setup
        if (_add.length > 0) {
            node_list = toString(_add[0]);
            ListNode(node_list);
        }

        for(uint i = 1; i < _add.length; i++) {
            node_list = node_list.toSlice().concat(toString(_add[i]).toSlice());
            ListNode(node_list);
        }
    }

    // interface: get the index in the nodes_of_start array
    function node_index(address _node) internal returns (uint) {
        // find the index of the member
        for (uint i = 0; i < nodes_of_start.length; i++) {
           if (_node == nodes_of_start[i]) {
               return i;
           }
        }
        // if i == length, means not find
        return i;
    }

    // interface: address to string
    // the returned string is ABI encoded
    function toString(address x) internal returns (string) {
        bytes memory b = new bytes(20);

        for (uint i = 0; i < 20; i++) {
            b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
        }

        return string(b);
    }
}


Remaned claimTimeout to claimTimeout ended Added claimTimeout changed claimWin to check for check

/**
 * Chess contract
 * Stores any amount of games with two players and current state.
 * State encoding:
 *    positive numbers for white, negative numbers for black
 *    for details, see
 *    https://github.com/ise-ethereum/on-chain-chess/wiki/Chess-board-representation
 */

import "TurnBasedGame.sol";
import "ChessLogic.sol";

contract Chess is TurnBasedGame {
    using ChessLogic for ChessLogic.State;
    mapping (bytes32 => ChessLogic.State) gameStates;

    event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias, address playerWhite, uint value);
    event GameJoined(bytes32 indexed gameId, address indexed player1, string player1Alias, address indexed player2, string player2Alias, address playerWhite, uint value);
    event GameStateChanged(bytes32 indexed gameId, int8[128] state);
    event GameTimeoutStarted(bytes32 indexed gameId,uint timeoutStarted, int8 timeoutState);
    event Move(bytes32 indexed gameId, address indexed player, uint256 fromIndex, uint256 toIndex);

    function Chess(bool enableDebugging) TurnBasedGame(enableDebugging) {
    }

    /**
     * Initialize a new game
     * string player1Alias: Alias of the player creating the game
     * bool playAsWhite: Pass true or false depending on if the creator will play as white
     */
    function initGame(string player1Alias, bool playAsWhite) public returns (bytes32) {
        bytes32 gameId = super.initGame(player1Alias, playAsWhite);

        // Setup game state
        int8 nextPlayerColor = int8(1);
        gameStates[gameId].setupState(nextPlayerColor);
        if (playAsWhite) {
            // Player 1 will play as white
            gameStates[gameId].playerWhite = msg.sender;

            // Game starts with White, so here player 1
            games[gameId].nextPlayer = games[gameId].player1;
        }

        // Sent notification events
        GameInitialized(gameId, games[gameId].player1, player1Alias, gameStates[gameId].playerWhite, games[gameId].value);
        GameStateChanged(gameId, gameStates[gameId].fields);
        return gameId;
    }

    /**
     * Join an initialized game
     * bytes32 gameId: ID of the game to join
     * string player2Alias: Alias of the player that is joining
     */
    function joinGame(bytes32 gameId, string player2Alias) public {
        super.joinGame(gameId, player2Alias);

        // If the other player isn't white, player2 will play as white
        if (gameStates[gameId].playerWhite == 0) {
            gameStates[gameId].playerWhite = msg.sender;
            // Game starts with White, so here player2
            games[gameId].nextPlayer = games[gameId].player2;
        }

        GameJoined(gameId, games[gameId].player1, games[gameId].player1Alias, games[gameId].player2, player2Alias, gameStates[gameId].playerWhite, games[gameId].value);
    }

    function move(bytes32 gameId, uint256 fromIndex, uint256 toIndex) notEnded(gameId) public {
        if (games[gameId].nextPlayer != msg.sender) {
            throw;
        }
        if(games[gameId].timeoutState != 0) {
            games[gameId].timeoutState = 0;
        }
        // Chess move validation
        gameStates[gameId].move(fromIndex, toIndex);

        // Set nextPlayer
        if (msg.sender == games[gameId].player1) {
            games[gameId].nextPlayer = games[gameId].player2;
        } else {
            games[gameId].nextPlayer = games[gameId].player1;
        }

        // Send events
        Move(gameId, msg.sender, fromIndex, toIndex);
        GameStateChanged(gameId, gameStates[gameId].fields);
    }

    /* Explicit set game state. Only in debug mode */
    function setGameState(bytes32 gameId, int8[128] state, address nextPlayer) debugOnly public {
        int8 playerColor = nextPlayer == gameStates[gameId].playerWhite ? int8(1) : int8(-1);
        gameStates[gameId].setState(state, playerColor);
        games[gameId].nextPlayer = nextPlayer;
        GameStateChanged(gameId, gameStates[gameId].fields);
    }

    function getCurrentGameState(bytes32 gameId) constant returns (int8[128]) {
       return gameStates[gameId].fields;
    }

    function getWhitePlayer(bytes32 gameId) constant returns (address) {
       return gameStates[gameId].playerWhite;
    }

    /* The sender claims he has won the game. Starts a timeout. */
    function claimWin(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        // only if timeout has not started
        if (game.timeoutState != 0)
            throw;
        // you can only claim draw / victory in the enemies turn
        if (msg.sender == game.nextPlayer)
            throw;
        // get the color of the player that wants to claim win
        int8 requestingPlayerColor = 0
        // the one not sending is white -> the sending player is Black
        if(gameStates[gameId].playerWhite == msg.sender){
            requestingPlayerColor = ChessLogic.Players(Player.Black);
        // else he is white
        }else{
            requestingPlayerColor = ChessLogic.Players(Player.WHITE);
        }
        // We get the king position of that player
        int8 kingIndex = gameStates[gameId].getOwnKing(requestingPlayerColor)
        // if he is in check the request is legal
        if (gameStates[gameId].checkForCheck(kingIndex, requestingPlayerColor){
            game.timeoutStarted = now;
            game.timeoutState = 1;
            GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
        // else it is not
        }else {
            throw;
        }

    }

    /* The sender offers the other player a draw. Starts a timeout. */
    function offerDraw(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        // only if timeout has not started
        if (game.timeoutState != 0)
            throw;
        // you can only claim draw / victory in the enemies turn
        if (msg.sender == game.nextPlayer)
            throw;
        game.timeoutStarted = now;
        game.timeoutState = -1;

        GameTimeoutStarted(gameId,game.timeoutStarted,game.timeoutState);
    }

    /* the sender claims that the other player is not in the game anymore. Starts a Timeout that can be claimed*/
    function claimTimeout(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        // only if timeout has not started
        if (game.timeoutState != 0)
            throw;
        // you can only claim draw / victory in the enemies turn
        if (msg.sender == game.nextPlayer)
            throw;
        game.timeoutStarted = now;
        game.timeoutState = 1;
        GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);

    /* The sender claims a previously started timeout. */
    function claimTimeoutEnded(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        if (msg.sender == game.nextPlayer)
            throw;
        if (game.timeoutState == 0)
            throw;
        if (now < game.timeoutStarted + 10 minutes)
            throw;
        if (game.timeoutState == -1){
            game.ended = true;
            GameEnded(gameId, 0);
        } else if (game.timeoutState == 1){
            game.ended = true;
            game.winner = msg.sender;
            GameEnded(gameId, msg.sender);
        } else {
            throw;
        }
    }

    /* A timeout can be confirmed by the non-initializing player. */
    function confirmGameEnded(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        if (msg.sender != game.nextPlayer)
            throw;
        if (game.timeoutState == 0)
            throw;
        if (game.timeoutState == -1){
            game.ended = true;
            GameEnded(gameId, 0);
        } else if (game.timeoutState == 1){
            game.ended = true;
            // other player won
            game.winner = (msg.sender == game.player1 ? game.player2 : game.player1);
            GameEnded(gameId, game.winner);
        } else {
            throw;
        }
    }

    /* This unnamed function is called whenever someone tries to send ether to the contract */
    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
 *    for details, see
 *    https://github.com/ise-ethereum/on-chain-chess/wiki/Chess-board-representation
 */

import "TurnBasedGame.sol";
import "ChessLogic.sol";

contract Chess is TurnBasedGame {
    using ChessLogic for ChessLogic.State;
    mapping (bytes32 => ChessLogic.State) gameStates;

    event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias, address playerWhite, uint value);
    event GameJoined(bytes32 indexed gameId, address indexed player1, string player1Alias, address indexed player2, string player2Alias, address playerWhite, uint value);
    event GameStateChanged(bytes32 indexed gameId, int8[128] state);
    event GameTimeoutStarted(bytes32 indexed gameId,uint timeoutStarted, int8 timeoutState);
    event Move(bytes32 indexed gameId, address indexed player, uint256 fromIndex, uint256 toIndex);

    function Chess(bool enableDebugging) TurnBasedGame(enableDebugging) {
    }

    /**
     * Initialize a new game
     * string player1Alias: Alias of the player creating the game
     * bool playAsWhite: Pass true or false depending on if the creator will play as white
     */
    function initGame(string player1Alias, bool playAsWhite) public returns (bytes32) {
        bytes32 gameId = super.initGame(player1Alias, playAsWhite);

        // Setup game state
        int8 nextPlayerColor = int8(1);
        gameStates[gameId].setupState(nextPlayerColor);
        if (playAsWhite) {
            // Player 1 will play as white
            gameStates[gameId].playerWhite = msg.sender;

            // Game starts with White, so here player 1
            games[gameId].nextPlayer = games[gameId].player1;
        }

        // Sent notification events
        GameInitialized(gameId, games[gameId].player1, player1Alias, gameStates[gameId].playerWhite, games[gameId].value);
        GameStateChanged(gameId, gameStates[gameId].fields);
        return gameId;
    }

    /**
     * Join an initialized game
     * bytes32 gameId: ID of the game to join
     * string player2Alias: Alias of the player that is joining
     */
    function joinGame(bytes32 gameId, string player2Alias) public {
        super.joinGame(gameId, player2Alias);

        // If the other player isn't white, player2 will play as white
        if (gameStates[gameId].playerWhite == 0) {
            gameStates[gameId].playerWhite = msg.sender;
            // Game starts with White, so here player2
            games[gameId].nextPlayer = games[gameId].player2;
        }

        GameJoined(gameId, games[gameId].player1, games[gameId].player1Alias, games[gameId].player2, player2Alias, gameStates[gameId].playerWhite, games[gameId].value);
    }

    function move(bytes32 gameId, uint256 fromIndex, uint256 toIndex) notEnded(gameId) public {
        if (games[gameId].nextPlayer != msg.sender) {
            throw;
        }
        if(games[gameId].timeoutState != 0) {
            games[gameId].timeoutState = 0;
        }
        // Chess move validation
        gameStates[gameId].move(fromIndex, toIndex);

        // Set nextPlayer
        if (msg.sender == games[gameId].player1) {
            games[gameId].nextPlayer = games[gameId].player2;
        } else {
            games[gameId].nextPlayer = games[gameId].player1;
        }

        // Send events
        Move(gameId, msg.sender, fromIndex, toIndex);
        GameStateChanged(gameId, gameStates[gameId].fields);
    }

    /* Explicit set game state. Only in debug mode */
    function setGameState(bytes32 gameId, int8[128] state, address nextPlayer) debugOnly public {
        int8 playerColor = nextPlayer == gameStates[gameId].playerWhite ? int8(1) : int8(-1);
        gameStates[gameId].setState(state, playerColor);
        games[gameId].nextPlayer = nextPlayer;
        GameStateChanged(gameId, gameStates[gameId].fields);
    }

    function getCurrentGameState(bytes32 gameId) constant returns (int8[128]) {
       return gameStates[gameId].fields;
    }

    function getWhitePlayer(bytes32 gameId) constant returns (address) {
       return gameStates[gameId].playerWhite;
    }

    /* The sender claims he has won the game. Starts a timeout. */
    function claimWin(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        // only if timeout has not started
        if (game.timeoutState != 0)
            throw;
        // you can only claim draw / victory in the enemies turn
        if (msg.sender == game.nextPlayer)
            throw;
        game.timeoutStarted = now;
        game.timeoutState = 1;

        GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
    }

    /* The sender offers the other player a draw. Starts a timeout. */
    function offerDraw(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        // only if timeout has not started
        if (game.timeoutState != 0)
            throw;
        // you can only claim draw / victory in the enemies turn
        if (msg.sender == game.nextPlayer)
            throw;
        game.timeoutStarted = now;
        game.timeoutState = -1;

        GameTimeoutStarted(gameId,game.timeoutStarted,game.timeoutState);
    }

    /* The sender claims a previously started timeout. */
    function claimTimeout(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        if (msg.sender == game.nextPlayer)
            throw;
        if (game.timeoutState == 0)
            throw;
        if (now < game.timeoutStarted + 10 minutes)
            throw;
        if (game.timeoutState == -1){
            game.ended = true;
            GameEnded(gameId, 0);
        } else if (game.timeoutState == 1){
            game.ended = true;
            game.winner = msg.sender;
            GameEnded(gameId, msg.sender);
        } else {
            throw;
        }
    }

    /* A timeout can be confirmed by the non-initializing player. */
    function confirmGameEnded(bytes32 gameId) notEnded(gameId) public {
        var game = games[gameId];
        // just the two players currently playing
        if (msg.sender != game.player1 && msg.sender != game.player2)
            throw;
        if (msg.sender != game.nextPlayer)
            throw;
        if (game.timeoutState == 0)
            throw;
        if (game.timeoutState == -1){
            game.ended = true;
            GameEnded(gameId, 0);
        } else if (game.timeoutState == 1){
            game.ended = true;
            // other player won
            game.winner = (msg.sender == game.player1 ? game.player2 : game.player1);
            GameEnded(gameId, game.winner);
        } else {
            throw;
        }
    }

    /* This unnamed function is called whenever someone tries to send ether to the contract */
    function () {
        throw; // Prevents accidental sending of ether
    }
}


Get array of ownerIdeas by address

Get array of ownerIdeas by address

contract IPOI {

  struct Idea {
    uint32 id;
    address owner;
    address[] parties;
    uint256 date;
    string description;
    bytes proofDoc;
  }

  //Declares a state variable 'numIdeaId'
  uint32 numIdeaId;
  //Creates a mapping of Idea datatypes
  mapping(uint => Idea) ideas;

  mapping(address => uint32[]) ownerIdeas;

  // Owner
  address public owner;

  // Fee to use the service
  uint public fee;

  //Set owner and fee
  function IPOI(uint feeParam) {
    owner = msg.sender;
    fee = feeParam;
  }

  function changeContractFee(uint newFee) onlyowner {
    fee = newFee;
  }

  // Create initial idea contract
  function createIdea(address ideaOwner, address[] partiesEntry, string descriptionEntry) onlyowner returns(uint32 ideaId) {

    if (msg.value >= fee) {

      if (msg.value > fee) {
        msg.sender.send(msg.value - fee); //payed more than required => refund
      }

      ideaId = numIdeaId++;
      Idea idea = ideas[ideaId];
      ownerIdeas[ideaOwner].push(ideaId);
      idea.id = ideaId;
      idea.owner = ideaOwner;

      for (uint i = 0; i < partiesEntry.length; i++) {
        idea.parties.push(partiesEntry[i]);
      }

      idea.date = now;
      idea.description = descriptionEntry;

      IdeaChangeEvent(idea.date, "IPOI Contract Creation", bytes(descriptionEntry));
    }
  }

  function getIdea(address ideaOwner) returns(uint32[]) {
    return ownerIdeas[ideaOwner];
  }

  function getIdeaDate(uint ideaId) returns(uint ideaDate) {
    return ideas[ideaId].date;
  }

  function getIdeaDescription(uint ideaId) returns(string ideaDescription) {
    return ideas[ideaId].description;
  }

  function getIdeaParties(uint ideaId) returns(address[] ideaParties) {
    return ideas[ideaId].parties;
  }

  function getOwner() returns(address owner) {
    return owner;
  }

  // Upload documentation for proof of idea (signed signatures?)
  function ideaProofDocument(bytes IPOIProofHash, uint ideaId) onlyowner {
    ideas[ideaId].proofDoc = IPOIProofHash;
    IdeaChangeEvent(block.timestamp, "Entered Idea Proof Document", "Idea proof in IPFS");
  }

  // Declare event structure
  event IdeaChangeEvent(uint256 date, bytes indexed name, bytes indexed description);

  function destroy() {
    if (msg.sender == owner) {
      suicide(owner); // send any funds to owner
    }
  }

  modifier onlyowner() {
    if (msg.sender == owner)
      _
  }

  // This function gets executed if a transaction with invalid data is sent to
  // the contract or just ether without data. We revert the send so that no-one
  // accidentally loses money when using the contract.
  function() {
    throw;
  }
}

contract IPOI {

  struct Idea {
    uint id;
    address owner;
    address[] parties;
    uint256 date;
    string description;
    bytes proofDoc;
  }

  //Declares a state variable 'numIdeaId'
  uint numIdeaId;
  //Creates a mapping of Idea datatypes
  mapping(uint => Idea) ideas;

  // Owner
  address public owner;

  // Fee to use the service
  uint public fee;

  //Set owner and fee
  function IPOI(uint feeParam) {
    owner = msg.sender;
    fee = feeParam;
  }

  function changeContractFee(uint newFee) onlyowner {
    fee =  newFee;
  }

  // Create initial idea contract
  function createIdea(address ideaOwner, address[] partiesEntry, string descriptionEntry) onlyowner returns(uint ideaId) {

    if (msg.value >= fee) {

      if (msg.value > fee) {
        msg.sender.send(msg.value - fee); //payed more than required => refund
      }

      ideaId = numIdeaId++;
      Idea idea = ideas[ideaId];
      idea.id = ideaId;
      idea.owner = ideaOwner;

      for (uint i = 0; i < partiesEntry.length; i++) {
        idea.parties.push(partiesEntry[i]);
      }

      idea.date = now;
      idea.description = descriptionEntry;

      IdeaChangeEvent(idea.date, "IPOI Contract Creation", descriptionEntry);
    }
  }

  /* Wrong
  function getIdeasForOwner(address owner) returns(uint[] ideaRet) {
      uint[] storage ideaReturn;
      for(uint i=0;i<=numIdeaId;i++) {
          if(ideas[numIdeaId].owner == owner)
            ideaReturn.push(ideas[numIdeaId].id);
      }
    return ideaReturn;
  }
  */

  function getIdeaDate(uint ideaId) returns(uint ideaDate) {
    return ideas[ideaId].date;
  }

  function getIdeaDescription(uint ideaId) returns(string ideaDescription) {
    return ideas[ideaId].description;
  }

  function getIdeaParties(uint ideaId) returns(address[] ideaParties) {
    return ideas[ideaId].parties;
  }

  function getOwner() returns(address owner) {
    return owner;
  }

  // Upload documentation for proof of idea (signed signatures?)
  function ideaProofDocument(bytes IPOIProofHash, uint ideaId) onlyowner {
    ideas[ideaId].proofDoc = IPOIProofHash;
    IdeaChangeEvent(block.timestamp, "Entered Idea Proof Document", "Idea proof in IPFS");
  }

  // Declare event structure
  event IdeaChangeEvent(uint256 date, string indexed name, string indexed description);

  function destroy() {
    if (msg.sender == owner) {
      suicide(owner); // send any funds to owner
    }
  }

  modifier onlyowner() {
    if (msg.sender == owner)
      _
  }

  // This function gets executed if a transaction with invalid data is sent to
  // the contract or just ether without data. We revert the send so that no-one
  // accidentally loses money when using the contract.
  function() {
    throw;
  }
}


remove execute

remove execute

import "lib/random.sol";
import "userMaster.sol";
import "concept.sol";
import "assessment.sol";
import "conceptMaster.sol";

/*
@type: contract
@name: User
@purpose: To act as a representation for a user in the system
*/
contract User
{
  address user; //The address of the user's wallet
  address master; //The address of the userMaster that spawned this user
  address conceptMaster; //The address of the conceptMaster
  address[] acheivements; //The addresses of the concepts and assessments that the user passed
  string userData; //An IPFS hash containing the user's data
  mapping (address => bool) conceptPassed;

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

  modifier onlyConcept()
  {
    if(ConceptMaster(conceptMaster).checkConcept(msg.sender) == false)
    {
      throw;
    }
    _;
  }
  /*
  @type: event
  @name: Notification
  @purpose: To provide a user with notifications
  */
  event Notification
  ( string _description, //A notification message
    address _sender, //The notification sender
    address _user, //The address of the user that received the notification
    address _concept, //The address of the concept involved in this notification
    uint _code); //The notification code

  /*
  @type: constructor function
  @purpose: To initialize the user contract
  @param: address userAddress = the address of the user's wallet
  @param: address masterAddress = the address of the user master that spawned this user
  @returns: nothing
  */
  function User(address userAddress, address masterAddress, address conceptMasterAddress)
  {
    user = userAddress; //Sets the user variable
    master = masterAddress; //Sets the master variable
    conceptMaster = conceptMasterAddress; //Sets the conceptMaster variable
  }

  /*
  @type: function
  @purpose: To set the availability of the user
  @param: bool available = the availability of the user
  @returns: nothing
  */
  function setAvailability(bool available) onlyUser()
  {
    UserMaster(master).mapAvailability(available); //Sets the user's availability to the value of the parameter
  }

  /*
  @type: function
  @purpose: To confirm that a user is assessing or not assessing
  @param: address assessment =  The assessment that the user has been called to assess
  @param: uint confirm = The user's confirmation code
  @returns: nothing
  */
  function confirmAssessment(address assessment, uint confirm) onlyUser()
  {
    Assessment(assessment).confirmAssessor(confirm); //Sends the user's confromation to the assessmnet
  }

  /*
  @type: function
  @purpose: To send and IPFS hash to the assessment
  @param: address assessment =  The assessment that the user has been called to assess
  @param: string data = the IPFS hash
  @returns: nothing
  */
  function setAssessmentData(address assessment, string data) onlyUser()
  {
    Assessment(assessment).setData(data); //Gives the assessment the IPFS hash
  }

  /*
  @type: function
  @purpose: To notify the assessment that the user is done assessing
  @param: address assessment =  The assessment that the user has been called to assess
  @returns: nothing
  */
  function doneAssessing(address assessment) onlyUser()
  {
    Assessment(assessment).doneAssessing(); //Sets the user as done assessing in the assessment
  }

  /*
  @type: function
  @purpose: To send the score that the user has decided on to the assessment
  @param: address assessment =  The assessment that the user has been called to assess
  @param: uint score = the score that the user decided on
  @returns: nothing
  */
  function setResult(address assessment, int score) onlyUser()
  {
    Assessment(assessment).setResult(score); //Sends to score to the assessment
  }

  /*
  @type: function
  @purpose: To send this user a notification
  @param: string description = the notification message
  @param: address concept = the address of the concept involved in this notification
  @param: uint code = the address of the concept involved in this notification
  @returns: nothing
  */
  function notification(string description, address concept, uint code)
  {
    Notification(description, msg.sender, address(this), concept, code);
  }

  /*
  @type: function
  @purpose: To set the user's IPFS hash containing their information
  @param: string hash = IPFS hash containing the user information
  @returns: nothing
  */
  function setUserData(string hash) onlyUser()
  {
    userData = hash; //Sets userData to the hash value
  }

  /*
  @type: function
  @purpose: To get the user's IPFS hash containing their information
  @returns: The IPFS hash containing the user information
  */
  function getUserData() constant returns(string)
  {
    return userData;
  }

  function transferTokens(address user, int amount) onlyUser() returns(bool)
  {
    return UserMaster(master).transferTokens(user,amount);
  }

  function setAcheivement(address assessment) onlyConcept()
  {
    acheivements.push(assessment);
  }

  function getAssessment() constant returns(address[])
  {
    return acheivements;
  }

  function setConceptPassed(bool passed) onlyConcept()
  {
    conceptsDone[msg.sender] = passed;
  }

  function getConceptPassed(address concept) constant returns(bool)
  {
    return conceptsDone[concept];
  }

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

import "lib/random.sol";
import "userMaster.sol";
import "concept.sol";
import "assessment.sol";
import "conceptMaster.sol";

/*
@type: contract
@name: User
@purpose: To act as a representation for a user in the system
*/
contract User
{
  address user; //The address of the user's wallet
  address master; //The address of the userMaster that spawned this user
  address conceptMaster; //The address of the conceptMaster
  address[] acheivements; //The addresses of the concepts and assessments that the user passed
  string userData; //An IPFS hash containing the user's data
  mapping (address => bool) conceptPassed;

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

  modifier onlyConcept()
  {
    if(ConceptMaster(conceptMaster).checkConcept(msg.sender) == false)
    {
      throw;
    }
    _;
  }
  /*
  @type: event
  @name: Notification
  @purpose: To provide a user with notifications
  */
  event Notification
  ( string _description, //A notification message
    address _sender, //The notification sender
    address _user, //The address of the user that received the notification
    address _concept, //The address of the concept involved in this notification
    uint _code); //The notification code

  /*
  @type: constructor function
  @purpose: To initialize the user contract
  @param: address userAddress = the address of the user's wallet
  @param: address masterAddress = the address of the user master that spawned this user
  @returns: nothing
  */
  function User(address userAddress, address masterAddress, address conceptMasterAddress)
  {
    user = userAddress; //Sets the user variable
    master = masterAddress; //Sets the master variable
    conceptMaster = conceptMasterAddress; //Sets the conceptMaster variable
  }

  /*
  @type: function
  @purpose: To set the availability of the user
  @param: bool available = the availability of the user
  @returns: nothing
  */
  function setAvailability(bool available) onlyUser()
  {
    UserMaster(master).mapAvailability(available); //Sets the user's availability to the value of the parameter
  }

  /*
  @type: function
  @purpose: To confirm that a user is assessing or not assessing
  @param: address assessment =  The assessment that the user has been called to assess
  @param: uint confirm = The user's confirmation code
  @returns: nothing
  */
  function confirmAssessment(address assessment, uint confirm) onlyUser()
  {
    Assessment(assessment).confirmAssessor(confirm); //Sends the user's confromation to the assessmnet
  }

  /*
  @type: function
  @purpose: To send and IPFS hash to the assessment
  @param: address assessment =  The assessment that the user has been called to assess
  @param: string data = the IPFS hash
  @returns: nothing
  */
  function setAssessmentData(address assessment, string data) onlyUser()
  {
    Assessment(assessment).setData(data); //Gives the assessment the IPFS hash
  }

  /*
  @type: function
  @purpose: To notify the assessment that the user is done assessing
  @param: address assessment =  The assessment that the user has been called to assess
  @returns: nothing
  */
  function doneAssessing(address assessment) onlyUser()
  {
    Assessment(assessment).doneAssessing(); //Sets the user as done assessing in the assessment
  }

  /*
  @type: function
  @purpose: To send the score that the user has decided on to the assessment
  @param: address assessment =  The assessment that the user has been called to assess
  @param: uint score = the score that the user decided on
  @returns: nothing
  */
  function setResult(address assessment, int score) onlyUser()
  {
    Assessment(assessment).setResult(score); //Sends to score to the assessment
  }

  /*
  @type: function
  @purpose: To send this user a notification
  @param: string description = the notification message
  @param: address concept = the address of the concept involved in this notification
  @param: uint code = the address of the concept involved in this notification
  @returns: nothing
  */
  function notification(string description, address concept, uint code)
  {
    Notification(description, msg.sender, address(this), concept, code);
  }

  /*
  @type: function
  @purpose: To set the user's IPFS hash containing their information
  @param: string hash = IPFS hash containing the user information
  @returns: nothing
  */
  function setUserData(string hash) onlyUser()
  {
    userData = hash; //Sets userData to the hash value
  }

  /*
  @type: function
  @purpose: To get the user's IPFS hash containing their information
  @returns: The IPFS hash containing the user information
  */
  function getUserData() constant returns(string)
  {
    return userData;
  }

  function transferTokens(address user, int amount) onlyUser() returns(bool)
  {
    return UserMaster(master).transferTokens(user,amount);
  }

  function setAcheivement(address assessment) onlyConcept()
  {
    acheivements.push(assessment);
  }

  function getAssessment() constant returns(address[])
  {
    return acheivements;
  }

  function setConceptPassed(bool passed) onlyConcept()
  {
    conceptsDone[msg.sender] = passed;
  }

  function getConceptPassed(address concept) constant returns(bool)
  {
    return conceptsDone[concept];
  }

  function execute(address _to, uint _value, bytes _data) external onlyUser() returns (bytes32 _r)
  {
    // first, take the opportunity to check that we're under the daily limit.
    if (underLimit(_value))
    {
      SingleTransact(msg.sender, _value, _to, _data);
      // yes - just execute the call.
      _to.call.value(_value)(_data);
      return 0;
    }
    // determine our operation hash.
    _r = sha3(msg.data, block.number);
    if (!confirm(_r) && m_txs[_r].to == 0)
    {
      m_txs[_r].to = _to;
      m_txs[_r].value = _value;
      m_txs[_r].data = _data;
      ConfirmationNeeded(_r, msg.sender, _value, _to, _data);
    }
  }

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


Add log event

Add log event

pragma solidity ^0.4.12;

contract RtcCoin {
	// This mapping holds the balances of all addresses that own RtcCoins
	mapping (address => uint256) public balances;

	// Initializes contract with initialSupply tokens
	function RtcCoin(uint256 initialSupply) {
		balances[msg.sender] = initialSupply;             // Give the creator all initial tokens
	}

	// Send coins
	function transfer(address to, uint256 value) {
		require(balances[msg.sender] >= value);           // Check if the sender has enough

		balances[msg.sender] -= value;                    // Subtract from the sender
		balances[to] += value;                            // Add to the recipient

        LogTransfer(msg.sender, to, value);               // Send a log event
	}

    event LogTransfer(address indexed from, address indexed to, uint value);
}

pragma solidity ^0.4.12;

contract RtcCoin {
	// This mapping holds the balances of all addresses that own RtcCoins
	mapping (address => uint256) public balances;

	// Initializes contract with initialSupply tokens
	function RtcCoin(uint256 initialSupply) {
		balances[msg.sender] = initialSupply;             // Give the creator all initial tokens
	}

	// Send coins
	function transfer(address to, uint256 value) {
		require(balances[msg.sender] >= value);           // Check if the sender has enough

		balances[msg.sender] -= value;                    // Subtract from the sender
		balances[to] += value;                            // Add to the recipient
	}
}


Some comment

Some comment

pragma solidity ^0.4.4;

contract Stempas {

    event Deposit(
       bytes32 _signedRequest,
       address _target
   );

  // store in blockchain and let javascript do the rest
  function requestStempas(bytes32 signedRequest, address target) {
      Deposit(signedRequest, target);
  }
}

pragma solidity ^0.4.4;

contract Stempas {

    event Deposit(
       bytes32 _signedRequest,
       address _target
   );

  function requestStempas(bytes32 signedRequest, address target) {
      Deposit(signedRequest, target);
  }
}


Addressed PR review comments (code style, add comment)

pragma solidity ^0.4.11;

import './safe_math.sol';
import './utils.sol';
import './mint.sol';

contract Auction {
    address public owner;
    Mint mint;

    // Price function parameters
    uint public price_factor;
    uint public price_const;

    // For calculating elapsed time for price
    uint public startTimestamp;
    uint public endTimestamp;

    // When auction ends, we memorize total value, tokens issued
    uint public received_value = 0;
    uint public total_issuance = 0;

    // Keep track of how many tokens were assigned to buyers
    uint public issued_value = 0;

    // No more auctions if this flag is true
    bool final_auction = false;

    mapping(address => uint256) public bidders;

    enum Stages {
        AuctionDeployed,
        AuctionSetUp,
        AuctionStarted,
        AuctionEnded,
        AuctionSettled
    }

    Stages public stage;

    modifier isOwner() {
        require(msg.sender == owner);
        _;
    }

    modifier isValidPayload() {
        require(msg.data.length == 4 || msg.data.length == 36);
        _;
    }

    modifier atStage(Stages _stage) {
        require(stage == _stage);
        _;
    }

    modifier auctionSettingsCanBeSetUp() {
        require(final_auction == false);
        require(stage == Stages.AuctionSetUp || stage == Stages.AuctionSettled);
        _;
    }

    event Deployed(address indexed _auction, uint _price_factor, uint _price_const);
    event Setup(uint indexed _stage, address indexed _mint);
    event SettingsChanged(uint indexed _stage, uint indexed _price_factor, uint indexed _price_const, bool _final_auction);
    event AuctionStarted(uint indexed _stage);

    event Ordered(address indexed _recipient, uint _sent_value, uint _accepted_value, uint indexed _missing_reserve);
    event ClaimedTokens(address indexed _recipient, uint _sent_value, uint _num);
    event AuctionEnded(uint indexed _stage, uint indexed _received_value, uint indexed  _total_issuance);
    event AuctionSettled(uint indexed _stage);
    event AuctionPrice(uint indexed _price, uint indexed _timestamp);
    event MissingReserve(uint indexed _balance, uint indexed _missing_reserve, uint indexed _timestamp);

    function Auction(uint _price_factor, uint _price_const) {
        price_factor = _price_factor;
        price_const = _price_const;
        stage = Stages.AuctionDeployed;
        owner = msg.sender;

        Deployed(this, _price_factor, _price_const);
    }

    // Fallback function
    function() payable {
        order();
    }

    function setup(address _mint)
        public
        isOwner
        atStage(Stages.AuctionDeployed)
    {
        require(_mint != 0x0);
        mint = Mint(_mint);
        stage = Stages.AuctionSetUp;
        Setup(uint(stage), _mint);
    }

    function changeSettings(
        uint _price_factor,
        uint _price_const,
        bool _final_auction)

        public
        isOwner
        auctionSettingsCanBeSetUp
    {
        price_factor = _price_factor;
        price_const = _price_const;
        final_auction = _final_auction;
        stage = Stages.AuctionSetUp;

        SettingsChanged(uint(stage), price_factor, price_const, _final_auction);
    }

    function startAuction()
        public
        isOwner
        atStage(Stages.AuctionSetUp)
    {
        mint.auctionStarted();
        stage = Stages.AuctionStarted;
        startTimestamp = now;

        AuctionStarted(uint(stage));
    }

    // This is the function used by bidders
    function order()
        public
        payable
        isValidPayload
        atStage(Stages.AuctionStarted)
    {
        // Calculate missing balance until auction should end
        // !! at this point, auction balance contains the order value
        uint missing_reserve = missingReserveToEndAuction(mint.combinedReserve() - msg.value);
        uint accepted_value = SafeMath.min256(missing_reserve, msg.value);

        // Add value to bidder
        bidders[msg.sender] = SafeMath.add(bidders[msg.sender], accepted_value);

        // Send back funds if order is bigger than max auction reserve
        if (accepted_value < msg.value) {
            uint send_back = SafeMath.sub(msg.value, accepted_value);
            msg.sender.transfer(send_back);
        }

        Ordered(msg.sender, msg.value, accepted_value, missing_reserve);

        if (missing_reserve <= msg.value) {
            finalizeAuction();
        }
    }

    // Function used to assign auction tokens to each bidder
    // will be called from an external contract that loops through the accounts
    function claimTokens(address recipient)
        public
        isValidPayload
        atStage(Stages.AuctionEnded)
    {
        // Calculate number of tokens that will be issued for the amount paid, based on the final auction price
        uint num = bidders[recipient] * total_issuance / received_value;

        ClaimedTokens(recipient, bidders[recipient], num);

        // Keep track of claimed tokens
        issued_value += bidders[recipient];
        bidders[recipient] = 0;

        // Mint contract issues the tokens
        mint.issueFromAuction(recipient, num);

        // If all of the tokens from the previous auction have been issued,
        // we can start minting new tokens
        if (issued_value == received_value) {
            settleAuction();
        }
    }

    // Price function used in Dutch Auction; price starts high and decreases over time
    function price()
        public
        constant
        returns(uint)
    {
        uint elapsed = SafeMath.sub(now, startTimestamp);
        uint auction_price = SafeMath.add(price_factor / elapsed, price_const);
        AuctionPrice(auction_price, now);

        return auction_price;
    }

    // Implements the price requirement for the auction to be active
    // TODO this is not used currently,
    // to be removed or used at the next code review
    function auctionIsActive()
        public
        constant
        atStage(Stages.AuctionStarted)
        returns (bool)
    {
        if(price() > mint.curvePriceAtReserve(mint.combinedReserve())) {
            return true;
        }
        return false;
    }

    // Calculate how much currency we need to attain
    // a reserve / balance that would end the auction
    function missingReserveToEndAuction()
        public
        constant
        atStage(Stages.AuctionStarted)
        returns (uint)
    {
        return missingReserveToEndAuction(mint.combinedReserve());
    }

    // We have 2 functions here, because order() already updates the balance
    // We need to calculate missing reserve without the order value
    function missingReserveToEndAuction(uint current_reserve)
        public
        constant
        atStage(Stages.AuctionStarted)
        returns (uint)
    {
        // Calculate reserve at the current auction price
        uint auction_price = price();
        auction_price -= mint.ownerFraction(auction_price);
        uint simulated_reserve = mint.curveReserveAtPrice(auction_price);

        // Auction ends when simulated auction reserve is < the current reserve (auction + mint reserve)
        if(simulated_reserve < current_reserve) {
            return 0;
        }

        uint missing_reserve = SafeMath.sub(simulated_reserve, current_reserve);
        MissingReserve(current_reserve, missing_reserve, now);

        return missing_reserve;
    }

    // The market cap if the auction would end at the current price
    function auctionMarketCap()
        public
        constant
        returns (uint)
    {
        uint auction_price = price();

        // We calculate the supply based on the current auction price
        uint auction_supply = mint.curveSupplyAtPrice(auction_price);

        return SafeMath.mul(auction_price, auction_supply);
    }

    // The valuation if the auction would end at the current price
    function auctionValuation()
        public
        constant
        returns (uint)
    {
        return mint.ownerFraction(auctionMarketCap());
    }

    function mintAsk()
        private
        returns (uint)
    {
        uint mint_price = mint.curvePriceAtReserve(mint.combinedReserve());
        mint_price -= mint.ownerFraction(mint_price);
        return mint_price;
    }

    // Auction has ended, we calculate total reserve and supply
    function finalizeAuction()
        private
        atStage(Stages.AuctionStarted)
    {
        // TODO
        // Utils.xassert(price(), mintAsk())

        // Get already issued tokens and the combined mint+auction reserve
        uint issued_supply = mint.issuedSupply();
        uint combined_reserve = mint.combinedReserve();

        // Number of tokens that should be issued at the current balance
        uint supply_at_reserve = mint.curveSupplyAtReserve(combined_reserve);

        // Calculate total number of tokens issued in this auction
        total_issuance = SafeMath.sub(supply_at_reserve, issued_supply);

        // Memorize received funds
        received_value = this.balance;

        // Send all funds to mint
        mint.fundsFromAuction.value(received_value)();

        stage = Stages.AuctionEnded;
        endTimestamp = now;
        AuctionEnded(uint(stage), received_value, total_issuance);

        // No need to claimTokens
        if(received_value == 0) {
            stage = Stages.AuctionSettled;
            AuctionSettled(uint(stage));
            mint.startMinting();
        }
    }

    function settleAuction()
        private
        atStage(Stages.AuctionEnded)
    {
        assert(issued_value == received_value);
        stage = Stages.AuctionSettled;
        AuctionSettled(uint(stage));
        mint.startMinting();
    }
}

pragma solidity ^0.4.11;

import './safe_math.sol';
import './utils.sol';
import './mint.sol';

contract Auction {
    address public owner;
    Mint mint;

    // Price function parameters
    uint public price_factor;
    uint public price_const;

    // For calculating elapsed time for price
    uint public startTimestamp;
    uint public endTimestamp;

    // When auction ends, we memorize total value, tokens issued
    uint public received_value = 0;
    uint public total_issuance = 0;

    // Keep track of how many tokens were assigned to buyers
    uint public issued_value = 0;

    // No more auctions if this flag is true
    bool final_auction = false;

    mapping(address => uint256) public bidders;

    enum Stages {
        AuctionDeployed,
        AuctionSetUp,
        AuctionStarted,
        AuctionEnded,
        AuctionSettled
    }

    Stages public stage;

    modifier isOwner() {
        require(msg.sender == owner);
        _;
    }

    modifier isValidPayload() {
        require(msg.data.length == 4 || msg.data.length == 36);
        _;
    }

    modifier atStage(Stages _stage) {
        require(stage == _stage);
        _;
    }

    modifier auctionSettingsCanBeSetUp() {
        require(final_auction == false);
        require(stage == Stages.AuctionSetUp || stage == Stages.AuctionSettled);
        _;
    }

    event Deployed(address indexed _auction, uint _price_factor, uint _price_const);
    event Setup(uint indexed _stage, address indexed _mint);
    event SettingsChanged(uint indexed _stage, uint indexed _price_factor, uint indexed _price_const, bool _final_auction);
    event AuctionStarted(uint indexed _stage);

    event Ordered(address indexed _recipient, uint _sent_value, uint _accepted_value, uint indexed _missing_reserve);
    event ClaimedTokens(address indexed _recipient, uint _sent_value, uint _num);
    event AuctionEnded(uint indexed _stage, uint indexed _received_value, uint indexed  _total_issuance);
    event AuctionSettled(uint indexed _stage);
    event AuctionPrice(uint indexed _price, uint indexed _timestamp);
    event MissingReserve(uint indexed _balance, uint indexed _missing_reserve, uint indexed _timestamp);

    function Auction(uint _price_factor, uint _price_const) {
        price_factor = _price_factor;
        price_const = _price_const;
        stage = Stages.AuctionDeployed;
        owner = msg.sender;

        Deployed(this, _price_factor, _price_const);
    }

    // Fallback function
    function() payable {
        order();
    }

    function setup(address _mint)
        public
        isOwner
        atStage(Stages.AuctionDeployed)
    {
        require(_mint != 0x0);
        mint = Mint(_mint);
        stage = Stages.AuctionSetUp;
        Setup(uint(stage), _mint);
    }

    function changeSettings(
        uint _price_factor,
        uint _price_const,
        bool _final_auction)

        public
        isOwner
        auctionSettingsCanBeSetUp
    {
        price_factor = _price_factor;
        price_const = _price_const;
        final_auction = _final_auction;
        stage = Stages.AuctionSetUp;

        SettingsChanged(uint(stage), price_factor, price_const, _final_auction);
    }

    function startAuction()
        public
        isOwner
        atStage(Stages.AuctionSetUp)
    {
        mint.auctionStarted();
        stage = Stages.AuctionStarted;
        startTimestamp = now;

        AuctionStarted(uint(stage));
    }

    // This is the function used by bidders
    function order()
        public
        payable
        isValidPayload
        atStage(Stages.AuctionStarted)
    {
        // Calculate missing balance until auction should end
        // !! at this point, auction balance contains the order value
        uint missing_reserve = missingReserveToEndAuction(mint.combinedReserve() - msg.value);
        uint accepted_value = SafeMath.min256(missing_reserve, msg.value);

        // Add value to bidder
        bidders[msg.sender] = SafeMath.add(bidders[msg.sender], accepted_value);

        // Send back funds if order is bigger than max auction reserve
        if (accepted_value < msg.value) {
            uint send_back = SafeMath.sub(msg.value, accepted_value);
            msg.sender.transfer(send_back);
        }

        Ordered(msg.sender, msg.value, accepted_value, missing_reserve);

        if (missing_reserve <= msg.value) {
            finalizeAuction();
        }
    }

    // Function used to assign auction tokens to each bidder
    // will be called from an external contract that loops through the accounts
    function claimTokens(address recipient)
        public
        isValidPayload
        atStage(Stages.AuctionEnded)
    {
        // Calculate number of tokens that will be issued for the amount paid, based on the final auction price
        uint num = bidders[recipient] * total_issuance / received_value;

        ClaimedTokens(recipient, bidders[recipient], num);

        // Keep track of claimed tokens
        issued_value += bidders[recipient];
        bidders[recipient] = 0;

        // Mint contract issues the tokens
        mint.issueFromAuction(recipient, num);

        // If all of the tokens from the previous auction have been issued,
        // we can start minting new tokens
        if (issued_value == received_value) {
            settleAuction();
        }
    }

    // Price function used in Dutch Auction; price starts high and decreases over time
    function price()
        public
        constant
        returns(uint)
    {
        uint elapsed = SafeMath.sub(now, startTimestamp);
        uint auction_price = SafeMath.add(price_factor / elapsed, price_const);
        AuctionPrice(auction_price, now);

        return auction_price;
    }

    // TODO
    function auctionIsActive()
        public
        constant
        atStage(Stages.AuctionStarted)
        returns (bool)
    {
        if(price() > mint.curvePriceAtReserve(mint.combinedReserve()))
            return true;
        return false;
    }

    // Calculate how much currency we need to attain
    // a reserve / balance that would end the auction
    function missingReserveToEndAuction()
        public
        constant
        atStage(Stages.AuctionStarted)
        returns (uint)
    {
        return missingReserveToEndAuction(mint.combinedReserve());
    }

    // We have 2 functions here, because order() already updates the balance
    // We need to calculate missing reserve without the order value
    function missingReserveToEndAuction(uint current_reserve)
        public
        constant
        atStage(Stages.AuctionStarted)
        returns (uint)
    {
        // Calculate reserve at the current auction price
        uint auction_price = price();
        auction_price -= mint.ownerFraction(auction_price);
        uint simulated_reserve = mint.curveReserveAtPrice(auction_price);

        // Auction ends when simulated auction reserve is < the current reserve (auction + mint reserve)
        if(simulated_reserve < current_reserve) {
            return 0;
        }

        uint missing_reserve = SafeMath.sub(simulated_reserve, current_reserve);
        MissingReserve(current_reserve, missing_reserve, now);

        return missing_reserve;
    }

    // The market cap if the auction would end at the current price
    function auctionMarketCap()
        public
        constant
        returns (uint)
    {
        uint auction_price = price();

        // We calculate the supply based on the current auction price
        uint auction_supply = mint.curveSupplyAtPrice(auction_price);

        return SafeMath.mul(auction_price, auction_supply);
    }

    // The valuation if the auction would end at the current price
    function auctionValuation()
        public
        constant
        returns (uint)
    {
        return mint.ownerFraction(auctionMarketCap());
    }

    function mintAsk()
        private
        returns (uint)
    {
        uint mint_price = mint.curvePriceAtReserve(mint.combinedReserve());
        mint_price -= mint.ownerFraction(mint_price);
        return mint_price;
    }

    // Auction has ended, we calculate total reserve and supply
    function finalizeAuction()
        private
        atStage(Stages.AuctionStarted)
    {
        // TODO
        // Utils.xassert(price(), mintAsk())

        // Get already issued tokens and the combined mint+auction reserve
        uint issued_supply = mint.issuedSupply();
        uint combined_reserve = mint.combinedReserve();

        // Number of tokens that should be issued at the current balance
        uint supply_at_reserve = mint.curveSupplyAtReserve(combined_reserve);

        // Calculate total number of tokens issued in this auction
        total_issuance = SafeMath.sub(supply_at_reserve, issued_supply);

        // Memorize received funds
        received_value = this.balance;

        // Send all funds to mint
        mint.fundsFromAuction.value(received_value)();

        stage = Stages.AuctionEnded;
        endTimestamp = now;
        AuctionEnded(uint(stage), received_value, total_issuance);

        // No need to claimTokens
        if(received_value == 0) {
            stage = Stages.AuctionSettled;
            AuctionSettled(uint(stage));
            mint.startMinting();
        }
    }

    function settleAuction()
        private
        atStage(Stages.AuctionEnded)
    {
        assert(issued_value == received_value);
        stage = Stages.AuctionSettled;
        AuctionSettled(uint(stage));
        mint.startMinting();
    }
}