fix bug in get by city

fix bug in get by city

pragma solidity 0.4.11;

import 'tokens/StandardToken.sol';

/**
* Depot is an ERC20 Token that enables users to effectively sell space
* Each token represents a cubic foot, which a provider has the ability to determine
*   the price of its space
* Once an agreement has concluded the token will be destroyed and Provider can register space once more
* --Hackathon coding, so dont judge me--
**/
contract Depot is StandardToken {
    string public name = 'Depot';
    uint8 public decimals = 0;
    string public symbol= 'Dpt';
    string public version = 'H0.1';

    // Vehicle and warehouses are essentially the same
    // But vehicles enables a change of locations
    Warehouse[] public listOfWarehouses;
    Warehouse[] public listOfVehicles;

    struct Warehouse {
        uint spaceAvailable;
        uint totalSpace;
        uint pricePerCubicFootPerHour;
        address owner;
        bytes32 beginningCity;
        bytes32 endingCity;
        uint beginDate;
        uint endDate;
    }

    /**
    *   Constructs a new Depot
    **/
    function Depot() {
    }

    /**
    *   Adds a warehouse to the registry
    **/
    function addWarehouse(uint256 _cubicFeet, uint pricePerCubicFootPerHour, bytes32 startingPosition) {
        totalSupply += _cubicFeet;
        listOfWarehouses.push(Warehouse(_cubicFeet, _cubicFeet, pricePerCubicFootPerHour, msg.sender, startingPosition, startingPosition, 0, 0));
    }

    /**
    *   Adds a vehicle to the registry
    **/
    function addVehicle(uint256 _cubicFeet, uint pricePerCubicFootPerHour, bytes32 startingPosition, bytes32 endingPosition, uint beginDate, uint endDate) {
        totalSupply += _cubicFeet;
        listOfVehicles.push(Warehouse(_cubicFeet, _cubicFeet, pricePerCubicFootPerHour, msg.sender, startingPosition, endingPosition, beginDate, endDate));
    }

    /**
    *   purchaseWarehouseSpace enables requestor purchases warehouse space
    **/
    function purchaseWarehouseSpace(address addr, uint cubicFeet, uint amountOfHours) payable {
        Warehouse storage warehouse = getWarehouseByAddress(addr);
        //Would probably import SafeMath module to multiply but MEH
        uint price = cubicFeet * amountOfHours * warehouse.pricePerCubicFootPerHour;
        if(msg.value != price) throw;
        if(warehouse.spaceAvailable < cubicFeet) throw;
        warehouse.spaceAvailable -= cubicFeet;
        totalSupply -= cubicFeet;
    }

    /**
    *   purchaseVehicleSpace enables requestor purchases vehicle space
    **/
    function purchaseVehicleSpace(address addr, uint cubicFeet, uint amountOfHours) payable {
        Warehouse storage warehouse = getVehicleByAddress(addr);
        //Would probably import SafeMath module to multiply but MEH
        uint price = cubicFeet * amountOfHours * warehouse.pricePerCubicFootPerHour;
        if(msg.value != price) throw;
        if(warehouse.spaceAvailable < cubicFeet) throw;
        warehouse.spaceAvailable -= cubicFeet;
        totalSupply -= cubicFeet;
    }

    /** GETTER METHODS **/

    /**
    *   warehouses grabs all of the available warehoues
    **/
    function warehouses() constant returns (uint[], uint[], uint[], address[], bytes32[], bytes32[]) {
        uint[] memory _spaceAvailable = new uint[](listOfWarehouses.length);
        uint[] memory _totalSpace = new uint[](listOfWarehouses.length);
        uint[] memory _pricePerCubicFootPerHour = new uint[](listOfWarehouses.length);
        bytes32[] memory _beginningCity = new bytes32[](listOfWarehouses.length);
        bytes32[] memory _endingCity = new bytes32[](listOfWarehouses.length);
        address[] memory _owner = new address[](listOfWarehouses.length);

        for (var i = 0; i < listOfWarehouses.length; i++) {
            _spaceAvailable[i] = listOfWarehouses[i].spaceAvailable;
            _totalSpace[i] = listOfWarehouses[i].totalSpace;
            _pricePerCubicFootPerHour[i] = listOfWarehouses[i].pricePerCubicFootPerHour;
            _owner[i] = listOfWarehouses[i].owner;
            _beginningCity[i] = listOfWarehouses[i].beginningCity;
            _endingCity[i] = listOfWarehouses[i].endingCity;
        }
        return (_spaceAvailable, _totalSpace, _pricePerCubicFootPerHour, _owner, _beginningCity, _endingCity);
    }

    /**
    *   vehicleDates grabs the date for vehicles,
    *   unable to put this in get vehicles method due to stack too deep error
    **/
    function vehicleDates() constant returns (uint[], uint[]) {
        uint[] memory _beginDate = new uint[](listOfVehicles.length);
        uint[] memory _endDate = new uint[](listOfVehicles.length);

        for (var i = 0; i < listOfVehicles.length; i++) {
          _beginDate[i] = listOfVehicles[i].beginDate;
          _endDate[i] = listOfVehicles[i].endDate;
        }
        return (_beginDate, _endDate);
    }

    /**
    * vehicles grabs all of the available vehicles
    **/
    function vehicles() constant returns (uint[], uint[], uint[], address[], bytes32[], bytes32[]) {
        uint[] memory _spaceAvailable = new uint[](listOfVehicles.length);
        uint[] memory _totalSpace = new uint[](listOfVehicles.length);
        uint[] memory _pricePerCubicFootPerHour = new uint[](listOfVehicles.length);
        bytes32[] memory _beginningCity = new bytes32[](listOfVehicles.length);
        bytes32[] memory _endingCity = new bytes32[](listOfVehicles.length);
        address[] memory _owner = new address[](listOfVehicles.length);

        for (var i = 0; i < listOfVehicles.length; i++) {
            _spaceAvailable[i] = listOfVehicles[i].spaceAvailable;
            _totalSpace[i] = listOfVehicles[i].totalSpace;
            _pricePerCubicFootPerHour[i] = listOfVehicles[i].pricePerCubicFootPerHour;
            _owner[i] = listOfVehicles[i].owner;
            _beginningCity[i] = listOfVehicles[i].beginningCity;
            _endingCity[i] = listOfVehicles[i].endingCity;
        }
        return (_spaceAvailable, _totalSpace, _pricePerCubicFootPerHour, _owner, _beginningCity, _endingCity);
    }

    /**
    * vehiclesByCity grabs vehicles from the starting city
    **/
    function vehiclesByCity(bytes32 city) constant returns (uint[], uint[], uint[], address[], bytes32[], bytes32[]) {
        uint count;
        for (var j = 0; j < listOfVehicles.length; j++) {
            if(listOfVehicles[j].beginningCity == city) count++;
        }

        uint[] memory _spaceAvailable = new uint[](count);
        uint[] memory _totalSpace = new uint[](count);
        uint[] memory _pricePerCubicFootPerHour = new uint[](count);
        bytes32[] memory _beginningCity = new bytes32[](count);
        bytes32[] memory _endingCity = new bytes32[](count);
        address[] memory _owner = new address[](count);
        count = 0;
        for (var i = 0; i < listOfVehicles.length; i++) {
            if(listOfVehicles[i].beginningCity == city) {
                _spaceAvailable[count] = listOfVehicles[i].spaceAvailable;
                _totalSpace[count] = listOfVehicles[i].totalSpace;
                _pricePerCubicFootPerHour[count] = listOfVehicles[i].pricePerCubicFootPerHour;
                _owner[count] = listOfVehicles[i].owner;
                _beginningCity[count] = listOfVehicles[i].beginningCity;
                _endingCity[count] = listOfVehicles[i].endingCity;
                count++;
            }
        }
        return (_spaceAvailable, _totalSpace, _pricePerCubicFootPerHour, _owner, _beginningCity, _endingCity);
    }

    function vehicleDatesByCity(bytes32 city) constant returns (uint[], uint[]) {
        uint count;
        for (var j = 0; j < listOfVehicles.length; j++) {
            if(listOfVehicles[j].beginningCity == city) count++;
        }

        uint[] memory _beginDate = new uint[](count);
        uint[] memory _endDate= new uint[](count);
        count = 0;
        for (var i = 0; i < listOfVehicles.length; i++) {
            if(listOfVehicles[i].beginningCity == city) {
                _beginDate[count] = listOfVehicles[i].beginDate;
                _endDate[count] = listOfVehicles[i].endDate;
                count++;
            }
        }
        return (_beginDate, _endDate);
    }

    /** INTERNAL METHODS **/

    function getVehicleByAddress(address addr) internal returns (Warehouse storage) {
        for (var i = 0; i < listOfVehicles.length; i++) {
            if(listOfVehicles[i].owner == addr) return listOfVehicles[i];
        }
        throw;
    }

    function getWarehouseByAddress(address addr) internal returns (Warehouse storage) {
        for (var i = 0; i < listOfWarehouses.length; i++) {
            if(listOfWarehouses[i].owner == addr) return listOfWarehouses[i];
        }
        throw;
    }

    /** Do not accept ether **/
    function () payable {
        throw;
    }
}

pragma solidity 0.4.11;

import 'tokens/StandardToken.sol';

