add goverment

add goverment

contract token {
    address public creator;
    string public symbol;
    string public name;
    uint public baseUnit;
    uint totalSupply;
    mapping (address => uint) balanceOf;
    mapping (address => mapping(address => bool)) approveOf;
    mapping (address => mapping(address => bool)) approveOnceOf;
    mapping (address => mapping(address => uint)) approveOnceValueOf;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Events */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event AddressApproval(address indexed _address, address indexed _proxy, bool _result);
    event AddressApprovalOnce(address indexed _address, address indexed _proxy, uint256 _value);

    /*Initial */
    function token(string _s, string _n, uint _unit) {
        creator = msg.sender;
        symbol = _s;
        name = _n;
        baseUnit = _unit;
    }

    /* Creator functions */
    function getTotalSupply()  creatorCheck returns (uint supply) {
        return totalSupply;
    }

    function emmision(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] + _amount < balanceOf[creator]) {return false;}
        balanceOf[creator] += _amount;
        totalSupply += _amount;
        return true;
    }

    function burn(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] < _amount) {return false;}
        if (balanceOf[msg.sender] + _amount < balanceOf[msg.sender]) {return false;}
        balanceOf[creator] -= _amount;
        totalSupply -= _amount;
        return true;
    }

    /* Agent function */

    function myBalance() returns (uint256 balance) {
        balance = balanceOf[msg.sender];
        return balance;
    }

    function transfer(address _to, uint256 _value) returns (bool result) {
        if (balanceOf[msg.sender] < _value) {return false;}
        if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) {return false;}
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        if(approveOf[_from][msg.sender])
        {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else if(approveOnceOf[_from][msg.sender] && approveOnceValueOf[_from][msg.sender]<=_value) {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        }
    }

    function approve(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = true;
        AddressApproval(_address, msg.sender, true);
        return true;
    }

    function unapprove(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

    function approveOnce(address _address, uint _maxValue) returns (bool result) {
        approveOnceOf[msg.sender][_address] = true;
        approveOnceValueOf[msg.sender][_address] = _maxValue;
        AddressApprovalOnce(_address, msg.sender, _maxValue);
        return true;
    }

    function unapproveOnce(address _address) returns (bool result) {
        approveOnceOf[msg.sender][_address] = false;
        approveOnceValueOf[msg.sender][_address] = 0;
        return true;
    }

    function isApprovedOnceFor(address _target, address _proxy) returns (uint maxValue) {
        maxValue = approveOnceValueOf[_target][_proxy];
        return maxValue;
    }

    function isApprovedFor(address _target, address _proxy) constant returns (bool result) {
        result = approveOnceOf[_target][_proxy];
        return result;
    }
}

contract agent {
    address creator;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Struct */
    AgentContract[] public agentContracts;

    struct AgentContract {
        address agentContractAddr;
        string abi;
        string helper;
    }

    /* Functions */
    function agent() {
        creator = msg.sender;
    }

    function setAgentContract(address _agentContractAddr, string _abi, string _helper) creatorCheck returns(uint agentContractID) {
        agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _agentContractAddr;
        a.abi = _abi;
        a.helper = _helper;
        return (agentContractID);
    }
}

contract marketAgent is agent {
    market agentMarket;
    token credit;

    modifier creatorCheck { if (msg.sender == creator) _ }

    function marketAgent(address _marketAddr, string _marketAbi, string _marketHelper) {
        creator = msg.sender;
        agentMarket = market(_marketAddr);
        credit.approve(agentMarket);

        uint agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _marketAddr;
        a.abi = _marketAbi;
        a.helper = _marketHelper;
    }

    function approveSupply(token _asset, uint _maxValue) creatorCheck returns(bool result) {
        token asset = token(_asset);
        result = asset.approveOnce(agentMarket, _maxValue);
        return result;
    }
}

contract market {
    address creator;
    token credit;

    struct Order {
        uint orderID;
        address owner;
        uint total;
        uint unitPrice;
        uint min;
        uint step;
        bool active;
    }

    struct SaleAssetList {
        address assetAddr;
        Order[] sellOrderList;
    }

    struct BuyAssetList {
        address assetAddr;
        Order[] buyOrderList;
    }

    SaleAssetList[] public sellAssetList;
    Order[] public sellOrderList;
    mapping (address => bool) public sellExistOf;
    mapping (address => uint) public sellDataOf;

    BuyAssetList[] public buyAssetList;
    Order[] public buyOrderList;
    mapping (address => bool) public buyExistOf;
    mapping (address => uint) public buyDataOf;

    function market(address _credit) {
        creator = msg.sender;
        credit = token(_credit);
    }

    function getSell(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (sellExistOf[_assetAddr]) {
            uint assetID = sellDataOf[_assetAddr];
            Order order = sellAssetList[assetID].sellOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }

    function getBuy(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (buyExistOf[_assetAddr]) {
            uint assetID = buyDataOf[_assetAddr];
            Order order = buyAssetList[assetID].buyOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }
}

contract goverment {
    address creator;
    token share;

    mapping (address => bool) public banAssetOf;
    mapping (address => bool) public banAgentOf;

    function goverment(string _s, string _n, uint _unit) {
        creator = msg.sender;
        share = new token(_s, _n, _unit);
    }

    struct marketDeal {
        address asset;
        address seller;
        address buyer;
        uint amount;
        uint pricel
    }

    struct Rule {
        address creator;
        uint emmision;
        uint burn;
        uint positive;
        uint negative;

    }

    function setProposal();
    function setRule();
    function executeRule(address _rule) {
        executingRule = rule(_rule)
    }
}

contract institute {

}

contract DAO {
    address public creator;
    token public share;
    token public credit;
    market public daoMarket;
    goverment public daoGoverment;

    function DAO() {
        creator = msg.sender;
        share = new token();
        credit = new token();
        daoMarket = new market(credit);
        daoGoverment = new goverment();
    }

}

contract token {
    address public creator;
    string public symbol;
    string public name;
    uint public baseUnit;
    uint totalSupply;
    mapping (address => uint) balanceOf;
    mapping (address => mapping(address => bool)) approveOf;
    mapping (address => mapping(address => bool)) approveOnceOf;
    mapping (address => mapping(address => uint)) approveOnceValueOf;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Events */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event AddressApproval(address indexed _address, address indexed _proxy, bool _result);
    event AddressApprovalOnce(address indexed _address, address indexed _proxy, uint256 _value);

    /*Initial */
    function token() {
        creator = msg.sender;
    }

    /* Creator functions */
    function setSymbol(string _s) creatorCheck returns(bool result) {
        symbol = _s;
        return true;
    }

    function setName(string _n) creatorCheck returns(bool result) {
        name = _n;
        return true;
    }

    function setBaseUnit(uint _unit) creatorCheck returns(bool result) {
        baseUnit = _unit;
        return true;
    }

    function getTotalSupply()  creatorCheck returns (uint supply) {
        return totalSupply;
    }

    function emmision(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] + _amount < balanceOf[creator]) {return false;}
        balanceOf[creator] += _amount;
        totalSupply += _amount;
        return true;
    }

    function burn(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] < _amount) {return false;}
        if (balanceOf[msg.sender] + _amount < balanceOf[msg.sender]) {return false;}
        balanceOf[creator] -= _amount;
        totalSupply += _amount;
        return true;
    }

    /* Agent function */

    function myBalance() returns (uint256 balance) {
        balance = balanceOf[msg.sender];
        return balance;
    }

    function transfer(address _to, uint256 _value) returns (bool result) {
        if (balanceOf[msg.sender] < _value) {return false;}
        if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) {return false;}
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        if(approveOf[_from][msg.sender])
        {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else if(approveOnceOf[_from][msg.sender] && approveOnceValueOf[_from][msg.sender]<=_value) {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        }
    }

    function approve(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = true;
        AddressApproval(_address, msg.sender, true);
        return true;
    }

    function unapprove(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

    function approveOnce(address _address, uint _maxValue) returns (bool result) {
        approveOnceOf[msg.sender][_address] = true;
        approveOnceValueOf[msg.sender][_address] = _maxValue;
        AddressApprovalOnce(_address, msg.sender, _maxValue);
        return true;
    }

    function unapproveOnce(address _address) returns (bool result) {
        approveOnceOf[msg.sender][_address] = false;
        approveOnceValueOf[msg.sender][_address] = 0;
        return true;
    }

    function isApprovedOnceFor(address _target, address _proxy) returns (uint maxValue) {
        maxValue = approveOnceValueOf[_target][_proxy];
        return maxValue;
    }

    function isApprovedFor(address _target, address _proxy) constant returns (bool result) {
        result = approveOnceOf[_target][_proxy];
        return result;
    }
}

contract agent {
    address creator;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Struct */
    AgentContract[] public agentContracts;

    struct AgentContract {
        address agentContractAddr;
        string abi;
        string helper;
    }

    /* Functions */
    function agent() {
        creator = msg.sender;
    }

    function setAgentContract(address _agentContractAddr, string _abi, string _helper) creatorCheck returns(uint agentContractID) {
        agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _agentContractAddr;
        a.abi = _abi;
        a.helper = _helper;
        return (agentContractID);
    }
}

contract marketAgent is agent {
    market agentMarket;
    token credit;

    modifier creatorCheck { if (msg.sender == creator) _ }

    function marketAgent(address _marketAddr, string _marketAbi, string _marketHelper) {
        creator = msg.sender;
        agentMarket = market(_marketAddr);
        credit.approve(agentMarket);

        uint agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _marketAddr;
        a.abi = _marketAbi;
        a.helper = _marketHelper;
    }

    function approveSupply(token _asset, uint _maxValue) creatorCheck returns(bool result) {
        token asset = token(_asset);
        result = asset.approveOnce(agentMarket, _maxValue);
        return result;
    }
}