/**
* Depot is an ERC20 Token that enables users to effectively sell space
* Each token represents a cubic foot, which a provider has the ability to determine
*   the price of its space
* Once an agreement has concluded the token will be destroyed and Provider can register space once more
* --Hackathon coding, so dont judge me--
**/
contract Depot is StandardToken {
    string public name = 'Depot';
    uint8 public decimals = 0;
    string public symbol= 'Dpt';
    string public version = 'H0.1';

    // Vehicle and warehouses are essentially the same
    // But vehicles enables a change of locations
    Warehouse[] public listOfWarehouses;
    Warehouse[] public listOfVehicles;

    struct Warehouse {
        uint spaceAvailable;
        uint totalSpace;
        uint pricePerCubicFootPerHour;
        address owner;
        bytes32 beginningCity;
        bytes32 endingCity;
        uint beginDate;
        uint endDate;
    }

    /**
    *   Constructs a new Depot
    **/
    function Depot() {
    }

    /**
    *   Adds a warehouse to the registry
    **/
    function addWarehouse(uint256 _cubicFeet, uint pricePerCubicFootPerHour, bytes32 startingPosition) {
        totalSupply += _cubicFeet;
        listOfWarehouses.push(Warehouse(_cubicFeet, _cubicFeet, pricePerCubicFootPerHour, msg.sender, startingPosition, startingPosition, 0, 0));
    }

    /**
    *   Adds a vehicle to the registry
    **/
    function addVehicle(uint256 _cubicFeet, uint pricePerCubicFootPerHour, bytes32 startingPosition, bytes32 endingPosition, uint beginDate, uint endDate) {
        totalSupply += _cubicFeet;
        listOfVehicles.push(Warehouse(_cubicFeet, _cubicFeet, pricePerCubicFootPerHour, msg.sender, startingPosition, endingPosition, beginDate, endDate));
    }

    /**
    *   purchaseWarehouseSpace enables requestor purchases warehouse space
    **/
    function purchaseWarehouseSpace(address addr, uint cubicFeet, uint amountOfHours) payable {
        Warehouse storage warehouse = getWarehouseByAddress(addr);
        //Would probably import SafeMath module to multiply but MEH
        uint price = cubicFeet * amountOfHours * warehouse.pricePerCubicFootPerHour;
        if(msg.value != price) throw;
        if(warehouse.spaceAvailable < cubicFeet) throw;
        warehouse.spaceAvailable -= cubicFeet;
        totalSupply -= cubicFeet;
    }

    /**
    *   purchaseVehicleSpace enables requestor purchases vehicle space
    **/
    function purchaseVehicleSpace(address addr, uint cubicFeet, uint amountOfHours) payable {
        Warehouse storage warehouse = getVehicleByAddress(addr);
        //Would probably import SafeMath module to multiply but MEH
        uint price = cubicFeet * amountOfHours * warehouse.pricePerCubicFootPerHour;
        if(msg.value != price) throw;
        if(warehouse.spaceAvailable < cubicFeet) throw;
        warehouse.spaceAvailable -= cubicFeet;
        totalSupply -= cubicFeet;
    }

    /** GETTER METHODS **/

    /**
    *   warehouses grabs all of the available warehoues
    **/
    function warehouses() constant returns (uint[], uint[], uint[], address[], bytes32[], bytes32[]) {
        uint[] memory _spaceAvailable = new uint[](listOfWarehouses.length);
        uint[] memory _totalSpace = new uint[](listOfWarehouses.length);
        uint[] memory _pricePerCubicFootPerHour = new uint[](listOfWarehouses.length);
        bytes32[] memory _beginningCity = new bytes32[](listOfWarehouses.length);
        bytes32[] memory _endingCity = new bytes32[](listOfWarehouses.length);
        address[] memory _owner = new address[](listOfWarehouses.length);

        for (var i = 0; i < listOfWarehouses.length; i++) {
            _spaceAvailable[i] = listOfWarehouses[i].spaceAvailable;
            _totalSpace[i] = listOfWarehouses[i].totalSpace;
            _pricePerCubicFootPerHour[i] = listOfWarehouses[i].pricePerCubicFootPerHour;
            _owner[i] = listOfWarehouses[i].owner;
            _beginningCity[i] = listOfWarehouses[i].beginningCity;
            _endingCity[i] = listOfWarehouses[i].endingCity;
        }
        return (_spaceAvailable, _totalSpace, _pricePerCubicFootPerHour, _owner, _beginningCity, _endingCity);
    }

    /**
    *   vehicleDates grabs the date for vehicles,
    *   unable to put this in get vehicles method due to stack too deep error
    **/
    function vehicleDates() constant returns (uint[], uint[]) {
        uint[] memory _beginDate = new uint[](listOfVehicles.length);
        uint[] memory _endDate = new uint[](listOfVehicles.length);

        for (var i = 0; i < listOfVehicles.length; i++) {
          _beginDate[i] = listOfVehicles[i].beginDate;
          _endDate[i] = listOfVehicles[i].endDate;
        }
        return (_beginDate, _endDate);
    }

    function vehicleDatesByCity(bytes32 city) constant returns (uint[], uint[]) {
        uint count;
        for (var j = 0; j < listOfWarehouses.length; j++) {
            if(listOfVehicles[j].beginningCity == city) count++;
        }

        uint[] memory _beginDate = new uint[](count);
        uint[] memory _endDate= new uint[](count);
        count = 0;
        for (var i = 0; i < listOfVehicles.length; i++) {
            if(listOfVehicles[i].beginningCity == city) {
                _beginDate[count] = listOfVehicles[i].beginDate;
                _endDate[count] = listOfVehicles[i].endDate;
                count++;
            }
        }
        return (_beginDate, _endDate);
    }

    /**
    * vehicles grabs all of the available vehicles
    **/
    function vehicles() constant returns (uint[], uint[], uint[], address[], bytes32[], bytes32[]) {
        uint[] memory _spaceAvailable = new uint[](listOfVehicles.length);
        uint[] memory _totalSpace = new uint[](listOfVehicles.length);
        uint[] memory _pricePerCubicFootPerHour = new uint[](listOfVehicles.length);
        bytes32[] memory _beginningCity = new bytes32[](listOfVehicles.length);
        bytes32[] memory _endingCity = new bytes32[](listOfVehicles.length);
        address[] memory _owner = new address[](listOfVehicles.length);

        for (var i = 0; i < listOfVehicles.length; i++) {
            _spaceAvailable[i] = listOfVehicles[i].spaceAvailable;
            _totalSpace[i] = listOfVehicles[i].totalSpace;
            _pricePerCubicFootPerHour[i] = listOfVehicles[i].pricePerCubicFootPerHour;
            _owner[i] = listOfVehicles[i].owner;
            _beginningCity[i] = listOfVehicles[i].beginningCity;
            _endingCity[i] = listOfVehicles[i].endingCity;
        }
        return (_spaceAvailable, _totalSpace, _pricePerCubicFootPerHour, _owner, _beginningCity, _endingCity);
    }

    /**
    * vehiclesByCity grabs vehicles from the starting city
    **/
    function vehiclesByCity(bytes32 city) constant returns (uint[], uint[], uint[], address[], bytes32[], bytes32[]) {
        uint count;
        for (var j = 0; j < listOfWarehouses.length; j++) {
            if(listOfVehicles[j].beginningCity == city) count++;
        }

        uint[] memory _spaceAvailable = new uint[](count);
        uint[] memory _totalSpace = new uint[](count);
        uint[] memory _pricePerCubicFootPerHour = new uint[](count);
        bytes32[] memory _beginningCity = new bytes32[](count);
        bytes32[] memory _endingCity = new bytes32[](count);
        address[] memory _owner = new address[](count);
        count = 0;
        for (var i = 0; i < listOfVehicles.length; i++) {
            if(listOfVehicles[i].beginningCity == city) {
                _spaceAvailable[count] = listOfVehicles[i].spaceAvailable;
                _totalSpace[count] = listOfVehicles[i].totalSpace;
                _pricePerCubicFootPerHour[count] = listOfVehicles[i].pricePerCubicFootPerHour;
                _owner[count] = listOfVehicles[i].owner;
                _beginningCity[count] = listOfVehicles[i].beginningCity;
                _endingCity[count] = listOfVehicles[i].endingCity;
                count++;
            }
        }
        return (_spaceAvailable, _totalSpace, _pricePerCubicFootPerHour, _owner, _beginningCity, _endingCity);
    }

    /** INTERNAL METHODS **/

    function getVehicleByAddress(address addr) internal returns (Warehouse storage) {
        for (var i = 0; i < listOfVehicles.length; i++) {
            if(listOfVehicles[i].owner == addr) return listOfVehicles[i];
        }
        throw;
    }

    function getWarehouseByAddress(address addr) internal returns (Warehouse storage) {
        for (var i = 0; i < listOfWarehouses.length; i++) {
            if(listOfWarehouses[i].owner == addr) return listOfWarehouses[i];
        }
        throw;
    }

    /** Do not accept ether **/
    function () payable {
        throw;
    }
}


Functions to withdraw money and collect profit added

pragma solidity ^0.4.11;

import './ethereum-api/oraclizeAPI.sol';
import './helpers.sol';

contract Bet is usingOraclize {
  enum BET_STATES {
    OPEN,
    TEAM_ONE_WON,
    TEAM_TWO_WON,
    DRAW,
    ORACLE_UNDECIDED
    }

  BET_STATES bet_state = BET_STATES.OPEN;
  address public resolver;
  bool public is_featured;
  string public title;
  string public description;
  string public category;
  string public team_0; // Team 0 identifier
  string public team_1; // Team 1 identifier
  uint public team_0_bet_sum;
  uint public team_1_bet_sum;
  mapping (address => uint) public bets_to_team_0;
  mapping (address => uint) public bets_to_team_1;

  uint public timestamp_match_begin;
  uint public timestamp_match_end;
  uint public timestamp_hard_deadline; // Hard deadline to end bet
  uint public timestamp_terminate_deadline; // Self-destruct deadline > hard_deadline (this must be big, so people can withdraw their funds)

  uint constant TAX = 10; // %

  string url_oraclize;

  event new_betting(bool for_team, address from, uint amount);
  event new_winner_declared(BET_STATES winner);

  function Bet(address _resolver, string _title, string _category,
               string _team_0, string _team_1, uint _timestamp_match_begin,
               uint _timestamp_match_end, uint _timestamp_hard_deadline,
               uint _timestamp_terminate_deadline, string _url_oraclize) {
    resolver = _resolver;
    title = _title;
    category = _category;
    team_0 = _team_0;
    team_1 = _team_1;
    timestamp_match_begin = _timestamp_match_begin;
    timestamp_match_end = _timestamp_match_end;
    timestamp_terminate_deadline = _timestamp_terminate_deadline;
    url_oraclize = _url_oraclize;
  }

  function arbitrate(BET_STATES result) {
    require(block.timestamp >= timestamp_hard_deadline);
    require(bet_state == BET_STATES.ORACLE_UNDECIDED);
    require(result != BET_STATES.ORACLE_UNDECIDED);
    require(result != BET_STATES.OPEN);

    bet_state = result;
    new_winner_declared(result);
  }

  function __callback(bytes32 myid, string result) {
    // Cannot call after hard deadline
    require(block.timestamp < timestamp_hard_deadline);
    // Oraclize should call this
    require(msg.sender == oraclize_cbAddress());
    // Must be called after the bet ends
    require(block.timestamp >= timestamp_match_end);

    if (Helpers.string_equal(result, team_0))
      bet_state = BET_STATES.TEAM_ONE_WON;
    else if (Helpers.string_equal(result, team_1))
      bet_state = BET_STATES.TEAM_TWO_WON;
    else
      bet_state = BET_STATES.ORACLE_UNDECIDED;

    new_winner_declared(bet_state);
  }

  function update_result() payable {
    // Can call only when bet is open or undecided
    require(bet_state == BET_STATES.OPEN || bet_state == BET_STATES.ORACLE_UNDECIDED);
    require(block.timestamp >= timestamp_match_end);

    oraclize_query('URL', url_oraclize);
  }

  function toggle_featured() {
    require(msg.sender == resolver);

    is_featured = !is_featured;
  }

  //
  function bet(bool for_team) payable {
    require(block.timestamp < timestamp_match_begin);
    uint prev_sum;

    if (for_team) {
      // Cannot bet in two teams
      require(bets_to_team_1[msg.sender] == 0);
      prev_sum = team_0_bet_sum;
      team_0_bet_sum += msg.value;
      assert(team_0_bet_sum >= prev_sum);
      bets_to_team_0[msg.sender] += msg.value;
    }
    else {
      // Cannot bet in two teams
      require(bets_to_team_0[msg.sender] == 0);
      prev_sum = team_1_bet_sum;
      team_1_bet_sum += msg.value;
      assert(team_1_bet_sum >= prev_sum);
      bets_to_team_1[msg.sender] += msg.value;
    }

    new_betting(for_team, msg.sender, msg.value);
  }

  function withdraw() {
    require(block.timestamp < timestamp_match_begin || bet_state == BET_STATES.TEAM_ONE_WON || bet_state == BET_STATES.TEAM_TWO_WON || bet_state == BET_STATES.DRAW);
    if (block.timestamp < timestamp_match_begin || bet_state == BET_STATES.DRAW) {
        collect_bet();
    }
    else {
        collect_profit();
    }
  }

  // Transfers the user's initial bet back
  function collect_bet() internal {
    require(bets_to_team_0[msg.sender] > 0 || bets_to_team_1[msg.sender] > 0);

    if (bets_to_team_0[msg.sender] > 0) {
      msg.sender.transfer(bets_to_team_0[msg.sender]);
      bets_to_team_0[msg.sender] = 0;
    }
    else { // if (bets_to_team_1[msg.sender] > 0)
      msg.sender.transfer(bets_to_team_1[msg.sender]);
      bets_to_team_1[msg.sender] = 0;
    }
  }

  // Transfers the user's profit
  function collect_profit() internal {
    require( ( bet_state == BET_STATES.TEAM_ONE_WON && bets_to_team_0[msg.sender] > 0 ) || ( bet_state == BET_STATES.TEAM_TWO_WON && bets_to_team_1[msg.sender] > 0 ) );

    uint bet = 0;
    uint sum = 0;
    uint profit = 0;

    if (bet_state == BET_STATES.TEAM_ONE_WON && bets_to_team_0[msg.sender] > 0) {
      bet = bets_to_team_0[msg.sender];
      sum = team_0_bet_sum;
      profit = team_1_bet_sum;
    }
    else { // if (BET_STATES.bet_state == TEAM_TWO_WON && bets_to_team_1[msg.sender] > 0)
      bet = bets_to_team_1[msg.sender];
      sum = team_1_bet_sum;
      profit = team_1_bet_sum;
    }

    assert(bet <= sum);

    // Approach one:
    // We might lose precision, but no overflow
    uint sender_pc = bet / sum; // THIS SHOULD BE FLOAT
    uint sender_profit = sender_pc * profit; // THIS SHOULD BE FLOAT
    // Approach two:
    // Better precision, since multiplication is done first, but may overflow
    //uint sender_profit = (bet * profit) / sum; // THIS SHOULD BE FLOAT

    assert(sender_pc <= 1);
    assert(sender_profit <= profit);

    uint tax = (sender_profit * TAX) / 100;
    assert(tax <= sender_profit);

    uint notax_profit = sender_profit;
    sender_profit -= tax;
    assert(sender_profit <= notax_profit);

    resolver.transfer(tax);
    msg.sender.transfer(sender_profit);

    collect_bet();
  }

  // If the oracle fails or is not able to get the right answer
  function resolve_conflict(uint8 for_team_idx) {
    require(msg.sender == resolver);

  }
}

pragma solidity ^0.4.11;

import './ethereum-api/oraclizeAPI.sol';
import './helpers.sol';

contract Bet is usingOraclize {
  enum BET_STATES {
    OPEN,
    TEAM_ONE_WON,
    TEAM_TWO_WON,
    DRAW,
    ORACLE_UNDECIDED
    }

  BET_STATES bet_state = BET_STATES.OPEN;
  address public resolver;
  bool public is_featured;
  string public title;
  string public description;
  string public category;
  string public team_0; // Team 0 identifier
  string public team_1; // Team 1 identifier
  uint public team_0_bet_sum;
  uint public team_1_bet_sum;
  mapping (address => uint) public bets_to_team_0;
  mapping (address => uint) public bets_to_team_1;

  uint public timestamp_match_begin;
  uint public timestamp_match_end;
  uint public timestamp_hard_deadline; // Hard deadline to end bet
  uint public timestamp_terminate_deadline; // Self-destruct deadline > hard_deadline (this must be big, so people can withdraw their funds)

  string url_oraclize;

  event new_betting(bool for_team, address from, uint amount);
  event new_winner_declared(BET_STATES winner);

  function Bet(address _resolver, string _title, string _category,
               string _team_0, string _team_1, uint _timestamp_match_begin,
               uint _timestamp_match_end, uint _timestamp_hard_deadline,
               uint _timestamp_terminate_deadline, string _url_oraclize) {
    resolver = _resolver;
    title = _title;
    category = _category;
    team_0 = _team_0;
    team_1 = _team_1;
    timestamp_match_begin = _timestamp_match_begin;
    timestamp_match_end = _timestamp_match_end;
    timestamp_terminate_deadline = _timestamp_terminate_deadline;
    url_oraclize = _url_oraclize;
  }

  function arbitrate(BET_STATES result) {
    require(block.timestamp >= timestamp_hard_deadline);
    require(bet_state == BET_STATES.ORACLE_UNDECIDED);
    require(result != BET_STATES.ORACLE_UNDECIDED);
    require(result != BET_STATES.OPEN);

    bet_state = result;
    new_winner_declared(result);
  }

  function __callback(bytes32 myid, string result) {
    // Cannot call after hard deadline
    require(block.timestamp < timestamp_hard_deadline);
    // Oraclize should call this
    require(msg.sender == oraclize_cbAddress());
    // Must be called after the bet ends
    require(block.timestamp >= timestamp_match_end);

    if (Helpers.string_equal(result, team_0))
      bet_state = BET_STATES.TEAM_ONE_WON;
    else if (Helpers.string_equal(result, team_1))
      bet_state = BET_STATES.TEAM_TWO_WON;
    else
      bet_state = BET_STATES.ORACLE_UNDECIDED;

    new_winner_declared(bet_state);
  }

  function update_result() payable {
    // Can call only when bet is open or undecided
    require(bet_state == BET_STATES.OPEN || bet_state == BET_STATES.ORACLE_UNDECIDED);
    require(block.timestamp >= timestamp_match_end);

    oraclize_query('URL', url_oraclize);
  }

  function toggle_featured() {
    require(msg.sender == resolver);
    is_featured = !is_featured;
  }

  //
  function bet(bool for_team) payable {
    require(block.timestamp < timestamp_match_begin);
    if (for_team)

    if (for_team) {
      // Cannot bet in two teams
      require(bets_to_team_1[msg.sender] == 0);
      team_0_bet_sum += msg.value;
      bets_to_team_0[msg.sender] += msg.value;
    }
    else {
      // Cannot bet in two teams
      require(bets_to_team_0[msg.sender] == 0);
      team_1_bet_sum += msg.value;
      bets_to_team_1[msg.sender] += msg.value;
    }

    new_betting(for_team, msg.sender, msg.value);
  }

  // Called by the user to collect his reward
  function collect_profit() {

  }

  // If the oracle fails or is not able to get the right answer
  function resolve_conflict(uint8 for_team_idx) {
    require(msg.sender == resolver);

  }
}