contract market {
    address creator;
    token credit;

    struct Order {
        uint orderID;
        address owner;
        uint total;
        uint unitPrice;
        uint min;
        uint step;
        bool active;
    }

    struct SaleAssetList {
        address assetAddr;
        Order[] sellOrderList;
    }

    struct BuyAssetList {
        address assetAddr;
        Order[] buyOrderList;
    }

    SaleAssetList[] public sellAssetList;
    Order[] public sellOrderList;
    mapping (address => bool) public sellExistOf;
    mapping (address => uint) public sellDataOf;

    BuyAssetList[] public buyAssetList;
    Order[] public buyOrderList;
    mapping (address => bool) public buyExistOf;
    mapping (address => uint) public buyDataOf;

    function market(address _credit) {
        creator = msg.sender;
        credit = token(_credit);
    }

    function getSell(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (sellExistOf[_assetAddr]) {
            uint assetID = sellDataOf[_assetAddr];
            Order order = sellAssetList[assetID].sellOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }

    function getBuy(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (buyExistOf[_assetAddr]) {
            uint assetID = buyDataOf[_assetAddr];
            Order order = buyAssetList[assetID].buyOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }
}


Fixed indents

Fixed indents

pragma solidity ^0.4.11;

contract Token {
    uint256 public totalSupply;

    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        require(balanceOf[msg.sender] >= _value);            // Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]);  // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
        Transfer(msg.sender, _to, _value);                   // Notify anyone listening that this transfer took place
    }

    /* Allow another contract to spend some tokens in your behalf */
    function approve(address _spender, uint256 _value) returns (bool success) {
        allowance[msg.sender][_spender] = _value;
        return true;
    }

    /* A contract attempts to get the coins */
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        require(balanceOf[_from] >= _value);                 // Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]);  // Check for overflows
        require(_value <= allowance[_from][msg.sender]);     // Check allowance
        balanceOf[_from] -= _value;                          // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
        allowance[_from][msg.sender] -= _value;
        Transfer(_from, _to, _value);
        return true;
    }

    uint public id; /* To ensure distinct contracts for different tokens owned by the same owner */
    address public owner;
    bool public sealed = false;

    function Token(uint _id) {
        owner = msg.sender;
        id = _id;
    }

    /* Allows the owner to mint more tokens */
    function mint(address _to, uint256 _value) returns (bool) {
        require(msg.sender == owner);                        // Only the owner is allowed to mint
        require(!sealed);                                    // Can only mint while unsealed
        require(balanceOf[_to] + _value >= balanceOf[_to]);  // Check for overflows
        balanceOf[_to] += _value;
        totalSupply += _value;
        return true;
    }

    function seal() {
        require(msg.sender == owner);
        sealed = true;
    }
}

contract Withdraw {
    Token public token;

    function Withdraw(Token _token) {
        token = _token;
    }

    function () payable {}

    function withdraw() {
        require(token.sealed());
        require(token.balanceOf(msg.sender) > 0);
        uint token_amount = token.balanceOf(msg.sender);
        uint wei_amount = this.balance * token_amount / token.totalSupply();
        if (!token.transferFrom(msg.sender, this, token_amount) || !msg.sender.send(wei_amount)) {
            throw;
        }
    }
}

contract TokenGame {
    address public owner;
    uint public cap_in_wei;
    uint constant initial_duration = 7 days;
    uint constant time_extension_from_doubling = 7 days;
    uint constant time_of_half_decay = 7 days;
    Token public excess_token; /* Token contract used to receive excess after the sale */
    Withdraw excess_withdraw;  /* Withdraw contract distributing the excess */
    Token public game_token;   /* Token contract used to receive prizes */
    uint public end_time;      /* Current end time */
    uint last_time = 0;        /* Timestamp of the latest contribution */
    uint256 ema = 0;           /* Current value of the EMA */
    uint total_wei_given = 0;  /* Total amount of wei given via fallback function */

    function TokenGame(uint _cap_in_wei) {
        owner = msg.sender;
        cap_in_wei = _cap_in_wei;
        excess_token = Token(1);
        excess_withdraw = Withdraw(excess_token);
        game_token = Token(2);
        end_time = now + initial_duration;
    }

    function play() payable {
        require(now <= end_time);   // Check that the sale has not ended
        require(msg.value > 0);     // Check that something has been sent
        total_wei_given += msg.value;
        ema = msg.value + ema * time_of_half_decay / (time_of_half_decay + (now - last_time) );
        last_time = now;
        uint extended_time = now + ema * time_extension_from_doubling / total_wei_given;
        if (extended_time > end_time) {
            end_time = extended_time;
        }
        if (!excess_token.mint(msg.sender, msg.value) || !game_token.mint(msg.sender, msg.value)) {
            throw;
        }
    }

    function finalise() {
        require(now > end_time);
        excess_token.seal();
        game_token.seal();
        if (this.balance > cap_in_wei) {
            if (!excess_withdraw.send(this.balance - cap_in_wei) || !owner.send(cap_in_wei)) {
                throw;
            }
        } else {
            if (!owner.send(this.balance)) {
                throw;
            }
        }
    }
}


- Added throws whenever constraints are violated inside claimFunds method

pragma solidity ^0.4.2;

import "./priced.sol";
import "./stateMachine.sol";
import "./accessRestricted.sol";

/// @title Brehon Contract
contract BrehonContract is
    priced,
    stateMachine,
    accessRestricted {

  struct Party {
    address addr;
    uint deposit;
    bool contractAccepted;
  }

  struct Brehon {
    address addr;
    bool contractAccepted;
    uint fixedFee;
    uint disputeFee;
  }

  struct Resolution {
    address proposerAddr;
    uint awardPartyA;
    uint awardPartyB;
    bool partyAAccepted;
    bool partyBAccepted;
  }

  int8 public appealLevel;
  uint public transactionAmount;
  uint public minimumContractAmt;
  bytes32 public contractTermsHash;
  bool public settlementReached;
  Party public partyA;
  Party public partyB;
  Brehon public primaryBrehon;
  Brehon public secondaryBrehon;
  Brehon public tertiaryBrehon;
  Brehon public activeBrehon;

  mapping (address => uint) awards;
  Resolution public proposedSettlement;

  uint appealPeriodInDays = 5;
  uint public appealPeriodStartTime;

  event ExecutionStarted(address _caller, uint _totalDeposits);
  event ContractDisputed(address _disputingParty, address _activeBrehon);
  event AppealPeriodStarted(int8 _appealLevel, uint _startTime, address _activeBrehon, uint _awardPartyA, uint _awardPartyB);
  //TODO: Provide the information about the party which appaled
  event AppealRaised(int8 _appealLevel, address _activeBrehon);
  event SettlementProposed(address _proposingParty, uint _awardPartyA, uint _awardPartyB);
  event DisputeResolved(uint _awardPartyA, uint _awardPartyB);
  event FundsClaimed(address claimingParty, uint amount);

  modifier eitherByParty(Party _party1, Party _party2)
  {
    if (msg.sender != _party1.addr &&
        msg.sender != _party2.addr)
        throw;
    _;
  }

  modifier afterContractStarts()
  {
    if(stage != Stages.Execution &&
       stage != Stages.Dispute &&
       stage != Stages.AppealPeriod &&
       stage != Stages.Appeal)
        throw;
    _;
  }

  modifier eitherByBrehon(Brehon _brehon1, Brehon _brehon2, Brehon _brehon3)
  {
    if (msg.sender != _brehon1.addr ||
        msg.sender != _brehon2.addr ||
        msg.sender != _brehon3.addr)
        throw;
    _;
  }

  modifier onlyByBrehon(Brehon _brehon) {
    if (msg.sender != _brehon.addr)
        throw;
    _;
  }

  function BrehonContract(
      address _partyA,
      address _partyB,
      uint _transactionAmount,
      bytes32 _contractTermsHash,
      address _primaryBrehon,
      uint _primaryBrehonFixedFee,
      uint _primaryBrehonDisputeFee,
      address _secondaryBrehon,
      uint _secondaryBrehonFixedFee,
      uint _secondaryBrehonDisputeFee,
      address _tertiaryBrehon,
      uint _tertiaryBrehonFixedFee,
      uint _tertiaryBrehonDisputeFee
  ) {
    partyA.addr = _partyA;
    transactionAmount = _transactionAmount;
    contractTermsHash = _contractTermsHash;

    partyB.addr = _partyB;

    primaryBrehon.addr = _primaryBrehon;
    primaryBrehon.fixedFee = _primaryBrehonFixedFee;
    primaryBrehon.disputeFee = _primaryBrehonDisputeFee;

    secondaryBrehon.addr = _secondaryBrehon;
    secondaryBrehon.fixedFee = _secondaryBrehonFixedFee;
    secondaryBrehon.disputeFee = _secondaryBrehonDisputeFee;

    tertiaryBrehon.addr = _tertiaryBrehon;
    tertiaryBrehon.fixedFee = _tertiaryBrehonFixedFee;
    tertiaryBrehon.disputeFee = _tertiaryBrehonDisputeFee;

    minimumContractAmt = primaryBrehon.fixedFee + primaryBrehon.disputeFee +
        secondaryBrehon.fixedFee + secondaryBrehon.disputeFee +
        tertiaryBrehon.fixedFee + tertiaryBrehon.disputeFee +
        transactionAmount;

    //Defaults
    stage = Stages.Negotiation;
    appealLevel = -1;
    settlementReached = false;
    partyA.contractAccepted = false;
    partyA.deposit = 0;

    partyB.contractAccepted = false;
    partyB.deposit = 0;

    primaryBrehon.contractAccepted = false;
    secondaryBrehon.contractAccepted = false;
    tertiaryBrehon.contractAccepted = false;
  }

  function acceptContract()
    atStage(Stages.Negotiation)
  {
      if (msg.sender == partyA.addr) {
          partyA.contractAccepted = true;
      } else if (msg.sender == partyB.addr) {
          partyB.contractAccepted = true;
      } else if(msg.sender == primaryBrehon.addr) {
          primaryBrehon.contractAccepted = true;
      } else if(msg.sender == secondaryBrehon.addr) {
          secondaryBrehon.contractAccepted = true;
      } else if(msg.sender == tertiaryBrehon.addr) {
          tertiaryBrehon.contractAccepted = true;
      } else throw;
  }

  function deposit()
    payable
  {
      if(msg.sender == partyA.addr) {
          partyA.deposit += msg.value;
      } else if (msg.sender == partyB.addr) {
          partyB.deposit += msg.value;
      } else throw;
  }

  function startContract()
    atStage(Stages.Negotiation)
    eitherByParty(partyA, partyB)
  {
      if(!partyA.contractAccepted ||
         !partyB.contractAccepted ||
         !primaryBrehon.contractAccepted ||
         !secondaryBrehon.contractAccepted ||
         !tertiaryBrehon.contractAccepted) throw;

      if ((partyA.deposit + partyB.deposit) >=
          minimumContractAmt) {
             ExecutionStarted(msg.sender, partyA.deposit + partyB.deposit);
             stage = Stages.Execution;
      } else throw;
  }

  function raiseDispute()
    atStage(Stages.Execution)
    eitherByParty(partyA, partyB)
  {
    stage = Stages.Dispute;
    appealLevel = 0;
    activeBrehon = primaryBrehon;
    ContractDisputed(msg.sender, primaryBrehon.addr);
  }

  function adjudicate(uint _awardPartyA, uint _awardPartyB)
    atStage(Stages.Dispute)
    onlyByBrehon(activeBrehon)
  {
    if((_awardPartyA + _awardPartyB) > (partyA.deposit + partyB.deposit)) throw;

    stage = Stages.AppealPeriod;
    appealPeriodStartTime = now;

    awards[partyA.addr] = _awardPartyA;
    awards[partyB.addr] = _awardPartyB;

    AppealPeriodStarted(appealLevel, appealPeriodInDays, activeBrehon.addr, _awardPartyA, _awardPartyB);
  }

  function getActiveJudgmentByParty(address _partyAddress)
    returns (uint)
  {
      if(_partyAddress != partyA.addr &&
         _partyAddress != partyB.addr) throw;
    return awards[_partyAddress];
  }

  function claimFunds()
    timedTransition(settlementReached, appealPeriodStartTime, appealPeriodInDays, Stages.AppealPeriod, Stages.Completed)
    atStage(Stages.Completed)
    eitherByParty(partyA, partyB)
  {
    uint amount = awards[msg.sender];

    if (amount == 0) {
      throw;
    }

    if (this.balance < amount) {
      throw;
    }

    awards[msg.sender] = 0;

    if(msg.sender.send(amount)) {
      FundsClaimed(msg.sender, amount);
    } else {
      awards[msg.sender] = amount;
      throw;
    }
  }

  function raiseAppeal()
    atStage(Stages.AppealPeriod)
    eitherByParty(partyA, partyB)
  {
    stage = Stages.Dispute;
    appealLevel = 1;

    activeBrehon = secondaryBrehon;

    AppealRaised(appealLevel, activeBrehon.addr);
  }

  function raise2ndAppeal()
    atStage(Stages.AppealPeriod)
    eitherByParty(partyA, partyB)
  {
    stage = Stages.Dispute;
    appealLevel = 2;

    activeBrehon = tertiaryBrehon;

    AppealRaised(appealLevel, activeBrehon.addr);
  }

  function proposeSettlement(uint _awardPartyA, uint _awardPartyB)
    afterContractStarts()
    eitherByParty(partyA, partyB)
  {
      proposedSettlement.proposerAddr = msg.sender;
      proposedSettlement.awardPartyA = _awardPartyA;
      proposedSettlement.awardPartyB = _awardPartyB;
      if (msg.sender == partyA.addr) {
          proposedSettlement.partyAAccepted = true;
          proposedSettlement.partyBAccepted = false;
      } else if (msg.sender == partyB.addr) {
          proposedSettlement.partyAAccepted = false;
          proposedSettlement.partyBAccepted = true;
      }

      SettlementProposed(msg.sender, _awardPartyA, _awardPartyB);
  }

  function acceptSettlement(uint _awardPartyA, uint _awardPartyB)
    afterContractStarts()
    eitherByParty(partyA, partyB)
  {
      if((proposedSettlement.awardPartyA != _awardPartyA) ||
         (proposedSettlement.awardPartyB != _awardPartyB))
          throw;

      if(msg.sender == partyA.addr) {
          proposedSettlement.partyAAccepted = true;
      }

      if(msg.sender == partyB.addr) {
          proposedSettlement.partyBAccepted = true;
      }

      if(proposedSettlement.partyAAccepted && proposedSettlement.partyBAccepted) {
          awards[partyA.addr] = proposedSettlement.awardPartyA;
          awards[partyB.addr] = proposedSettlement.awardPartyB;
          stage = Stages.Completed;
          DisputeResolved(_awardPartyA, _awardPartyB);
      }
  }
}