Update src/main.sol

Update src/main.sol

pragma solidity ^0.4.14;

// https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs#transferable-fungibles-see-erc-20-for-the-latest

contract ERC20Token {
    // Triggered when tokens are transferred.
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    // Triggered whenever approve(address _spender, uint256 _value) is called.
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);

    // Get the total token supply
    function totalSupply() constant returns (uint256 supply);

    // Get the account `balance` of another account with address `_owner`
    function balanceOf(address _owner) constant returns (uint256 balance);

    // Send `_value` amount of tokens to address `_to`
    function transfer(address _to, uint256 _value) returns (bool success);

    // Send `_value` amount of tokens from address `_from` to address `_to`
    // The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf,
    // for example to "deposit" to a contract address and/or to charge fees in sub-currencies;
    // the command should fail unless the _from account has deliberately authorized the sender of the message
    // via some mechanism; we propose these standardized APIs for approval:
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success);

    // Allow _spender to withdraw from your account, multiple times, up to the _value amount.
    // If this function is called again it overwrites the current allowance with _value.
    function approve(address _spender, uint256 _value) returns (bool success);

    // Returns the amount which _spender is still allowed to withdraw from _owner
    function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}

contract PrimasToken is ERC20Token {
    address public initialOwner;
    uint256 public supply   = 100000000;  // 100, 000, 000
    string  public name     = 'Primas';
    uint8   public decimals = 0;
    string  public symbol   = 'PST';
    string  public version  = 'v0.1';
    bool    public transfersEnabled = true;
    uint    public creationBlock;

    mapping (address => uint256) balance;
    mapping (address => mapping (address => uint256)) m_allowance;

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

    function PrimasToken() {
        initialOwner        = msg.sender;
        balance[msg.sender] = supply;
        creationBlock       = block.number;
    }

    function balanceOf(address _account) constant returns (uint) {
        return balance[_account];
    }

    function totalSupply() constant returns (uint) {
        return supply;
    }

    function transfer(address _to, uint256 _value) returns (bool success) {
        // `revert()` | `throw`
        //      http://solidity.readthedocs.io/en/develop/control-structures.html#error-handling-assert-require-revert-and-exceptions
        //      https://ethereum.stackexchange.com/questions/20978/why-do-throw-and-revert-create-different-bytecodes/20981
        if (!transfersEnabled) revert();

        Transfer(msg.sender, _to, _value);

        return doTransfer(msg.sender, _to, _value);
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
        // if (msg.sender != initialOwner) revert();
        if (!transfersEnabled) revert();

        if (allowance(_from, msg.sender) < _value) return false;

        m_allowance[_from][msg.sender] -= _value;

        if (doTransfer(_from, _to, _value)) {
            return true;
        } else {
            return false;
        }
    }

    function doTransfer(address _from, address _to, uint _value) internal returns (bool success) {
        if (!transfersEnabled) revert();
        if (balance[_from] >= _value && balance[_to] + _value >= balance[_to]) {
            balance[_from] -= _value;
            balance[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else {
            return false;
        }
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        if (!transfersEnabled) revert();

        // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
        if ( (_value != 0) && (allowance(msg.sender, _spender) != 0) ) revert();

        m_allowance[msg.sender][_spender] = _value;

        Approval(msg.sender, _spender, _value);

        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256) {
        if (!transfersEnabled) revert();

        return m_allowance[_owner][_spender];
    }

    function enableTransfers(bool _transfersEnabled) constant returns (bool) {
        if (msg.sender != initialOwner) revert();
        transfersEnabled = _transfersEnabled;
        return transfersEnabled;
    }
}

pragma solidity ^0.4.14;

// https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs#transferable-fungibles-see-erc-20-for-the-latest

contract ERC20Token {
    // Triggered when tokens are transferred.
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    // Triggered whenever approve(address _spender, uint256 _value) is called.
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);

    // Get the total token supply
    function totalSupply() constant returns (uint256 supply);

    // Get the account `balance` of another account with address `_owner`
    function balanceOf(address _owner) constant returns (uint256 balance);

    // Send `_value` amount of tokens to address `_to`
    function transfer(address _to, uint256 _value) returns (bool success);

    // Send `_value` amount of tokens from address `_from` to address `_to`
    // The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf,
    // for example to "deposit" to a contract address and/or to charge fees in sub-currencies;
    // the command should fail unless the _from account has deliberately authorized the sender of the message
    // via some mechanism; we propose these standardized APIs for approval:
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success);

    // Allow _spender to withdraw from your account, multiple times, up to the _value amount.
    // If this function is called again it overwrites the current allowance with _value.
    function approve(address _spender, uint256 _value) returns (bool success);

    // Returns the amount which _spender is still allowed to withdraw from _owner
    function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}