pragma solidity ^0.4.2;

import "./priced.sol";
import "./stateMachine.sol";
import "./accessRestricted.sol";

/// @title Brehon Contract
contract BrehonContract is
    priced,
    stateMachine,
    accessRestricted {

  struct Party {
    address addr;
    uint deposit;
    bool contractAccepted;
  }

  struct Brehon {
    address addr;
    bool contractAccepted;
    uint fixedFee;
    uint disputeFee;
  }

  struct Resolution {
    address proposerAddr;
    uint awardPartyA;
    uint awardPartyB;
    bool partyAAccepted;
    bool partyBAccepted;
  }

  int8 public appealLevel;
  uint public transactionAmount;
  uint public minimumContractAmt;
  bytes32 public contractTermsHash;
  bool public settlementReached;
  Party public partyA;
  Party public partyB;
  Brehon public primaryBrehon;
  Brehon public secondaryBrehon;
  Brehon public tertiaryBrehon;
  Brehon public activeBrehon;

  mapping (address => uint) awards;
  Resolution public proposedSettlement;

  uint appealPeriodInDays = 5;
  uint public appealPeriodStartTime;

  event ExecutionStarted(address _caller, uint _totalDeposits);
  event ContractDisputed(address _disputingParty, address _activeBrehon);
  event AppealPeriodStarted(int8 _appealLevel, uint _startTime, address _activeBrehon, uint _awardPartyA, uint _awardPartyB);
  //TODO: Provide the information about the party which appaled
  event AppealRaised(int8 _appealLevel, address _activeBrehon);
  event SettlementProposed(address _proposingParty, uint _awardPartyA, uint _awardPartyB);
  event DisputeResolved(uint _awardPartyA, uint _awardPartyB);
  event FundsClaimed(address claimingParty, uint amount);

  modifier eitherByParty(Party _party1, Party _party2)
  {
    if (msg.sender != _party1.addr &&
        msg.sender != _party2.addr)
        throw;
    _;
  }

  modifier afterContractStarts()
  {
    if(stage != Stages.Execution &&
       stage != Stages.Dispute &&
       stage != Stages.AppealPeriod &&
       stage != Stages.Appeal)
        throw;
    _;
  }

  modifier eitherByBrehon(Brehon _brehon1, Brehon _brehon2, Brehon _brehon3)
  {
    if (msg.sender != _brehon1.addr ||
        msg.sender != _brehon2.addr ||
        msg.sender != _brehon3.addr)
        throw;
    _;
  }

  modifier onlyByBrehon(Brehon _brehon) {
    if (msg.sender != _brehon.addr)
        throw;
    _;
  }

  function BrehonContract(
      address _partyA,
      address _partyB,
      uint _transactionAmount,
      bytes32 _contractTermsHash,
      address _primaryBrehon,
      uint _primaryBrehonFixedFee,
      uint _primaryBrehonDisputeFee,
      address _secondaryBrehon,
      uint _secondaryBrehonFixedFee,
      uint _secondaryBrehonDisputeFee,
      address _tertiaryBrehon,
      uint _tertiaryBrehonFixedFee,
      uint _tertiaryBrehonDisputeFee
  ) {
    partyA.addr = _partyA;
    transactionAmount = _transactionAmount;
    contractTermsHash = _contractTermsHash;

    partyB.addr = _partyB;

    primaryBrehon.addr = _primaryBrehon;
    primaryBrehon.fixedFee = _primaryBrehonFixedFee;
    primaryBrehon.disputeFee = _primaryBrehonDisputeFee;

    secondaryBrehon.addr = _secondaryBrehon;
    secondaryBrehon.fixedFee = _secondaryBrehonFixedFee;
    secondaryBrehon.disputeFee = _secondaryBrehonDisputeFee;

    tertiaryBrehon.addr = _tertiaryBrehon;
    tertiaryBrehon.fixedFee = _tertiaryBrehonFixedFee;
    tertiaryBrehon.disputeFee = _tertiaryBrehonDisputeFee;

    minimumContractAmt = primaryBrehon.fixedFee + primaryBrehon.disputeFee +
        secondaryBrehon.fixedFee + secondaryBrehon.disputeFee +
        tertiaryBrehon.fixedFee + tertiaryBrehon.disputeFee +
        transactionAmount;

    //Defaults
    stage = Stages.Negotiation;
    appealLevel = -1;
    settlementReached = false;
    partyA.contractAccepted = false;
    partyA.deposit = 0;

    partyB.contractAccepted = false;
    partyB.deposit = 0;

    primaryBrehon.contractAccepted = false;
    secondaryBrehon.contractAccepted = false;
    tertiaryBrehon.contractAccepted = false;
  }

  function acceptContract()
    atStage(Stages.Negotiation)
  {
      if (msg.sender == partyA.addr) {
          partyA.contractAccepted = true;
      } else if (msg.sender == partyB.addr) {
          partyB.contractAccepted = true;
      } else if(msg.sender == primaryBrehon.addr) {
          primaryBrehon.contractAccepted = true;
      } else if(msg.sender == secondaryBrehon.addr) {
          secondaryBrehon.contractAccepted = true;
      } else if(msg.sender == tertiaryBrehon.addr) {
          tertiaryBrehon.contractAccepted = true;
      } else throw;
  }

  function deposit()
    payable
  {
      if(msg.sender == partyA.addr) {
          partyA.deposit += msg.value;
      } else if (msg.sender == partyB.addr) {
          partyB.deposit += msg.value;
      } else throw;
  }

  function startContract()
    atStage(Stages.Negotiation)
    eitherByParty(partyA, partyB)
  {
      if(!partyA.contractAccepted ||
         !partyB.contractAccepted ||
         !primaryBrehon.contractAccepted ||
         !secondaryBrehon.contractAccepted ||
         !tertiaryBrehon.contractAccepted) throw;

      if ((partyA.deposit + partyB.deposit) >=
          minimumContractAmt) {
             ExecutionStarted(msg.sender, partyA.deposit + partyB.deposit);
             stage = Stages.Execution;
      } else throw;
  }

  function raiseDispute()
    atStage(Stages.Execution)
    eitherByParty(partyA, partyB)
  {
    stage = Stages.Dispute;
    appealLevel = 0;
    activeBrehon = primaryBrehon;
    ContractDisputed(msg.sender, primaryBrehon.addr);
  }

  function adjudicate(uint _awardPartyA, uint _awardPartyB)
    atStage(Stages.Dispute)
    onlyByBrehon(activeBrehon)
  {
    if((_awardPartyA + _awardPartyB) > (partyA.deposit + partyB.deposit)) throw;

    stage = Stages.AppealPeriod;
    appealPeriodStartTime = now;

    awards[partyA.addr] = _awardPartyA;
    awards[partyB.addr] = _awardPartyB;

    AppealPeriodStarted(appealLevel, appealPeriodInDays, activeBrehon.addr, _awardPartyA, _awardPartyB);
  }

  function getActiveJudgmentByParty(address _partyAddress)
    returns (uint)
  {
      if(_partyAddress != partyA.addr &&
         _partyAddress != partyB.addr) throw;
    return awards[_partyAddress];
  }

  function claimFunds()
    timedTransition(settlementReached, appealPeriodStartTime, appealPeriodInDays, Stages.AppealPeriod, Stages.Completed)
    atStage(Stages.Completed)
    eitherByParty(partyA, partyB)
    returns (bool)
  {
    uint amount = awards[msg.sender];
    awards[msg.sender] = 0;
    if(msg.sender.send(amount)) {
      FundsClaimed(msg.sender, amount);
      return true;
    } else {
      awards[msg.sender] = amount;
      return false;
    }
  }

  function raiseAppeal()
    atStage(Stages.AppealPeriod)
    eitherByParty(partyA, partyB)
  {
    stage = Stages.Dispute;
    appealLevel = 1;

    activeBrehon = secondaryBrehon;

    AppealRaised(appealLevel, activeBrehon.addr);
  }

  function raise2ndAppeal()
    atStage(Stages.AppealPeriod)
    eitherByParty(partyA, partyB)
  {
    stage = Stages.Dispute;
    appealLevel = 2;

    activeBrehon = tertiaryBrehon;

    AppealRaised(appealLevel, activeBrehon.addr);
  }

  function proposeSettlement(uint _awardPartyA, uint _awardPartyB)
    afterContractStarts()
    eitherByParty(partyA, partyB)
  {
      proposedSettlement.proposerAddr = msg.sender;
      proposedSettlement.awardPartyA = _awardPartyA;
      proposedSettlement.awardPartyB = _awardPartyB;
      if (msg.sender == partyA.addr) {
          proposedSettlement.partyAAccepted = true;
          proposedSettlement.partyBAccepted = false;
      } else if (msg.sender == partyB.addr) {
          proposedSettlement.partyAAccepted = false;
          proposedSettlement.partyBAccepted = true;
      }

      SettlementProposed(msg.sender, _awardPartyA, _awardPartyB);
  }

  function acceptSettlement(uint _awardPartyA, uint _awardPartyB)
    afterContractStarts()
    eitherByParty(partyA, partyB)
  {
      if((proposedSettlement.awardPartyA != _awardPartyA) ||
         (proposedSettlement.awardPartyB != _awardPartyB))
          throw;

      if(msg.sender == partyA.addr) {
          proposedSettlement.partyAAccepted = true;
      }

      if(msg.sender == partyB.addr) {
          proposedSettlement.partyBAccepted = true;
      }

      if(proposedSettlement.partyAAccepted && proposedSettlement.partyBAccepted) {
          awards[partyA.addr] = proposedSettlement.awardPartyA;
          awards[partyB.addr] = proposedSettlement.awardPartyB;
          stage = Stages.Completed;
          DisputeResolved(_awardPartyA, _awardPartyB);
      }
  }
}