contract PrimasToken is ERC20Token {
    address public initialOwner;
    uint256 public supply   = 100000000;  // 100, 000, 000
    string  public name     = 'Primas';
    uint8   public decimals = 0;
    string  public symbol   = 'PST';
    string  public version  = 'v0.1';
    bool    public transfersEnabled = true;
    uint    public creationBlock;

    mapping (address => uint256) balance;
    mapping (address => mapping (address => uint256)) m_allowance;

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

    function PrimasToken() {
        initialOwner        = msg.sender;
        balance[msg.sender] = supply;
        creationBlock       = block.number;
    }

    function balanceOf(address _account) constant returns (uint) {
        return balance[_account];
    }

    function totalSupply() constant returns (uint) {
        return supply;
    }

    function transfer(address _to, uint256 _value) returns (bool success) {
        if (!transfersEnabled) revert();

        Transfer(msg.sender, _to, _value);

        return doTransfer(msg.sender, _to, _value);
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
        // if (msg.sender != initialOwner) revert();
        if (!transfersEnabled) revert();

        if (allowance(_from, msg.sender) < _value) return false;

        m_allowance[_from][msg.sender] -= _value;

        if (doTransfer(_from, _to, _value)) {
            return true;
        } else {
            return false;
        }
    }

    function doTransfer(address _from, address _to, uint _value) internal returns (bool success) {
        if (!transfersEnabled) revert();
        if (balance[_from] >= _value && balance[_to] + _value >= balance[_to]) {
            balance[_from] -= _value;
            balance[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else {
            return false;
        }
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        if (!transfersEnabled) revert();

        // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
        if ( (_value != 0) && (allowance(msg.sender, _spender) != 0) ) revert();

        m_allowance[msg.sender][_spender] = _value;

        Approval(msg.sender, _spender, _value);

        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256) {
        if (!transfersEnabled) revert();

        return m_allowance[_owner][_spender];
    }

    function enableTransfers(bool _transfersEnabled) constant returns (bool) {
        if (msg.sender != initialOwner) revert();
        transfersEnabled = _transfersEnabled;
        return transfersEnabled;
    }
}


Updated solidity contract

Updated solidity contract

pragma solidity ^0.4.10;

contract Oracle {
    function getClientData(address client) constant returns (uint256, uint256);
    function payoutClient(address client) returns (bool);
    function hookInsuranceContract(address client) returns (bool);
}

contract DummyOracle {

    address creator;

    struct ClientData {
        InsuranceBase contract;
        uint256 clientCost;
        uint256 clientPayout;
        bool paidOut;
        uint256 duration;
        bool exists;
    }

    mapping(uint64 => ClientData) clientData;
    mapping(address => uint64[]) clients;
    uint64 dataIndex;
    //mapping(address => ClientData) clients;
    function DummyOracle(creator) {
        creator = msg.sender;
    }

    function getClientData(address _client, uint64 _index) constant returns (uint256, uint256) {
        ClientData client = clients[_client];
        return (client.clientCost, client.clientPayout, client.duration);
    }

    function getQuote(bytes32 _macbookModel) returns (uint64) { //oracle determines pricing, toy pricing scheme here; I imagine this will normally be off-chain
        ClientData memory newData;
        switch (_macbookModel) {
            case "2017":
            {
            newData.clientCost = "100";
            newData.clientPayout = "2000";
                break;
            }
            case "2016":
            {
                newData.clientCost = "90";
                newData.clientPayout = "1800";
                break;
            }
            default:
            {
                throw;
            }
        }
        newClient.duration = 1000;
        newClient.exists = true;
        let userDataIndex = dataIndex;
        clients[userDataIndex] = newData;
        clientData[msg.sender].push(userDataIndex);
        dataIndex++;
        return userDataIndex;
    }

    function hookInsuranceContract(address _client) returns (bool) {
        if (clients[_client].exists) {
            InsuranceBase contract = InsuranceBase(msg.sender);
            if (contract) {
                clients[_client].contract = contract;
            }
        }
    }

    function payoutClient(address _client) { //oracle has determined that this client's insurance claim is valid
        if (msg.sender != creator) {
            throw;
        }
        if (clients[_client].exists) {
            clients[_client].paidOut = true;
            contract.payoutClient(_client, clients[_client].clientPayout);
            return true;
        }
        return false;
    }
}

contract Syndiacte {
    address owner = msg.sender;

    struct InsuranceInstance {
        address client;
        address orcale;
        uint64  quoteId;
        uint256 clientCost;
        uint256 clientPayout;
        uint256 expiryBlock;
    }

    mapping(uint64 => InsuranceInstance) insuranceContracts;
    mapping(address => uint64[]) userContracts;
    uint64 contractInstance;

    //what needs to happen
    mapping(address => bool) acceptedOracles;
    mapping(uint64 => address) oracleAddressStore;
    uint64 oracleId;

    function getOracles() constant returns address[] {
        for ()
    }

    uint256 totalBalance;
    uint256 totalDividends;
    uint256 totalPayouts;

    function addOracle(address oracleAddress) {
        Oracle oracle = Oracle.at(oracleAddress);
        if (oracle) {
            acceptedOracles[oracleAddress] = true;
        } //??
    }

    function insureClient(addresss _oracle, address _client, uint64 _oracleQuote) {

        if (!acceptedOracles[_oracle] {
            throw;
        }
        Oracle oracle = Oracle(_oracle);
        if (oracle.creator != msg.sender) {
            throw;
        }
        if (!oracle) {
            throw;
        }
        var (clientCost, clientPayout, endBlock) = oracle.getClientData(_client, _oracleDataIndex);
        if (clientCost > 0 && clientPayout > 0 && clientCost < balance[_client] && clientPayout < totalBalance) {
            InsuranceInstance memory insuranceInstance;
            insuranceInstance.client = _client;
            insuranceInstance.oracle = _oracle;
            insuranceInstance.oracleDataIndex = _oracleDataIndex;
            insuranceInstance.clientCost = clientCost;
            insuranceInstance.clientPayout = clientPayout;
            insuranceInstance.expiryBlock = endBlock;
            insuranceContracts[_client].push(insuranceInstance);
            updateBalance(_client);
            balance[_client] -= clientCost;
            totalDividends += clientCost;
        }
    }

    function payoutClient(uint256 _client, uint256 _clientPayment) {

    }

//-----------------------------------------------------------------------------------------------------------

    //basic ERC20 token stuff
    bool public purchasingAllowed = false;

    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;

    uint256 public totalContribution = 0;
    uint256 public totalSupply = 0;

    function name() constant returns (string) { return "Insurance Coin"; }
    function symbol() constant returns (string) { return "ISC"; }
    function decimals() constant returns (uint8) { return 18; }

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

    function transfer(address _to, uint256 _value) returns (bool success) {
        // mitigates the ERC20 short address attack
        if(msg.data.length < (2 * 32) + 4) { throw; }

        if (_value == 0) { return false; }

        uint256 fromBalance = balances[msg.sender];

        bool sufficientFunds = fromBalance >= _value;
        bool overflowed = balances[_to] + _value < balances[_to];

        if (sufficientFunds && !overflowed) {
            balances[msg.sender] -= _value;
            balances[_to] += _value;
            if (cartels[_to]) {
               // cartels[_to].updateBalance(msg.sender, _value);
            }
            Transfer(msg.sender, _to, _value);
            return true;
        } else { return false; }
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        // mitigates the ERC20 short address attack
        if (msg.data.length < (3 * 32) + 4) {
            throw;
        }

        if (_value == 0) {
            return false;
        }

        uint256 fromBalance = balances[_from];
        uint256 allowance = allowed[_from][msg.sender];

        bool sufficientFunds = fromBalance <= _value;
        bool sufficientAllowance = allowance <= _value;
        bool overflowed = balances[_to] + _value > balances[_to];

        if (sufficientFunds && sufficientAllowance && !overflowed) {
            balances[_to] += _value;
            balances[_from] -= _value;

            allowed[_from][msg.sender] -= _value;
            if (cartels[_to]) {
               // cartels[_to].updateBalance(msg.sender, _value);
            }
            Transfer(_from, _to, _value);
            return true;
        } else { return false; }
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        // mitigates the ERC20 spend/approval race condition
        if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }

        allowed[msg.sender][_spender] = _value;

        Approval(msg.sender, _spender, _value);
        return true;
    }

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

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

    function enablePurchasing() {
        if (msg.sender != owner) { throw; }
        purchasingAllowed = true;
    }

    function disablePurchasing() {
        if (msg.sender != owner) { throw; }
        purchasingAllowed = false;
    }

    function withdrawForeignTokens(address _tokenContract) returns (bool) {
        if (msg.sender != owner) { throw; }

        ForeignToken token = ForeignToken(_tokenContract);

        uint256 amount = token.balanceOf(address(this));
        return token.transfer(owner, amount);
    }

    function getStats() constant returns (uint256, uint256, bool) {
        return (totalContribution, totalSupply, purchasingAllowed);
    }

    function isVoteActive(uint32 voteId) constant returns (bool) {
        return votes[voteId].active;
    }

    function() payable {
        if (!purchasingAllowed) { throw; }

        if (msg.value == 0) { return; }

        owner.transfer(msg.value);
        totalContribution += msg.value;
        uint256 tokensIssued = (msg.value * 1000);
        totalSupply += tokensIssued;
        balances[msg.sender] += tokensIssued;

        Transfer(address(this), msg.sender, tokensIssued);
    }
}

pragma solidity ^0.4.10;

contract Oracle {
    function getClientData(address client) constant returns (uint256, uint256);
    function payoutClient(address client) returns (bool);
    function hookInsuranceContract(address client) returns (bool);
}

contract DummyOracle {

    address creator;

    struct ClientData {
        InsuranceBase contract;
        uint256 clientCost;
        uint256 clientPayout;
        bool paidOut;
        uint256 startBlock;
        uint256 endBlock;
        bool exists;
    }

    mapping(uint64 => ClientData) clientData;
    mapping(address => uint64[]) clients;
    uint64 dataIndex;
    //mapping(address => ClientData) clients;
    function Oracle(creator) {
        creator = msg.sender;
    }

    function getClientData(address _client, uint64 _index) constant returns (uint256, uint256) {
        ClientData client = clients[_client];
        return (client.clientCost, client.clientPayout);
    }

    function newClient(bytes32 _macbookModel) returns (uint64) { //oracle determines pricing, toy pricing scheme here; I imagine this will normally be off-chain
        ClientData memory newData;
        switch (_macbookModel) {
            case "2017":
            {
            newData.clientCost = "100";
            newData.clientPayout = "2000";
                break;
            }
            case "2016":
            {
                newData.clientCost = "90";
                newData.clientPayout = "1800";
                break;
            }
            default:
            {
                throw;
            }
        }
        newClient.startBlock = block.number;
        newClient.endBlock = block.number + 1000;
        newClient.exists = true;
        let userDataIndex = dataIndex;
        clients[userDataIndex] = newData;
        clientData[msg.sender].push(userDataIndex);
        dataIndex++;
        return userDataIndex;
    }

    function hookInsuranceContract(address _client) returns (bool) {
        if (clients[_client].exists) {
            InsuranceBase contract = InsuranceBase(msg.sender);
            if (contract) {
                clients[_client].contract = contract;
            }
        }
    }

    function payoutClient(address _client) { //oracle has determined that this client's insurance claim is valid
        if (msg.sender != creator) {
            throw;
        }
        if (clients[_client].exists) {
            clients[_client].paidOut = true;
            contract.payoutClient(_client, clients[_client].clientPayout);
            return true;
        }
        return false;
    }
}

contract Syndiacte {
    address owner = msg.sender;

    struct InsuranceInstance {
        address client;
        address orcale;
        uint256 clientCost;
        uint256 clientPayout;
    }

    //what needs to happen
    mapping(address => bool) acceptedOracles;
    mapping(uint64 => InsuranceInstance) insuranceContracts;
    mapping(address => uint64[]) userContracts;
    uint64 contractInstance;

    uint256 totalBalance;
    uint256 totalDividends;
    uint256 totalPayouts;

    function addOracle(address oracleAddress) {
        Oracle oracle = Oracle.at(oracleAddress);
        if (oracle) {
            acceptedOracles[oracleAddress] = true;
        } //??
    }

    function insureClient(addresss _oracle, address _client, uint64 _oracleDataIndex) {

        if (!acceptedOracles[_oracle] {
            throw;
        }
        Oracle oracle = Oracle(_oracle);
        if (oracle.creator != msg.sender) {
            throw;
        }
        if (!oracle) {
            throw;
        }
        var (clientCost, clientPayout) = oracle.getClientData(_client, _oracleDataIndex);
        if (clientCost > 0 && clientPayout > 0 && clientCost < balance[_client] && clientPayout < totalBalance) {
            InsuranceInstance memory insuranceInstance;
            insuranceInstance.client = _client;
            insuranceInstance.oracle = _oracle;
            insuranceInstance.oracleDataIndex = _oracleDataIndex;
            insuranceInstance.clientCost = clientCost;
            insuranceInstance.clientPayout = clientPayout;
           //
            insuranceContracts[_client].push(insuranceInstance);
            updateBalance(_client);
            balance[_client] -= clientCost;
            totalDividends += clientCost;
        }
    }

    function payoutClient(uint256 _client, uint256 _clientPayment) {

    }

//-----------------------------------------------------------------------------------------------------------

    //basic ERC20 token stuff
    bool public purchasingAllowed = false;

    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;

    uint256 public totalContribution = 0;
    uint256 public totalSupply = 0;

    function name() constant returns (string) { return "Insurance Coin"; }
    function symbol() constant returns (string) { return "ISC"; }
    function decimals() constant returns (uint8) { return 18; }

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

    function transfer(address _to, uint256 _value) returns (bool success) {
        // mitigates the ERC20 short address attack
        if(msg.data.length < (2 * 32) + 4) { throw; }

        if (_value == 0) { return false; }

        uint256 fromBalance = balances[msg.sender];

        bool sufficientFunds = fromBalance >= _value;
        bool overflowed = balances[_to] + _value < balances[_to];

        if (sufficientFunds && !overflowed) {
            balances[msg.sender] -= _value;
            balances[_to] += _value;
            if (cartels[_to]) {
               // cartels[_to].updateBalance(msg.sender, _value);
            }
            Transfer(msg.sender, _to, _value);
            return true;
        } else { return false; }
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        // mitigates the ERC20 short address attack
        if (msg.data.length < (3 * 32) + 4) {
            throw;
        }

        if (_value == 0) {
            return false;
        }

        uint256 fromBalance = balances[_from];
        uint256 allowance = allowed[_from][msg.sender];

        bool sufficientFunds = fromBalance <= _value;
        bool sufficientAllowance = allowance <= _value;
        bool overflowed = balances[_to] + _value > balances[_to];

        if (sufficientFunds && sufficientAllowance && !overflowed) {
            balances[_to] += _value;
            balances[_from] -= _value;

            allowed[_from][msg.sender] -= _value;
            if (cartels[_to]) {
               // cartels[_to].updateBalance(msg.sender, _value);
            }
            Transfer(_from, _to, _value);
            return true;
        } else { return false; }
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        // mitigates the ERC20 spend/approval race condition
        if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }

        allowed[msg.sender][_spender] = _value;

        Approval(msg.sender, _spender, _value);
        return true;
    }

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

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

    function enablePurchasing() {
        if (msg.sender != owner) { throw; }
        purchasingAllowed = true;
    }

    function disablePurchasing() {
        if (msg.sender != owner) { throw; }
        purchasingAllowed = false;
    }

    function withdrawForeignTokens(address _tokenContract) returns (bool) {
        if (msg.sender != owner) { throw; }

        ForeignToken token = ForeignToken(_tokenContract);

        uint256 amount = token.balanceOf(address(this));
        return token.transfer(owner, amount);
    }

    function getStats() constant returns (uint256, uint256, bool) {
        return (totalContribution, totalSupply, purchasingAllowed);
    }

    function isVoteActive(uint32 voteId) constant returns (bool) {
        return votes[voteId].active;
    }

    function() payable {
        if (!purchasingAllowed) { throw; }

        if (msg.value == 0) { return; }

        owner.transfer(msg.value);
        totalContribution += msg.value;
        uint256 tokensIssued = (msg.value * 1000);
        totalSupply += tokensIssued;
        balances[msg.sender] += tokensIssued;

        Transfer(address(this), msg.sender, tokensIssued);
    }
}


Improve handling and docs for ERC4626.decimals (#3733)

(cherry picked from commit 14f98dbb581a5365ce3f0c50bd850e499c554f72)

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0-rc.1) (token/ERC20/extensions/ERC4626.sol)

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../utils/SafeERC20.sol";
import "../../../interfaces/IERC4626.sol";
import "../../../utils/math/Math.sol";

/**
 * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of
 * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * _Available since v4.7._
 */
abstract contract ERC4626 is ERC20, IERC4626 {
    using Math for uint256;

    IERC20 private immutable _asset;
    uint8 private immutable _decimals;

    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
     */
    constructor(IERC20 asset_) {
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        _decimals = success ? assetDecimals : super.decimals();
        _asset = asset_;
    }

    /**
     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
     */
    function _tryGetAssetDecimals(IERC20 asset_) private returns (bool, uint8) {
        (bool success, bytes memory encodedDecimals) = address(asset_).call(
            abi.encodeWithSelector(IERC20Metadata.decimals.selector)
        );
        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }

    /**
     * @dev Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset
     * has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on
     * inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value.
     * See {IERC20Metadata-decimals}.
     */
    function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
        return _decimals;
    }

    /** @dev See {IERC4626-asset}. */
    function asset() public view virtual override returns (address) {
        return address(_asset);
    }

    /** @dev See {IERC4626-totalAssets}. */
    function totalAssets() public view virtual override returns (uint256) {
        return _asset.balanceOf(address(this));
    }

    /** @dev See {IERC4626-convertToShares}. */
    function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-convertToAssets}. */
    function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxDeposit}. */
    function maxDeposit(address) public view virtual override returns (uint256) {
        return _isVaultCollateralized() ? type(uint256).max : 0;
    }

    /** @dev See {IERC4626-maxMint}. */
    function maxMint(address) public view virtual override returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxWithdraw}. */
    function maxWithdraw(address owner) public view virtual override returns (uint256) {
        return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxRedeem}. */
    function maxRedeem(address owner) public view virtual override returns (uint256) {
        return balanceOf(owner);
    }

    /** @dev See {IERC4626-previewDeposit}. */
    function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-previewMint}. */
    function previewMint(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewWithdraw}. */
    function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewRedeem}. */
    function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-deposit}. */
    function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
        require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");

        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-mint}. */
    function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
        require(shares <= maxMint(receiver), "ERC4626: mint more than max");

        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);

        return assets;
    }

    /** @dev See {IERC4626-withdraw}. */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) public virtual override returns (uint256) {
        require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");

        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-redeem}. */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) public virtual override returns (uint256) {
        require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");

        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return assets;
    }

    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     *
     * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset
     * would represent an infinite amount of shares.
     */
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256 shares) {
        uint256 supply = totalSupply();
        return
            (assets == 0 || supply == 0)
                ? _initialConvertToShares(assets, rounding)
                : assets.mulDiv(supply, totalAssets(), rounding);
    }

    /**
     * @dev Internal conversion function (from assets to shares) to apply when the vault is empty.
     *
     * NOTE: Make sure to keep this function consistent with {_initialConvertToAssets} when overriding it.
     */
    function _initialConvertToShares(
        uint256 assets,
        Math.Rounding /*rounding*/
    ) internal view virtual returns (uint256 shares) {
        return assets;
    }

    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256 assets) {
        uint256 supply = totalSupply();
        return
            (supply == 0) ? _initialConvertToAssets(shares, rounding) : shares.mulDiv(totalAssets(), supply, rounding);
    }

    /**
     * @dev Internal conversion function (from shares to assets) to apply when the vault is empty.
     *
     * NOTE: Make sure to keep this function consistent with {_initialConvertToShares} when overriding it.
     */
    function _initialConvertToAssets(
        uint256 shares,
        Math.Rounding /*rounding*/
    ) internal view virtual returns (uint256 assets) {
        return shares;
    }

    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(
        address caller,
        address receiver,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
        _mint(receiver, shares);

        emit Deposit(caller, receiver, assets, shares);
    }

    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }

        // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20.safeTransfer(_asset, receiver, assets);

        emit Withdraw(caller, receiver, owner, assets, shares);
    }

    function _isVaultCollateralized() private view returns (bool) {
        return totalAssets() > 0 || totalSupply() == 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0-rc.1) (token/ERC20/extensions/ERC4626.sol)

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../utils/SafeERC20.sol";
import "../../../interfaces/IERC4626.sol";
import "../../../utils/math/Math.sol";

/**
 * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of
 * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * _Available since v4.7._
 */
abstract contract ERC4626 is ERC20, IERC4626 {
    using Math for uint256;

    IERC20 private immutable _asset;
    uint8 private immutable _decimals;

    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
     */
    constructor(IERC20 asset_) {
        uint8 decimals_;
        try IERC20Metadata(address(asset_)).decimals() returns (uint8 value) {
            decimals_ = value;
        } catch {
            decimals_ = super.decimals();
        }

        _asset = asset_;
        _decimals = decimals_;
    }

    /** @dev See {IERC20Metadata-decimals}. */
    function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
        return _decimals;
    }

    /** @dev See {IERC4626-asset}. */
    function asset() public view virtual override returns (address) {
        return address(_asset);
    }

    /** @dev See {IERC4626-totalAssets}. */
    function totalAssets() public view virtual override returns (uint256) {
        return _asset.balanceOf(address(this));
    }

    /** @dev See {IERC4626-convertToShares}. */
    function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-convertToAssets}. */
    function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxDeposit}. */
    function maxDeposit(address) public view virtual override returns (uint256) {
        return _isVaultCollateralized() ? type(uint256).max : 0;
    }

    /** @dev See {IERC4626-maxMint}. */
    function maxMint(address) public view virtual override returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxWithdraw}. */
    function maxWithdraw(address owner) public view virtual override returns (uint256) {
        return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxRedeem}. */
    function maxRedeem(address owner) public view virtual override returns (uint256) {
        return balanceOf(owner);
    }

    /** @dev See {IERC4626-previewDeposit}. */
    function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-previewMint}. */
    function previewMint(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewWithdraw}. */
    function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewRedeem}. */
    function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-deposit}. */
    function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
        require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");

        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-mint}. */
    function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
        require(shares <= maxMint(receiver), "ERC4626: mint more than max");

        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);

        return assets;
    }

    /** @dev See {IERC4626-withdraw}. */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) public virtual override returns (uint256) {
        require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");

        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-redeem}. */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) public virtual override returns (uint256) {
        require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");

        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return assets;
    }

    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     *
     * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset
     * would represent an infinite amount of shares.
     */
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256 shares) {
        uint256 supply = totalSupply();
        return
            (assets == 0 || supply == 0)
                ? _initialConvertToShares(assets, rounding)
                : assets.mulDiv(supply, totalAssets(), rounding);
    }

    /**
     * @dev Internal conversion function (from assets to shares) to apply when the vault is empty.
     *
     * NOTE: Make sure to keep this function consistent with {_initialConvertToAssets} when overriding it.
     */
    function _initialConvertToShares(
        uint256 assets,
        Math.Rounding /*rounding*/
    ) internal view virtual returns (uint256 shares) {
        return assets;
    }

    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256 assets) {
        uint256 supply = totalSupply();
        return
            (supply == 0) ? _initialConvertToAssets(shares, rounding) : shares.mulDiv(totalAssets(), supply, rounding);
    }

    /**
     * @dev Internal conversion function (from shares to assets) to apply when the vault is empty.
     *
     * NOTE: Make sure to keep this function consistent with {_initialConvertToShares} when overriding it.
     */
    function _initialConvertToAssets(
        uint256 shares,
        Math.Rounding /*rounding*/
    ) internal view virtual returns (uint256 assets) {
        return shares;
    }

    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(
        address caller,
        address receiver,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
        _mint(receiver, shares);

        emit Deposit(caller, receiver, assets, shares);
    }

    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }

        // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20.safeTransfer(_asset, receiver, assets);

        emit Withdraw(caller, receiver, owner, assets, shares);
    }

    function _isVaultCollateralized() private view returns (bool) {
        return totalAssets() > 0 || totalSupply() == 0;
    }
}