remove tabs

remove tabs

import './PullPaymentCapable.sol';

contract PullPaymentBid is PullPaymentCapable {
  address public highestBidder;
  uint public highestBid;

  function bid() external {
    if (msg.value <= highestBid) throw;

    if (highestBidder != 0) {
      asyncSend(highestBidder, highestBid);
    }
    highestBidder = msg.sender;
    highestBid = msg.value;
  }
}


Create etherToken.sol

Create etherToken.sol

contract etherToken {
    address public creator;
    string public symbol;
    string public name;
    uint totalSupply;
    mapping (address => uint) public balanceOf;
    mapping (address => mapping(address => bool)) approveOf;
    mapping (address => mapping(address => bool)) approveOnceOf;
    mapping (address => mapping(address => uint)) approveOnceValueOf;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Events */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event AddressApproval(address indexed _address, address indexed _proxy, bool _result);
    event AddressApprovalOnce(address indexed _address, address indexed _proxy, uint256 _value);

    /*Initial */
    function etherToken() {
        creator = msg.sender;
        symbol = "Eth";
        name = "Eth";
    }

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

    /* Agent function */

    function getBalance(address _account) returns (uint256 balance) {
		balance = 0;
        if (approveOf[_account][msg.sender]) {
			balance = balanceOf[_account];
		}
        return balance;
    }

    function myBalance() returns (uint256 balance) {
		balance = balanceOf[msg.sender];
        return balance;
    }

    function loadBalance() {
        balanceOf[msg.sender] += msg.value;
        totalSupply += msg.value;

    }

    function withdraw(uint256 _value) returns (bool result){
        if (balanceOf[msg.sender] < _value) {return false;}
        if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) {return false;}
        msg.sender.send(_value);
        return true;

    }

    function transfer(address _to, uint256 _value) returns (bool result) {
        if (balanceOf[msg.sender] < _value) {return false;}
        if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) {return false;}
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        if(approveOf[_from][msg.sender])
        {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else if(approveOnceOf[_from][msg.sender] && approveOnceValueOf[_from][msg.sender]<=_value) {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        }
    }

    function approve(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = true;
        AddressApproval(_address, msg.sender, true);
        return true;
    }

    function unapprove(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

    function approveOnce(address _address, uint _maxValue) returns (bool result) {
        approveOnceOf[msg.sender][_address] = true;
        approveOnceValueOf[msg.sender][_address] = _maxValue;
        AddressApprovalOnce(_address, msg.sender, _maxValue);
        return true;
    }

    function unapproveOnce(address _address) returns (bool result) {
        approveOnceOf[msg.sender][_address] = false;
        approveOnceValueOf[msg.sender][_address] = 0;
        return true;
    }

    function isApprovedOnceFor(address _target, address _proxy) returns (uint maxValue) {
        maxValue = approveOnceValueOf[_target][_proxy];
        return maxValue;
    }

    function isApprovedFor(address _target, address _proxy) returns (bool result) {
        result = approveOnceOf[_target][_proxy];
        return result;
    }

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

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


criado updatepokemon

criado updatepokemon

// Pokemon create template: 1,500,40,"at1",1,"at2",500
// owner "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"

contract owned {
    address public owner;
    address public market;

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

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

    modifier Market {
        if (msg.sender != market || msg.sender != owner) throw;
        _
    }

    function transferOwnership(address newOwner) onlyOwner {
        owner = newOwner;
    }

    function updateMarket(address newMarket) onlyOwner {
        market = newMarket;
    }
}

contract IssuePokemon is owned {

    uint256 public totalPokemonSupply;
    address public marketAddress;

    Pokemon[] public pokemons;
    PokemonMaster[] public pokeMasters;

    mapping (uint256 => address) public pokemonToMaster;
    mapping (address => uint256) public pokeOwnerIndex;
    mapping (uint => uint256) public pokemonIndex;
    mapping (address => uint256) public totalPokemonsFromMaster;

    struct Pokemon {
        uint pokeNumber;
        string pokeName;
        string pokeType;
        uint pokeCP;
        uint pokeHP;
        //string pokeAttack;
        //uint pokeAttackPower;
        //string pokeSpecial;
        //uint pokeSpecialPower;
        bytes32 pokemonHash;
        address pokeOwner;
    }

    struct PokemonMaster {
        address pokeMaster;
        uint[] pokemons;
    }

    string[][] public pokemonNameTypes = [["Pokemon 0", "invalid"], ["Bulbassauro", "Grass/Poison"], ["Charmander", "Fire"], ["Squirtle","Water"], ["Pikachu","Eletric"]]; // nÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂ£o aceita bytes

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address from, address to, uint256 value);
    event CreatePokemon(uint id, string name, uint cp, uint hp );
    event UpdatePokemon(uint id, string name, uint cp, uint hp );
    event UpdateMasterPokemons(address owner, uint total);
    event Log1(uint number);
    event Log2(string message);

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function IssuePokemon() {
        owner = msg.sender;
        newPokemonMaster(owner);                            // Todos pokemons serao criados para este owner
        newPokemon(0,0,0);                                  // Pokemon Índice 0
        totalPokemonSupply-=1;                              // Ajusta o total de pokemons porque o primeiro é fake

        /* Criacao de pokemons iniciais */
        newPokemon(3,500,40);
        newPokemon(1,535,70);
        newPokemon(4,546,80);
        newPokemon(2,557,90);

    }

    //function newPokemon(uint pokemonNumber, uint cp, uint hp, string attack, uint attackPower, string special, uint specialPower ) returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
    function newPokemon(uint pokemonNumber, uint cp, uint hp )  returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
        address owner = msg.sender;
        uint pokemonID = pokemons.length++;
        Pokemon p = pokemons[pokemonID];
        p.pokeNumber = pokemonNumber;
        p.pokeName = pokemonNameTypes[pokemonNumber][0];
        p.pokeType = pokemonNameTypes[pokemonNumber][1];
        p.pokeCP = cp;
        p.pokeHP = hp;
        //p.pokeAttack = attack;
        //p.pokeAttackPower = attackPower;
        //p.pokeSpecial = special;
        //p.pokeSpecialPower = specialPower;

        //p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP, p.pokeAttack, p.pokeAttackPower, p.pokeSpecial, p.pokeSpecialPower);
        p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP);
        p.pokeOwner = owner;
        pokemonIndex[pokemonNumber] = pokemonID;
        pokemonToMaster[pokemonID] = owner;
        addPokemonToMaster(owner, pokemonID);

        totalPokemonSupply += 1;
        CreatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP);
        return true;
    }

    function updatePokemon(uint _pokemonNumber, uint _cp, uint _hp )  returns (bool success) {
        uint pokemonID = pokemonIndex[_pokemonNumber];
        Pokemon p = pokemons[pokemonID];
        p.pokeCP = _cp;
        p.pokeHP = _hp;
        //p.pokeAttack = attack;
        //p.pokeAttackPower = attackPower;
        //p.pokeSpecial = special;
        //p.pokeSpecialPower = specialPower;

        //p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP, p.pokeAttack, p.pokeAttackPower, p.pokeSpecial, p.pokeSpecialPower);
        p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP);

        UpdatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP);
        return true;

    }

    function newPokemonMaster(address pokemonMaster)  returns (bool success) {
        uint ownerID = pokeMasters.length++;
        PokemonMaster o = pokeMasters[ownerID];
        o.pokeMaster = pokemonMaster;
        pokeOwnerIndex[pokemonMaster] = ownerID;
        return true;
    }

    function transferPokemon(address _from, address _to, uint256 _pokemonID)   returns (uint pokemonID, address from, address to) {
        Pokemon p = pokemons[_pokemonID];
        if (p.pokeOwner != _from) throw;
        if (pokeOwnerIndex[_to] == 0 && _to != pokemonToMaster[0] ) newPokemonMaster(_to);
        // Construir controle de acesso somente para o owner
        p.pokeOwner = _to;
        pokemonToMaster[_pokemonID] = _to;
        delPokemonFromMaster(_from, _pokemonID);
        addPokemonToMaster(_to, _pokemonID);
        Transfer(_from, _to, _pokemonID);
        return (_pokemonID, _from, _to);
    }

    function addPokemonToMaster(address _pokemonOwner, uint256 _pokemonID)  returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) {
        uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;

        // o.pokemons.push(_pokemonID);
        // usando .push ele adiciona 0,_pokemonID

        // Ao invés de simplesmente adicionar um pokemon ao final da lista,
        // verifica se há slot zerado no array, senao adiciona ao final
        bool slot;
        for (uint i=0; i < pokeList.length; i++){
            if (pokeList[i] == 0){
                slot = true;
                break;
            }
        }
        if (slot == true){
            o.pokemons[i] = _pokemonID;
        } else {
            uint j = pokeList.length++;
            o.pokemons[j] = _pokemonID;
        }

        qtdePokemons(_pokemonOwner);
        UpdateMasterPokemons(_pokemonOwner, o.pokemons.length);
        return (_pokemonOwner, o.pokemons, o.pokemons.length);
    }

    function delPokemonFromMaster(address _pokemonOwner, uint256 _pokemonID)  returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) {
        uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;

        for (uint i=0; i < pokeList.length; i++){
            if (pokeList[i] == _pokemonID){
                delete pokeList[i];
            }
        }

        // http://ethereum.stackexchange.com/questions/3373/how-to-clear-large-arrays-without-blowing-the-gas-limit
        o.pokemons=pokeList; // Se usar delete, usa a propria pokeList

        qtdePokemons(_pokemonOwner);
        UpdateMasterPokemons(_pokemonOwner, o.pokemons.length);
        return (_pokemonOwner, o.pokemons, o.pokemons.length);
    }

    function listPokemons( address _pokeOwner )  returns (address, uint[]){
        uint ownerID = pokeOwnerIndex[_pokeOwner];
        PokemonMaster o = pokeMasters[ownerID];
        return ( _pokeOwner, o.pokemons );
    }

    function qtdePokemons( address _pokeOwner)  returns (uint qtde){
        uint ownerID = pokeOwnerIndex[_pokeOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;
        uint count = 0;
        for (uint i=0; i < pokeList.length; i++){
            if ( pokeList[i] > 0 ){
                count++;
            }
        }
        totalPokemonsFromMaster[_pokeOwner] = count;
        return count;
    }

    /* Se tentarem enviar ether para o end desse contrato, ele rejeita */
    function () {
        throw;
    }
}

// Pokemon create template: 1,500,40,"at1",1,"at2",500
// owner "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"

contract owned {
    address public owner;
    address public market;

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

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

    modifier Market {
        if (msg.sender != market || msg.sender != owner) throw;
        _
    }

    function transferOwnership(address newOwner) onlyOwner {
        owner = newOwner;
    }

    function updateMarket(address newMarket) onlyOwner {
        market = newMarket;
    }
}

contract IssuePokemon is owned {

    uint256 public totalPokemonSupply;
    address public marketAddress;

    Pokemon[] public pokemons;
    PokemonMaster[] public pokeMasters;

    mapping (uint256 => address) public pokemonToMaster;
    mapping (address => uint256) public pokeOwnerIndex;
    mapping (address => uint256) public totalPokemonsFromMaster;

    struct Pokemon {
        uint pokeNumber;
        string pokeName;
        string pokeType;
        uint pokeCP;
        uint pokeHP;
        //string pokeAttack;
        //uint pokeAttackPower;
        //string pokeSpecial;
        //uint pokeSpecialPower;
        bytes32 pokemonHash;
        address pokeOwner;
    }

    struct PokemonMaster {
        address pokeMaster;
        uint[] pokemons;
    }

    string[][] public pokemonNameTypes = [["Pokemon 0", "invalid"], ["Bulbassauro", "Grass/Poison"], ["Charmander", "Fire"], ["Squirtle","Water"], ["Pikachu","Eletric"]]; // nÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂ£o aceita bytes

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address from, address to, uint256 value);
    event CreatePokemon(uint id, string name, uint cp, uint hp );
    event UpdateMasterPokemons(address owner, uint total);
    event Log1(uint number);
    event Log2(string message);

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function IssuePokemon() {
        owner = msg.sender;
        newPokemonMaster(owner);                            // Todos pokemons serao criados para este owner
        newPokemon(0,0,0);                                  // Pokemon Índice 0
        totalPokemonSupply-=1;                              // Ajusta o total de pokemons porque o primeiro é fake

        /* Criacao de pokemons iniciais */
        newPokemon(3,500,40);
        newPokemon(1,535,70);
        newPokemon(4,546,80);
        newPokemon(2,557,90);

    }

    //function newPokemon(uint pokemonNumber, uint cp, uint hp, string attack, uint attackPower, string special, uint specialPower ) returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
    function newPokemon(uint pokemonNumber, uint cp, uint hp )  returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
        address owner = msg.sender;
        uint pokemonID = pokemons.length++;
        Pokemon p = pokemons[pokemonID];
        p.pokeNumber = pokemonNumber;
        p.pokeName = pokemonNameTypes[pokemonNumber][0];
        p.pokeType = pokemonNameTypes[pokemonNumber][1];
        p.pokeCP = cp;
        p.pokeHP = hp;
        //p.pokeAttack = attack;
        //p.pokeAttackPower = attackPower;
        //p.pokeSpecial = special;
        //p.pokeSpecialPower = specialPower;

        //p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP, p.pokeAttack, p.pokeAttackPower, p.pokeSpecial, p.pokeSpecialPower);
        p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP);
        p.pokeOwner = owner;

        pokemonToMaster[pokemonID] = owner;
        addPokemonToMaster(owner, pokemonID);

        totalPokemonSupply += 1;
        CreatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP);
        return true;
    }

    function newPokemonMaster(address pokemonMaster)  returns (bool success) {
        uint ownerID = pokeMasters.length++;
        PokemonMaster o = pokeMasters[ownerID];
        o.pokeMaster = pokemonMaster;
        pokeOwnerIndex[pokemonMaster] = ownerID;
        return true;
    }

    function transferPokemon(address _from, address _to, uint256 _pokemonID)   returns (uint pokemonID, address from, address to) {
        Pokemon p = pokemons[_pokemonID];
        if (p.pokeOwner != _from) throw;
        if (pokeOwnerIndex[_to] == 0 && _to != pokemonToMaster[0] ) newPokemonMaster(_to);
        // Construir controle de acesso somente para o owner
        p.pokeOwner = _to;
        pokemonToMaster[_pokemonID] = _to;
        delPokemonFromMaster(_from, _pokemonID);
        addPokemonToMaster(_to, _pokemonID);
        Transfer(_from, _to, _pokemonID);
        return (_pokemonID, _from, _to);
    }

    function addPokemonToMaster(address _pokemonOwner, uint256 _pokemonID)  returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) {
        uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;

        // o.pokemons.push(_pokemonID);
        // usando .push ele adiciona 0,_pokemonID

        // Ao invés de simplesmente adicionar um pokemon ao final da lista,
        // verifica se há slot zerado no array, senao adiciona ao final
        bool slot;
        for (uint i=0; i < pokeList.length; i++){
            if (pokeList[i] == 0){
                slot = true;
                break;
            }
        }
        if (slot == true){
            o.pokemons[i] = _pokemonID;
        } else {
            uint j = pokeList.length++;
            o.pokemons[j] = _pokemonID;
        }

        qtdePokemons(_pokemonOwner);
        UpdateMasterPokemons(_pokemonOwner, o.pokemons.length);
        return (_pokemonOwner, o.pokemons, o.pokemons.length);
    }

    function delPokemonFromMaster(address _pokemonOwner, uint256 _pokemonID)  returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) {
        uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;

        for (uint i=0; i < pokeList.length; i++){
            if (pokeList[i] == _pokemonID){
                delete pokeList[i];
            }
        }

        // http://ethereum.stackexchange.com/questions/3373/how-to-clear-large-arrays-without-blowing-the-gas-limit
        o.pokemons=pokeList; // Se usar delete, usa a propria pokeList

        qtdePokemons(_pokemonOwner);
        UpdateMasterPokemons(_pokemonOwner, o.pokemons.length);
        return (_pokemonOwner, o.pokemons, o.pokemons.length);
    }

    function listPokemons( address _pokeOwner )  returns (address, uint[]){
        uint ownerID = pokeOwnerIndex[_pokeOwner];
        PokemonMaster o = pokeMasters[ownerID];
        return ( _pokeOwner, o.pokemons );
    }

    function qtdePokemons( address _pokeOwner)  returns (uint qtde){
        uint ownerID = pokeOwnerIndex[_pokeOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;
        uint count = 0;
        for (uint i=0; i < pokeList.length; i++){
            if ( pokeList[i] > 0 ){
                count++;
            }
        }
        totalPokemonsFromMaster[_pokeOwner] = count;
        return count;
    }

    /* Se tentarem enviar ether para o end desse contrato, ele rejeita */
    function () {
        throw;
    }
}


Change soft and hard cap

Change soft and hard cap


add safemath

add safemath

pragma solidity ^0.4.8;
import "./SafeMath.sol";
import "./RLC.sol";

/*
  Crowdsale Smart Contract for the iEx.ec project

  This smart contract collects ETH and BTC, and in return emits RLC tokens to the backers

  Thanks to BeyondTheVoid and TokenMarket who helped us shaping this code.

 */

// TODO
// Comment vont faire les gars qui ont investit en BTC avant le min cap pour recuperer leur rlc?
// add lockable to RLC transfer only for owner
// add emergency stop

// TEST:
// test differente timeframe
// test multiple invest
// test claim ETH