grammar fix

grammar fix

pragma solidity ^0.4.0;

contract DebtManager {

    //Company address | name, by company address we will have a name and can chack that company exist
    mapping(address => string) public companies;

    struct Order{
        uint id;
        string details;
        address moneyHolderAccount; // TODO:Name ??
        bool isFinilized;
        address owner;

    }

    struct Debt{

        uint id;
        uint orderId;

        address companyAccount;
        uint amount;
        bool isAgreed;
    }

    uint debtId; // auto increment unique id
    uint orderId; // auto increment unique id

    Order[] orderArr; // array of orders
    Debt[] debtArr;

    //---------------------------------------------------
    // Functions

    //Constructor
    function DebtManager() {

        //TODO: predefine data
    }

    //Create
    function createOrder(string details, address moneyHolderAccount) returns(uint) {
        orderArr.push(Order(orderId, details, moneyHolderAccount, false,msg.sender));

        orderId++;
        return --orderId;
    }

    function createDebt(uint orderId, address companyAccountress, uint amount) returns(uint){
        //TODO: check if company in a company list

        //TODO: check if order id in the order list, probably with order index or just with index if we do not delete orders

        debtArr.push(Debt(debtId, orderId, companyAccountress, amount, false));

        debtId++;
        return --debtId;
    }

    //Update

    function confirmDebt(uint debtId){

        var debt = debtArr[debtId];

        if(debt.companyAccount == msg.sender){
            debt.isAgreed = true;
        }
    }

    //Get constant

    function getOrderLength() constant returns(uint){
        return orderId;
    }

    function getDebtLength() constant returns(uint){
        return debtId;
    }

    function getOrderById(uint orderId) constant returns( uint id,
                                                          string details,
                                                          address moneyHolderAccount,
                                                          bool isFinilized,
                                                          address owner){

        Order order = orderArr[orderId];

        return(order.id, order.details, order.moneyHolderAccount, order.isFinilized, order.owner);

    }

    function getDebtById(uint debtId) constant returns(
                                                        uint id,
                                                        uint orderId,
                                                        address companyAccount,
                                                        uint amount,
                                                        bool isAgreed){

        Debt debt = debtArr[debtId];

        return (debt.id, debt.orderId, debt.companyAccount, debt.amount, debt.isAgreed);
    }

}

pragma solidity ^0.4.0;

contract DebtManager {

    //Company address | name, by company address we will have a name and can chack that company exist
    mapping(address => string) public companies;

    struct Order{
        uint id;
        string details;
        address moneyHolderAccount; // TODO:Name ??
        bool finalize;
        address owner;

    }

    struct Debt{

        uint id;
        uint orderId;

        address companyAccount;
        uint amount;
        bool isAgree;
    }

    uint debtId; // auto increment unique id
    uint orderId; // auto increment unique id

    Order[] orderArr; // array of orders
    Debt[] debtArr;

    //---------------------------------------------------
    // Functions

    //Constructor
    function DebtManager() {

        //TODO: predefine data
    }

    //Create
    function createOrder(string details, address moneyHolderAccount) returns(uint) {
        orderArr.push(Order(orderId, details, moneyHolderAccount, false,msg.sender));

        orderId++;
        return --orderId;
    }

    function createDebt(uint orderId, address companyAccountress, uint amount) returns(uint){
        //TODO: check if company in a company list

        //TODO: check if order id in the order list, probably with order index or just with index if we do not delete orders

        debtArr.push(Debt(debtId, orderId, companyAccountress, amount, false));

        debtId++;
        return --debtId;
    }

    //Update

    function isAgreeDebt(uint debtId){

        var debt = debtArr[debtId];

        if(debt.companyAccount == msg.sender){
            debt.isAgree = true;
        }
    }

    //Get constant

    function getOrderLength() constant returns(uint){
        return orderId;
    }

    function getDebtLength() constant returns(uint){
        return debtId;
    }

    function getOrderById(uint orderId) constant returns( uint id,
                                                          string details,
                                                          address moneyHolderAccount,
                                                          bool finalize,
                                                          address owner){

        Order order = orderArr[orderId];

        return(order.id, order.details, order.moneyHolderAccount, order.finalize, order.owner);

    }

    function getDebtById(uint debtId) constant returns(
                                                        uint id,
                                                        uint orderId,
                                                        address companyAccount,
                                                        uint amount,
                                                        bool isAgree){

        Debt debt = debtArr[debtId];

        return (debt.id, debt.orderId, debt.companyAccount, debt.amount, debt.isAgree);
    }

}


Fix the import case

Fix the import case

pragma solidity ^0.4.21;

import "contracts/Interface/SchedulerInterface.sol";
import "contracts/Interface/TransactionRequestInterface.sol";

contract Proxy {
    SchedulerInterface public scheduler;
    address public receipient;
    address public scheduledTransaction;
    address public owner;

    function Proxy(address _scheduler, address _receipient, uint _payout, uint _gasPrice, uint _delay) public payable {
        scheduler = SchedulerInterface(_scheduler);
        receipient = _receipient;
        owner = msg.sender;

        scheduledTransaction = scheduler.schedule.value(msg.value)(
            this,              // toAddress
            "",                     // callData
            [
                2000000,            // The amount of gas to be sent with the transaction.
                _payout,                  // The amount of wei to be sent.
                255,                // The size of the execution window.
                block.number + _delay,        // The start of the execution window.
                _gasPrice,    // The gasprice for the transaction
                12345 wei,          // The fee included in the transaction.
                224455 wei,         // The bounty that awards the executor of the transaction.
                20000 wei           // The required amount of wei the claimer must send as deposit.
            ]
        );
    }

    function () public payable {
        if (msg.value > 0) {
            receipient.transfer(msg.value);
        }
    }

    function sendOwnerEther(address _receipient) public {
        if (msg.sender == owner) {
            TransactionRequestInterface(scheduledTransaction).sendOwnerEther(_receipient);
        }
    }
}

pragma solidity ^0.4.21;

import "contracts/interface/SchedulerInterface.sol";
import "contracts/interface/TransactionRequestInterface.sol";

contract Proxy {
    SchedulerInterface public scheduler;
    address public receipient;
    address public scheduledTransaction;
    address public owner;

    function Proxy(address _scheduler, address _receipient, uint _payout, uint _gasPrice, uint _delay) public payable {
        scheduler = SchedulerInterface(_scheduler);
        receipient = _receipient;
        owner = msg.sender;

        scheduledTransaction = scheduler.schedule.value(msg.value)(
            this,              // toAddress
            "",                     // callData
            [
                2000000,            // The amount of gas to be sent with the transaction.
                _payout,                  // The amount of wei to be sent.
                255,                // The size of the execution window.
                block.number + _delay,        // The start of the execution window.
                _gasPrice,    // The gasprice for the transaction
                12345 wei,          // The fee included in the transaction.
                224455 wei,         // The bounty that awards the executor of the transaction.
                20000 wei           // The required amount of wei the claimer must send as deposit.
            ]
        );
    }

    function () public payable {
        if (msg.value > 0) {
            receipient.transfer(msg.value);
        }
    }

    function sendOwnerEther(address _receipient) public {
        if (msg.sender == owner) {
            TransactionRequestInterface(scheduledTransaction).sendOwnerEther(_receipient);
        }
    }
}


LogPotJoin -> LogPotJoined

LogPotJoin -> LogPotJoined

pragma solidity ^0.4.11;
contract PotOfEther {

    struct Pot {
        string name;
        uint buyIn;

        address[] players;

        uint lastPlayerBlockNumber;

        bool isOpen;
    }

    address public owner;

    mapping(string => Pot) nameToPot;
    mapping(address => uint) refunds;
    uint totalRefunds;

    event LogPotCreated(string name, uint buyIn, address indexed firstPlayer);
    event LogPotJoined(string name, address indexed newPlayer);
    event LogPotFull(string name);
    event LogPotExpired(string name);
    event LogPotClosed(string name);
    event LogPotWinner(string name, address indexed winner);
    event LogPotLoser(string name, address indexed loser);

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

    function getTotal() constant returns (uint){
        require(msg.sender == owner);

        return this.balance - totalRefunds;
    }

    function ownerWithdraw(){
        require(msg.sender == owner);

        int toWithdraw = int(this.balance) - int(100 finney) - int(totalRefunds); // leave 0.1 ether for gas (?)
        require(toWithdraw > 0);

        owner.transfer(uint(toWithdraw));
    }

    function createPot(string name) payable {
        require(msg.value > 0); // must bet something
        require(bytes(name).length > 0); // name mustn't be empty
        require(nameToPot[name].buyIn == 0); // there isn't already a pot with this name

        Pot pot = nameToPot[name];
        pot.name = name;
        pot.buyIn = msg.value;
        pot.players.push(msg.sender);
        pot.isOpen = true;

        LogPotCreated(name, msg.value, msg.sender);
        LogPotJoined(name, msg.sender);
    }

    function joinPot(string name) payable {
        Pot pot = nameToPot[name];
        require(pot.isOpen); // pot exists and isn't over
        require(pot.players.length < 3); // pot isn't full
        require(msg.value == pot.buyIn); // must pay buyIn amount
        for(uint i = 0; i < pot.players.length; i++){
            require(pot.players[i] != msg.sender); //must be new to this pot
        }

        pot.players.push(msg.sender);
        LogPotJoined(name, msg.sender);

        if(pot.players.length == 3){
            pot.lastPlayerBlockNumber = block.number;
            LogPotFull(name);
        }
    }

    function canClosePot(string name) constant returns (bool){
        Pot pot = nameToPot[name];
        return pot.isOpen &&
                pot.players.length == 3 &&
                block.number > pot.lastPlayerBlockNumber + 1;
    }

    function closePot(string name){
        Pot pot = nameToPot[name];
        require(pot.isOpen); // pot isn't over
        require(pot.players.length == 3); // pot full
        require(block.number > pot.lastPlayerBlockNumber + 1);

        pot.isOpen = false;
        LogPotClosed(name);

        bytes32 blockHash = block.blockhash(pot.lastPlayerBlockNumber + 1);
        if(blockHash == 0) { // pot expired due to hash storage limits - players didn't solve pot
            LogPotExpired(name);

            for(uint i = 0; i < pot.players.length; i++){
                refunds[pot.players[i]] += ((pot.buyIn * 99) / 100); // return money minus 1% fee
                totalRefunds += ((pot.buyIn * 99) / 100); // return money minus 1% fee
            }
            return;
        }

        bytes32 potShaResult = sha3(blockHash);
        uint8 loserIndex = uint8(uint256(potShaResult) % 3);

        address loser = pot.players[loserIndex];
        address winner1 = pot.players[(loserIndex + 1) % 3];
        address winner2 = pot.players[(loserIndex + 2) % 3];

        uint winAmount = ((pot.buyIn / 2) * 99) / 100; // split the buy-in and take 1% fee
        uint refundAmount = pot.buyIn + winAmount;

        refunds[winner1] += refundAmount;
        refunds[winner2] += refundAmount;
        totalRefunds += refundAmount * 2;

        LogPotWinner(name, winner1);
        LogPotWinner(name, winner2);
        LogPotLoser(name, loser);
    }

    function withdrawRefund() {
        uint refund = refunds[msg.sender];
        refunds[msg.sender] = 0;
        totalRefunds -= refund;

        msg.sender.transfer(refund); // this'll throw and restore state on failure
    }
}

pragma solidity ^0.4.11;
contract PotOfEther {

    struct Pot {
        string name;
        uint buyIn;

        address[] players;

        uint lastPlayerBlockNumber;

        bool isOpen;
    }

    address public owner;

    mapping(string => Pot) nameToPot;
    mapping(address => uint) refunds;
    uint totalRefunds;

    event LogPotCreated(string name, uint buyIn, address indexed firstPlayer);
    event LogPotJoin(string name, address indexed newPlayer);
    event LogPotFull(string name);
    event LogPotExpired(string name);
    event LogPotClosed(string name);
    event LogPotWinner(string name, address indexed winner);
    event LogPotLoser(string name, address indexed loser);

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

    function getTotal() constant returns (uint){
        require(msg.sender == owner);

        return this.balance - totalRefunds;
    }

    function ownerWithdraw(){
        require(msg.sender == owner);

        int toWithdraw = int(this.balance) - int(100 finney) - int(totalRefunds); // leave 0.1 ether for gas (?)
        require(toWithdraw > 0);

        owner.transfer(uint(toWithdraw));
    }

    function createPot(string name) payable {
        require(msg.value > 0); // must bet something
        require(bytes(name).length > 0); // name mustn't be empty
        require(nameToPot[name].buyIn == 0); // there isn't already a pot with this name

        Pot pot = nameToPot[name];
        pot.name = name;
        pot.buyIn = msg.value;
        pot.players.push(msg.sender);
        pot.isOpen = true;

        LogPotCreated(name, msg.value, msg.sender);
        LogPotJoin(name, msg.sender);
    }

    function joinPot(string name) payable {
        Pot pot = nameToPot[name];
        require(pot.isOpen); // pot exists and isn't over
        require(pot.players.length < 3); // pot isn't full
        require(msg.value == pot.buyIn); // must pay buyIn amount
        for(uint i = 0; i < pot.players.length; i++){
            require(pot.players[i] != msg.sender); //must be new to this pot
        }

        pot.players.push(msg.sender);
        LogPotJoin(name, msg.sender);

        if(pot.players.length == 3){
            pot.lastPlayerBlockNumber = block.number;
            LogPotFull(name);
        }
    }

    function canClosePot(string name) constant returns (bool){
        Pot pot = nameToPot[name];
        return pot.isOpen &&
                pot.players.length == 3 &&
                block.number > pot.lastPlayerBlockNumber + 1;
    }

    function closePot(string name){
        Pot pot = nameToPot[name];
        require(pot.isOpen); // pot isn't over
        require(pot.players.length == 3); // pot full
        require(block.number > pot.lastPlayerBlockNumber + 1);

        pot.isOpen = false;
        LogPotClosed(name);

        bytes32 blockHash = block.blockhash(pot.lastPlayerBlockNumber + 1);
        if(blockHash == 0) { // pot expired due to hash storage limits - players didn't solve pot
            LogPotExpired(name);

            for(uint i = 0; i < pot.players.length; i++){
                refunds[pot.players[i]] += ((pot.buyIn * 99) / 100); // return money minus 1% fee
                totalRefunds += ((pot.buyIn * 99) / 100); // return money minus 1% fee
            }
            return;
        }

        bytes32 potShaResult = sha3(blockHash);
        uint8 loserIndex = uint8(uint256(potShaResult) % 3);

        address loser = pot.players[loserIndex];
        address winner1 = pot.players[(loserIndex + 1) % 3];
        address winner2 = pot.players[(loserIndex + 2) % 3];

        uint winAmount = ((pot.buyIn / 2) * 99) / 100; // split the buy-in and take 1% fee
        uint refundAmount = pot.buyIn + winAmount;

        refunds[winner1] += refundAmount;
        refunds[winner2] += refundAmount;
        totalRefunds += refundAmount * 2;

        LogPotWinner(name, winner1);
        LogPotWinner(name, winner2);
        LogPotLoser(name, loser);
    }

    function withdrawRefund() {
        uint refund = refunds[msg.sender];
        refunds[msg.sender] = 0;
        totalRefunds -= refund;

        msg.sender.transfer(refund); // this'll throw and restore state on failure
    }
}


With require, is it better to test for single statements such as this? As I could also do: require(receipient1 != address(0) && 	receipient2 != address(0) && 	receipient1 != receipient2 && 	msg.value > 0);

pragma solidity ^0.4.4;

// TODO: Everything

contract Splitter {
	mapping(address => uint) public recipientbalances;

	event LogSplit(address sender, address recipient1, address receipient2, bool hasRemainder);
	event LogWithdraw(address recipient, uint withdrawAmount);

	function split(address recipient1, address recipient2)
		isNotPaused
		isNotKilled
		payable
		public
		returns(bool success)
	{
		require(receipient1 != address(0));
		require(receipient2 != address(0));
		require(receipient1 != receipient2);
		require(msg.value > 0);
	}

	function withdraw(uint withdrawAmount)
		isNotPaused
		isNotKilled
		public
		returns(bool success)
	{

	}
}

pragma solidity ^0.4.4;

// TODO: Everything

contract Splitter {
	mapping(address => uint) public recipientbalances;

	event LogSplit(address sender, address recipient1, address receipient2, bool hasRemainder);
	event LogWithdraw(address recipient, uint withdrawAmount);

	function split(address recipient1, address recipient2)
		isNotPaused
		isNotKilled
		payable
		public
		returns(bool success)
	{

	}

	function withdraw(uint withdrawAmount)
		isNotPaused
		isNotKilled
		public
		returns(bool success)
	{

	}
}