contract Crowdsale is SafeMath {

	// temp logs
	event Logs(address indexed from, uint amount, string value);

  	struct BackerETH {
	  uint weiReceived;	// Amount of ETH given
	  uint rlcToSend;  	// rlc to distribute when the min cap is reached
	}

  	struct BackerBTC {
	  string btc_address;  //store the btc address for full tracability
	  uint satoshiReceived;	// Amount of BTC given
	  uint rlcToSend;   	// rlc to distribute when the min cap is reached
	}

	RLC 	public rlc;         // RLC contract reference
	address public owner;       // Contract owner (iEx.ec team)
	address public multisigETH; // Multisig contract that will receive the ETH
	address public BTCproxy;	// addess of the BTC Proxy

	uint public RLCPerETH;      // Number of RLC per ETH
	uint public RLCPerBTC;      // Number of RLC per BTC
	uint public RLCPerSATOSHI;  // Number of RLC per SATOSHI
	uint public ETHReceived;    // Number of ETH received
	uint public BTCReceived;    // Number of BTC received
	uint public RLCSentToETH;   // Number of RLC sent to ETH contributors
	uint public RLCSentToBTC;   // Number of RLC sent to BTC contributors
	uint public RLCEmitted;		// Number of RLC emitted
	uint public startBlock;     // Crowdsale start block
	uint public endBlock;       // Crowdsale end block
	uint public minCap;         // Minimum number of RLC to sell
	uint public maxCap;         // Maximum number of RLC to sell
	bool public maxCapReached;  // Max cap has been reached
	uint public minInvestETH;   // Minimum amount to invest
	uint public minInvestBTC;   // Minimum amount to invest
	bool public crowdsaleClosed;// Is crowdsale still on going

	address public bounty;		// address at which the bounty RLC will be sent
	address public reserve; 	// address at which the contingency reserve will be sent
	address public team;		// address at which the team RLC will be sent

	uint public rlc_bounty;		// amount of bounties RLC
	uint public rlc_reserve;	// amount of the contingency reserve
	uint public rlc_team;		// amount of the team RLC

	mapping(address => BackerETH) public backersETH; //backersETH indexed by their ETH address
	mapping(address => BackerBTC) public backersBTC; //backersBTC indexed by their (BTC,ETH) address

    // Auth modifier, if the msg.sender isn't the expected address, throw.
	modifier onlyBy(address a){
	    if (msg.sender != a) throw;
	    _;
	}

	event receivedETH(address addr, uint value);
	event receivedBTC(address addr, string from, uint value);
	event RefundBTC(string to, uint value);
	// Constructor of the contract.
	function Crowdsale(address _token) {

	  //set the different variables
	  owner = msg.sender;
	  BTCproxy = 0x8cd6B3D8713df6aA35894c8beA200c27Ebe92550; // to change
	  //RLC = Token(0x0a8f269d52fad5f0f6297a264f48cbb290c68130); 	// RLC contract address
	  rlc = RLC(_token); 	// RLC contract address
	  multisigETH = 0x8cd6B3D8713df6aA35894c8beA200c27Ebe92550;
	  RLCSentToETH = 0;
	  minInvestETH = 100 finney; // 0.1 ether
	  minInvestBTC = 100000;     // approx 1 USD or 0.00100000 BTC
	  startBlock = now ;            // now (testnet)
	  endBlock =  now + 30 days;    // ever (testnet) startdate + 30 days
	  //RLCPerBTC = 50000000000000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  RLCPerETH = 5000000000000;          // FIXME
	  RLCPerSATOSHI = 50000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  minCap=12000000000000000;
	  maxCap=60000000000000000;
	  rlc_bounty=1700000000000000;
	  rlc_reserve=17000000000000000;
	  rlc_team=12000000000000000;
	  RLCEmitted = rlc_bounty + rlc_reserve + rlc_team;
	}

	/*
	* The fallback function corresponds to a donation in ETH
	*/
	function() payable	{
	  receiveETH(msg.sender);
	}

	/*
	*	Receives a payment in ETH
	*/
	function receiveETH(address beneficiary) payable {
// TODO check for msg.value coherent ?

	  //don't accept funding under a predefined treshold
	  if (msg.value < minInvestETH) throw;

	  // check if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((msg.value*RLCPerETH)/(1 ether));
	  //uint rlcToSend = bonus((msg.value*RLCPerFINNEY)/(1 finney));

	  // check if we are not reaching the maxCap by accepting this payment
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  // check that the same ETH address has not be used for BTC payment to facilitate refund
	 if (backersBTC[beneficiary].satoshiReceived > 0) throw;

	  //update the backer
	  BackerETH backer = backersETH[beneficiary];

	  // if the min cap is reached, token transfer happens immediately possibly along
	  // with the previous payment
	  if(isMinCapReached()) {
	  	Logs(msg.sender,rlcToSend + backer.rlcToSend, "1st list");
		if (!transferRLC(beneficiary, rlcToSend + backer.rlcToSend)) throw;     // Do the transfer right now
			backer.rlcToSend=0;
	  } else {
	      //if not we provision them to be paid or reclaimed later
		  //backer.rlcToSend += rlcToSend;
		  backer.rlcToSend = safeAdd(backer.rlcToSend, rlcToSend);
	  }

	  //backer.weiReceived += msg.value;
	  backer.weiReceived = safeAdd(backer.weiReceived, msg.value);
	  //ETHReceived += msg.value;    // Update the total wei collcted during the crowdfunding
	  ETHReceived = safeAdd(ETHReceived, msg.value) ;
	  //RLCSentToETH += rlcToSend;   // Update the total wei collcted during the crowdfunding
	  RLCSentToETH = safeAdd(RLCSentToETH, rlcToSend);

	  emitRLC(rlcToSend);

	  // send the corresponding contribution event
	  receivedETH(beneficiary,ETHReceived);
	}

	/*
	* receives a payment in BTC
	*/

	// Refund BTC in JS if function throw

	function receiveBTC(address beneficiary, string btc_address, uint value) onlyBy(BTCproxy){
	  //don't accept funding under a predefined treshold
	  if (value < minInvestBTC) throw;

	  // if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  // check that the same ETH address has not be used for ETH payment to facilitate refund
	  if (backersETH[beneficiary].weiReceived > 0) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((value*RLCPerBTC));

	  // check if we are not reaching the maxCap
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  //update the backer
	  BackerBTC backer = backersBTC[beneficiary];

	  // if the min cap is reached, token transfer happens immediately possibly along
	  // with the previous payment
	  if(isMinCapReached()) {
		  if (!transferRLC(beneficiary, rlcToSend + backer.rlcToSend)) throw;     // Do the transfer right now
		  backer.rlcToSend=0;
	  } else {
	      //if not we provision them to be paid or reclaimed later
		  backer.rlcToSend += rlcToSend;
	  }

	  backer.btc_address = btc_address;
	  //backer.satoshiReceived += value;
	  backer.satoshiReceived = safeAdd(backer.satoshiReceived, value);

	  //BTCReceived += value;    // Update the total satoshi collcted during the crowdfunding
	  BTCReceived =  safeAdd(BTCReceived, value);
	  //RLCSentToBTC += rlcToSend;
	  RLCSentToBTC = safeAdd(RLCSentToBTC, rlcToSend);
	  emitRLC(rlcToSend);

	  receivedBTC(beneficiary, btc_address, BTCReceived);
	}

	function isMinCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) > minCap;
	}

	function isMaxCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) == maxCap;
	}

	// Compute the variable part
	function emitRLC(uint amount) internal {
		Logs(msg.sender ,amount, "emitRLC");
		rlc_bounty+=amount/10;      // bounty is 10% of the crowdsale
		rlc_team+=amount/20;        // team is 5% of the crowdsale
		rlc_reserve+=amount/10; 	// contingency is 10% of the crowdsale
		RLCEmitted+=amount + amount/4;	// adjust the total number of RLC emitted
	}

	/*
	  Compute the RLC bonus according to the investment period
	*/
	function bonus(uint amount) returns (uint) {
	  if (now < (startBlock + 10 days)) return (amount + amount/5);  // bonus 20%
	  if (now < startBlock + 20 days) return (amount + amount/10);  // bonus 10%
	  return amount;
	}

	/*
	 * Transfer RLC to backers
	 * Assumes that the owner of the token contract and the crowdsale contract is the same
	 */
	function transferRLC(address to, uint amount) internal returns (bool) {
	  return rlc.transfer(to, amount);
	}

	/*
	* After the end of the crowdsale let user reclaimed their RLC if minCap has not been reached.
	* It must be sent from the backer address
	*/
	function claimRLC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint amount=backersETH[msg.sender].rlcToSend;
		if (amount !=0 ) {
			if (!rlc.transfer(msg.sender,amount)) throw;
			backersETH[msg.sender].rlcToSend=0;
			//transfer the corresponding amount to the multisig address
			if (!multisigETH.send(backersETH[msg.sender].weiReceived)) throw;
			backersETH[msg.sender].weiReceived=0;
		} else {
			amount = backersBTC[msg.sender].rlcToSend;
			if (!rlc.transfer(msg.sender,amount)) throw;
			backersBTC[msg.sender].rlcToSend=0;
			backersBTC[msg.sender].satoshiReceived=0;
		}
	}

	/*
	* After the end of the crowdsale let user reclaimed their ETH if minCap has not been reached.
	* It must be sent from the backer address
	*/
	function claimETH() {
		//check if we are in the correct time frame and if the
/*
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		if (!msg.sender.send(backersETH[msg.sender].weiReceived)) throw;
		backersETH[msg.sender].weiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		*/

		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valToSend = backersETH[msg.sender].weiReceived;
		backersETH[msg.sender].weiReceived=0;
		backersETH[msg.sender].rlcToSend=0;
		if (!msg.sender.send(valToSend)) throw;
	}

	/*
	* After the end of the crowdsale let user reclaimetheir BTC if minCap has not been reached.
	* It must be sent from the backer address
	*/
	/*
	function claimBTC(address beneficiary) onlyBy(BTCproxy) {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valueToSend = backersBTC[msg.sender].satoshiReceived;
		backersBTC[msg.sender].satoshiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend);

	}
	*/
	function claimBTC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valueToSend = backersBTC[msg.sender].satoshiReceived;
		backersBTC[msg.sender].satoshiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend);
	}

	/*
	* Update the rate RLC per ETH, computed externally by using the BTCETH index
	*/
	function setRLCPerETH(uint rate) onlyBy(BTCproxy) {
		RLCPerETH=rate;
	}

	/*
	* Finalize the crowdsale, should be called after the refund period
	*/
	function finalize() onlyBy(owner) {
		if ((now > endBlock + 10 days ) && (now < endBlock + 60 days)) throw;
		//moves the remaining ETH to the multisig address
		if (!multisigETH.send(this.balance)) throw;
		//moves RLC to the team, reserve and bounty address
	    if (!transferRLC(team,rlc_team)) throw;
	    if (!transferRLC(reserve,rlc_reserve)) throw;
	    if (!transferRLC(bounty,rlc_bounty)) throw;
	    rlc.burn(rlc.totalSupply() - RLCEmitted);
		crowdsaleClosed = true;
	}
}

pragma solidity ^0.4.8;
import "./SafeMath.sol";
import "./RLC.sol";

/*
  Crowdsale Smart Contract for the iEx.ec project

  This smart contract collects ETH and BTC, and in return emits RLC tokens to the backers

  Thanks to BeyondTheVoid and TokenMarket who helped us shaping this code.

 */

// TODO
// Comment vont faire les gars qui ont investit en BTC avant le min cap pour recuperer leur rlc?
// add lockable to RLC transfer only for owner
// add emergency stop

// TEST:
// test differente timeframe
// test multiple invest
// test claim ETH

contract Crowdsale {

	// temp logs
	event Logs(address indexed from, uint amount, string value);

  	struct BackerETH {
	  uint weiReceived;	// Amount of ETH given
	  uint rlcToSend;  	// rlc to distribute when the min cap is reached
	}

  	struct BackerBTC {
	  string btc_address;  //store the btc address for full tracability
	  uint satoshiReceived;	// Amount of BTC given
	  uint rlcToSend;   	// rlc to distribute when the min cap is reached
	}

	RLC 	public rlc;         // RLC contract reference
	address public owner;       // Contract owner (iEx.ec team)
	address public multisigETH; // Multisig contract that will receive the ETH
	address public BTCproxy;	// addess of the BTC Proxy

	uint public RLCPerETH;      // Number of RLC per ETH
	uint public RLCPerBTC;      // Number of RLC per BTC
	uint public RLCPerSATOSHI;  // Number of RLC per SATOSHI
	uint public ETHReceived;    // Number of ETH received
	uint public BTCReceived;    // Number of BTC received
	uint public RLCSentToETH;   // Number of RLC sent to ETH contributors
	uint public RLCSentToBTC;   // Number of RLC sent to BTC contributors
	uint public RLCEmitted;		// Number of RLC emitted
	uint public startBlock;     // Crowdsale start block
	uint public endBlock;       // Crowdsale end block
	uint public minCap;         // Minimum number of RLC to sell
	uint public maxCap;         // Maximum number of RLC to sell
	bool public maxCapReached;  // Max cap has been reached
	uint public minInvestETH;   // Minimum amount to invest
	uint public minInvestBTC;   // Minimum amount to invest
	bool public crowdsaleClosed;// Is crowdsale still on going

	address public bounty;		// address at which the bounty RLC will be sent
	address public reserve; 	// address at which the contingency reserve will be sent
	address public team;		// address at which the team RLC will be sent

	uint public rlc_bounty;		// amount of bounties RLC
	uint public rlc_reserve;	// amount of the contingency reserve
	uint public rlc_team;		// amount of the team RLC

	mapping(address => BackerETH) public backersETH; //backersETH indexed by their ETH address
	mapping(address => BackerBTC) public backersBTC; //backersBTC indexed by their (BTC,ETH) address

    // Auth modifier, if the msg.sender isn't the expected address, throw.
	modifier onlyBy(address a){
	    if (msg.sender != a) throw;
	    _;
	}

	event receivedETH(address addr, uint value);
	event receivedBTC(address addr, string from, uint value);
	event RefundBTC(string to, uint value);
	// Constructor of the contract.
	function Crowdsale(address _token) {

	  //set the different variables
	  owner = msg.sender;
	  BTCproxy = 0x8cd6B3D8713df6aA35894c8beA200c27Ebe92550; // to change
	  //RLC = Token(0x0a8f269d52fad5f0f6297a264f48cbb290c68130); 	// RLC contract address
	  rlc = RLC(_token); 	// RLC contract address
	  multisigETH = 0x8cd6B3D8713df6aA35894c8beA200c27Ebe92550;
	  RLCSentToETH = 0;
	  minInvestETH = 100 finney; // 0.1 ether
	  minInvestBTC = 100000;     // approx 1 USD or 0.00100000 BTC
	  startBlock = now ;            // now (testnet)
	  endBlock =  now + 30 days;    // ever (testnet) startdate + 30 days
	  //RLCPerBTC = 50000000000000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  RLCPerETH = 5000000000000;          // FIXME
	  RLCPerSATOSHI = 50000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  minCap=12000000000000000;
	  maxCap=60000000000000000;
	  rlc_bounty=1700000000000000;
	  rlc_reserve=17000000000000000;
	  rlc_team=12000000000000000;
	  RLCEmitted = rlc_bounty + rlc_reserve + rlc_team;
	}

	/*
	* The fallback function corresponds to a donation in ETH
	*/
	function() payable	{
	  receiveETH(msg.sender);
	}

	/*
	*	Receives a payment in ETH
	*/
	function receiveETH(address beneficiary) payable {
// TODO check for msg.value coherent ?

	  //don't accept funding under a predefined treshold
	  if (msg.value < minInvestETH) throw;

	  // check if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((msg.value*RLCPerETH)/(1 ether));
	  //uint rlcToSend = bonus((msg.value*RLCPerFINNEY)/(1 finney));

	  // check if we are not reaching the maxCap by accepting this payment
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  // check that the same ETH address has not be used for BTC payment to facilitate refund
	 if (backersBTC[beneficiary].satoshiReceived > 0) throw;

	  //update the backer
	  BackerETH backer = backersETH[beneficiary];

	  // if the min cap is reached, token transfer happens immediately possibly along
	  // with the previous payment
	  if(!isMinCapReached()) {
	  	Logs(msg.sender,rlcToSend + backer.rlcToSend, "1st list");
		if (!transferRLC(beneficiary, rlcToSend + backer.rlcToSend)) throw;     // Do the transfer right now
			backer.rlcToSend=0;
	  } else {
	      //if not we provision them to be paid or reclaimed later
		  backer.rlcToSend += rlcToSend;
	  }

	  backer.weiReceived += msg.value;
	  ETHReceived += msg.value;    // Update the total wei collcted during the crowdfunding
	  RLCSentToETH += rlcToSend;   // Update the total wei collcted during the crowdfunding

	  emitRLC(rlcToSend);

	  // send the corresponding contribution event
	  receivedETH(beneficiary,ETHReceived);
	}

	/*
	* receives a payment in BTC
	*/

	// add refund BTC event here

	function receiveBTC(address beneficiary, string btc_address, uint value) onlyBy(BTCproxy){
	  //don't accept funding under a predefined treshold
	  if (value < minInvestBTC) throw;

	  // if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  // check that the same ETH address has not be used for ETH payment to facilitate refund
	  if (backersETH[beneficiary].weiReceived > 0) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((value*RLCPerBTC));

	  // check if we are not reaching the maxCap
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  //update the backer
	  BackerBTC backer = backersBTC[beneficiary];

	  // if the min cap is reached, token transfer happens immediately possibly along
	  // with the previous payment
	  if(isMinCapReached()) {
		  if (!transferRLC(beneficiary, rlcToSend + backer.rlcToSend)) throw;     // Do the transfer right now
		  backer.rlcToSend=0;
	  } else {
	      //if not we provision them to be paid or reclaimed later
		  backer.rlcToSend += rlcToSend;
	  }

	  backer.btc_address = btc_address;
	  backer.satoshiReceived += value;

	  BTCReceived += value;    // Update the total satoshi collcted during the crowdfunding
	  RLCSentToBTC += rlcToSend;
	  emitRLC(rlcToSend);

	  receivedBTC(beneficiary, btc_address, BTCReceived);
	}

	function isMinCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) > minCap;
	}

	function isMaxCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) == maxCap;
	}

	// Compute the variable part
	function emitRLC(uint amount) internal {
		Logs(msg.sender ,amount, "emitRLC");
		rlc_bounty+=amount/10;      // bounty is 10% of the crowdsale
		rlc_team+=amount/20;        // team is 5% of the crowdsale
		rlc_reserve+=amount/10; 	// contingency is 10% of the crowdsale
		RLCEmitted+=amount + amount/4;	// adjust the total number of RLC emitted
	}

	/*
	  Compute the RLC bonus according to the investment period
	*/
	function bonus(uint amount) returns (uint) {
	  if (now < (startBlock + 10 days)) return (amount + amount/5);  // bonus 20%
	  if (now < startBlock + 20 days) return (amount + amount/10);  // bonus 10%
	  return amount;
	}

	/*
	 * Transfer RLC to backers
	 * Assumes that the owner of the token contract and the crowdsale contract is the same
	 */
	function transferRLC(address to, uint amount) internal returns (bool) {
	  return rlc.transfer(to, amount);
	}

	/*
	* After the end of the crowdsale let user reclaimed their RLC if minCap has not been reached.
	* It must be sent from the backer address
	*/
	function claimRLC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint amount=backersETH[msg.sender].rlcToSend;
		if (amount !=0 ) {
			if (!rlc.transfer(msg.sender,amount)) throw;
			backersETH[msg.sender].rlcToSend=0;
			//transfer the corresponding amount to the multisig address
			if (!multisigETH.send(backersETH[msg.sender].weiReceived)) throw;
			backersETH[msg.sender].weiReceived=0;
		} else {
			amount = backersBTC[msg.sender].rlcToSend;
			if (!rlc.transfer(msg.sender,amount)) throw;
			backersBTC[msg.sender].rlcToSend=0;
			backersBTC[msg.sender].satoshiReceived=0;
		}
	}

	/*
	* After the end of the crowdsale let user reclaimed their ETH if minCap has not been reached.
	* It must be sent from the backer address
	*/
	function claimETH() {
		//check if we are in the correct time frame and if the
/*
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		if (!msg.sender.send(backersETH[msg.sender].weiReceived)) throw;
		backersETH[msg.sender].weiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		*/

		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valToSend = backersETH[msg.sender].weiReceived;
		backersETH[msg.sender].weiReceived=0;
		backersETH[msg.sender].rlcToSend=0;
		if (!msg.sender.send(valToSend)) throw;
	}

	/*
	* After the end of the crowdsale let user reclaimetheir BTC if minCap has not been reached.
	* It must be sent from the backer address
	*/
	/*
	function claimBTC(address beneficiary) onlyBy(BTCproxy) {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valueToSend = backersBTC[msg.sender].satoshiReceived;
		backersBTC[msg.sender].satoshiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend);

	}
	*/
	function claimBTC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valueToSend = backersBTC[msg.sender].satoshiReceived;
		backersBTC[msg.sender].satoshiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend);
	}

	/*
	* Update the rate RLC per ETH, computed externally by using the BTCETH index
	*/
	function setRLCPerETH(uint rate) onlyBy(BTCproxy) {
		RLCPerETH=rate;
	}

	/*
	* Finalize the crowdsale, should be called after the refund period
	*/
	function finalize() onlyBy(owner) {
		if ((now > endBlock + 10 days ) && (now < endBlock + 60 days)) throw;
		//moves the remaining ETH to the multisig address
		if (!multisigETH.send(this.balance)) throw;
		//moves RLC to the team, reserve and bounty address
	    if (!transferRLC(team,rlc_team)) throw;
	    if (!transferRLC(reserve,rlc_reserve)) throw;
	    if (!transferRLC(bounty,rlc_bounty)) throw;
	    rlc.burn(rlc.totalSupply() - RLCEmitted);
		crowdsaleClosed = true;
	}
}


wip: Experimenting with EscrowWisp ideas

//SPDX-License-Identifier: MIT
pragma solidity ^0.8;

// FIXME: Use 4.x pre-release which slims down the 721 implementation
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";

import "./IKetherHomepage.sol";

// XXX
import "hardhat/console.sol";

// 1. Precompute deterministic contract address 0xSWAP
// 2. Call on-chain KetherHomepage.setAdOwner(_idx, 0xSWAP)
// 3. Call on-chain deploy TransientOwnerSwapper(address(KetherNFT), _idx) to address 0xSWAP
//    -> Inside, it calls KetherNFT.wrap(_idx)?

contract TransientOwnerSwapper {
  uint idx;
  address to;
  IKetherHomepage kether;

  constructor(IKetherHomepage _kether, KetherNFT _target, uint _idx) {
    idx = _idx;
    to = address(_target);
    kether = _kether;

    _target.wrap(_idx, msg.sender);

    selfdestruct();
  }

  function transfer() external {
    _kether.setAdOwner(idx, to);
  }
}

contract Wrapper {
  address authorized;

  constructor(address _authorized) {
    authorized = _authorized;
  }

  function call(address target, bytes memory payload) (bool, bytes memory) {
    require(msg.sender == authorized, "Wrapper: call must be done by authorized sender");

    return target.call(payload);
  }
}

interface Transferer {
  function transfer(address _from, address _to, uint _tokenId) external;
}

contract KetherNFT is ERC721 {
  /// instance is the KetherHomepage contract that this wrapper interfaces with.
  IKetherHomepage public instance;

  /// metadataSigner provides oracle authenticity for tokenURI content.
  address public metadataSigner;

  // TODO: Do we want to emit events?

  constructor(address _ketherContract, address _metadataSigner) ERC721("Thousand Ether Homepage Ad", "1KAD") {
    instance = IKetherHomepage(_ketherContract);
    metadataSigner = _metadataSigner;
  }

  function precompute(address _owner) pure public (bytes32 salt, address wrapper) {
    bytes32 salt = bytes32(_owner);

    address predictedAddress = address(uint160(uint(keccak256(abi.encodePacked(
      bytes1(0xff),
      address(this),
      salt,
      keccak256(abi.encodePacked(
        type(D).creationCode,
        arg
      ))
    )))));
    return salt, predictedAddress;
  }

  /// wrap mints an NFT if the ad unit's ownership has been trasnferred to this contract.
  function wrap(uint _idx, address _owner) external {
    bytes32 salt, address precomputerWrapper = precompute(_owner);

    require(instance.ads[_idx].owner == precomputedWrapper, "KetherNFT: owner needs to be our wrapper");

    // TODO: Check if wrapper already exists on precomputed address, use that instead.
    Wrapper w = new Wrapper{salt: salt}(address(this));
    require(address(w) == precomputedWrapper, "KetherNFT: precomputedWrapper is incorrect");

    (bool success,) = w.call(
      address(instance),
      abi.encodeWithSignature("setAdOwner(uint256,address)", _idx, address(this)));
    require(success, "KetherNFT: setAdOwner call failed");

    require(instance.ads[_idx].owner == address(this), "KetherNFT: owner needs to be KetherNFT");
    _mint(_owner, _idx);
  }

  function unwrap(uint _idx, address _newOwner) external {
    require(ownerOf(_idx) == msg.sender, "KetherNFT: unwrap for sender that is not owner");

    (bool success,) = w.call(
      address(instance),
      abi.encodeWithSignature("setAdOwner(uint256,address)", _idx, msg.sender));
    require(success, "KetherNFT: setAdOwner call failed");

    _burn(_idx);
  }

  // TODO: Should we have a setTokenURI function so owners can change the rendering of their token?
  // TODO: If we let people set their own tokenURI, do we need another NSFW flag option here?

  function tokenURI(uint256 _tokenId) public view virtual override(ERC721) returns (string memory) {
    // FIXME: Replace with IPFS URI? Perhaps set on wrap?
    return "ipfs://1000ether.com/ad/TODO"; // FIXME: Need to convert the uint256 to string, maybe Strings.uint2str?
  }

  /// publish is a delegated proxy for KetherHomapage's publish function.
  ///
  /// Publish allows for setting the link, image, and NSFW status for the ad
  /// unit that is identified by the idx which was returned during the buy step.
  /// The link and image must be full web3-recognizeable URLs, such as:
  ///  - bzz://a5c10851ef054c268a2438f10a21f6efe3dc3dcdcc2ea0e6a1a7a38bf8c91e23
  ///  - bzz://mydomain.eth/ad.png
  ///  - https://cdn.mydomain.com/ad.png
  ///  - https://ipfs.io/ipfs/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu
  ///  - ipfs://Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu
  /// Images should be valid PNG.
  /// Content-addressable storage links like IPFS are encouraged.
  function publish(uint _idx, string calldata _link, string calldata _image, string calldata _title, bool _NSFW) external {
    require(getApproved(_idx) == msg.sender, "KetherNFT: publish for sender that is not approved");

    // TODO: Finish this lol
    (bool success,) = w.call(
      address(instance),
      abi.encodeWithSignature("publish(uint256,string,string,string,bool)", _idx, _link, _image, _title, _NSFW));

    require(success, "KetherNFT: publish call failed");
  }

}

//SPDX-License-Identifier: MIT
pragma solidity ^0.8;

// FIXME: Use 4.x pre-release which slims down the 721 implementation
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";

import "./IKetherHomepage.sol";

// XXX
import "hardhat/console.sol";

contract KetherNFT is ERC721 {
  /// instance is the KetherHomepage contract that this wrapper interfaces with.
  IKetherHomepage public instance;

  /// metadataSigner provides oracle authenticity for tokenURI content.
  address public metadataSigner;

  mapping (uint => address) prewrapped;

  // TODO: Do we want to emit events?

  constructor(address _ketherContract, address _metadataSigner) ERC721("Thousand Ether Homepage Ad", "1KAD") {
    instance = IKetherHomepage(_ketherContract);
    metadataSigner = _metadataSigner;
  }

  /*
     Migration process:
     1. KetherNFT.prepare(_idx) as KetherHomepage owner
     2. KetherHomepage.setAdOwner(_idx, address(KetherNFT))
     3. KetherNFT.wrap(_idx); as owner
  */

  /// prepare an ad unit to be wrapped. It confirms that the sender is the owner of the ad unit.
  function prepare(uint _idx) external {
    require(instance.ads[_idx].owner == msg.sender, "KetherNFT: prepare for sender that is not owner");

    prewrapped[idx] = msg.sender;
  }

  /// wrap mints an NFT if the ad unit's ownership has been trasnferred to this contract.
  function wrap(uint _idx) external {
    require(prewrapped[_idx] == msg.sender, "KetherNFT: wrap for sender that was not prewrapped");
    require(instance.ads[_idx].owner == address(this), "KetherNFT: owner needs to be this contract before wrapping");

    _mint(msg.sender, _idx);

    // Transfer contract ownership to this contract as a delegate.
    // -> KetherHomepage(_ketherContract).setAdOwner(_idx, newOwner);

    //bytes memory callEncoded = abi.encodePacked(bytes4(keccak256("setAdOwner(uint256,address)")), _idx, address(this));
    //bytes memory callEncoded = abi.encodeWithSignature("setAdOwner(uint256,address)", _idx, address(this));
    //Address.functionDelegateCall(address(instance), callEncoded, "KetherNFT: wrap delegatecall setAdOwner failed");

    //(bool success, bytes memory data) = address(instance).delegatecall(callEncoded);
  }

  function unwrap(uint _idx, address _newOwner) external {
    require(ownerOf(_idx) == msg.sender, "KetherNFT: unwrap for sender that is not owner");

    // TODO: Test that if this fails, the rest of the call fails
    instance.setAdOwner(_idx, _newOwner);

    _burn(_idx);
  }

  // TODO: Should we have a setTokenURI function so owners can change the rendering of their token?
  // TODO: If we let people set their own tokenURI, do we need another NSFW flag option here?

  function tokenURI(uint256 _tokenId) public view virtual override(ERC721) returns (string memory) {
    // FIXME: Replace with IPFS URI? Perhaps set on wrap?
    return "ipfs://1000ether.com/ad/TODO"; // FIXME: Need to convert the uint256 to string, maybe Strings.uint2str?
  }

  /// publish is a delegated proxy for KetherHomapage's publish function.
  ///
  /// Publish allows for setting the link, image, and NSFW status for the ad
  /// unit that is identified by the idx which was returned during the buy step.
  /// The link and image must be full web3-recognizeable URLs, such as:
  ///  - bzz://a5c10851ef054c268a2438f10a21f6efe3dc3dcdcc2ea0e6a1a7a38bf8c91e23
  ///  - bzz://mydomain.eth/ad.png
  ///  - https://cdn.mydomain.com/ad.png
  ///  - https://ipfs.io/ipfs/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu
  ///  - ipfs://Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu
  /// Images should be valid PNG.
  /// Content-addressable storage links like IPFS are encouraged.
  function publish(uint _idx, string calldata _link, string calldata _image, string calldata _title, bool _NSFW) external {
    // FIXME: Should this be ownerOf? Letting approved accounts publish would allow lending.
    require(getApproved(_idx) == msg.sender, "KetherNFT: publish for sender that is not approved");

    instance.publish(_idx, _link, _image, _title, _NSFW);
  }

}


-Fixed the undeclared identifier bug

-Fixed the undeclared identifier bug

contract EscrowCreator {
    struct Entity {
        address addr;
        bool accepted;
    }

    struct EscrowInfo {
        Entity buyer;
        Entity seller;
        uint amount;
    }

    mapping (bytes32 => EscrowInfo) contracts;

    function keyGenerator(address buyerAddress, address sellerAddress, uint amount, uint blockNumber) returns (bytes32) {
      return sha3(buyerAddress, sellerAddress, amount, blockNumber);
    }

    function initiateCreation(address buyerAddress, address sellerAddress, uint amount) {
        bytes32 token = keyGenerator(buyerAddress, sellerAddress, amount, block.number);
        Entity memory buyer = Entity(buyerAddress, false);
        Entity memory seller = Entity(sellerAddress, true);
        contracts[token] = EscrowInfo(buyer, seller, amount);
    }

    function getEscrowInfo(bytes32 token) returns (
        address buyerAddr,
        bool buyerAccepted,
        address sellerAddr,
        bool sellerAccepted,
        uint amount
    ) {
        buyerAddr = contracts[token].buyer.addr;
        buyerAccepted = contracts[token].buyer.accepted;
        sellerAddr = contracts[token].seller.addr;
        sellerAccepted = contracts[token].seller.accepted;
        amount = contracts[token].amount;
    }
}

contract EscrowCreator {
    struct Entity {
        address addr;
        bool accepted;
    }

    struct EscrowInfo {
        Entity buyer;
        Entity seller;
        uint amount;
    }

    mapping (bytes32 => EscrowInfo) contracts;

    function keyGenerator(address buyerAddress, address sellerAddress, uint amount, uint blockNumber) returns (bytes32) {
      return sha3(buyerAddress, sellerAddress, amount, blockNumber);
    }

    function initiateCreation(address buyerAddress, address sellerAddress, uint amount) {
        token = keyGenerator(buyerAddress, sellerAddress, amount, block.number);
        Entity memory buyer = Entity(buyerAddress, false);
        Entity memory seller = Entity(sellerAddress, true);
        contracts[token] = EscrowInfo(buyer, seller, amount);
    }

    function getEscrowInfo(bytes32 token) returns (
        address buyerAddr,
        bool buyerAccepted,
        address sellerAddr,
        bool sellerAccepted,
        uint amount
    ) {
        buyerAddr = contracts[token].buyer.addr;
        buyerAccepted = contracts[token].buyer.accepted;
        sellerAddr = contracts[token].seller.addr;
        sellerAccepted = contracts[token].seller.accepted;
        amount = contracts[token].amount;
    }
}


Spelling again

Spelling again

pragma solidity ^0.4.10;

contract brew2venue {
    enum beerType {lager, stout, porter, ipa}

    //Object to hold beer product, such as Newstead Brewery 21 Feet Seven Inches porter
    struct beer {
        address brewer;
        beerType beerType;
        string name;
        int ml;  //size of bottle / can in millilitres
        bytes32 sku;
    }

    function add (string _batch, int _abv)
    {
        beer memory _beer = beer (_batch, block.timestamp, _cost, _abv);
        bottles.push(_bottle);
    }

    //Add new product to the blockchain
    function newProduct(beerType _beerType, string _name, int _ml, bytes _sku)
    {
        beer memory _beer = beer (msg.sender, _beerTye, _name, _ml, _sku);
        _products(msg.sender).push(_beer);
    }

    beer [] public bottles;

    //Products per brewer
    mapping (address => bottle[]) _products;
}

pragma solidity ^0.4.10;

contract brew2venue {
    enum beerType {lager, stout, porter, ipa}

    //Object to hold beer product, such as Newstead Brewery 21 Feet Seven Inches porter
    struct beer {
        address brewer;
        beerType beerType;
        string name;
        int ml;  //size of bottle / can in milliletres
        bytes32 sku;
    }

    function add (string _batch, int _abv)
    {
        beer memory _beer = beer (_batch, block.timestamp, _cost, _abv);
        bottles.push(_bottle);
    }

    //Add new product to the blockchain
    function newProduct(beerType _beerType, string _name, int _ml, bytes _sku)
    {
        beer memory _beer = beer (msg.sender, _beerTye, _name, _ml, _sku);
        _products(msg.sender).push(_beer);
    }

    beer [] public bottles;

    //Products per brewer
    mapping (address => bottle[]) _products;
}