Upgrade market

Upgrade market

contract token {
    address public daoAddr;
    address public owner;
    mapping (address => uint) public tokenBalanceOf;
    DAO daoToken;

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

    /* DAO functions */
    function emission(address _agentContrAddr, uint _amount) returns(bool result) {
        if(msg.sender==daoAddr)
        {
            tokenBalanceOf[_agentContrAddr] += _amount;
            return true;
        }
        return false;
    }

    function burn(address _agentContrAddr, uint _amount) returns(bool result) {
        if(msg.sender==daoAddr && tokenBalanceOf[_agentContrAddr]>=_amount)
        {
            tokenBalanceOf[_agentContrAddr] -= _amount;
            return true;
        }
        return false;
    }

    function setDaoAddr(address _daoAddr) {
        daoToken = DAO(_daoAddr);
        if(daoToken.daoFounder() == msg.sender && owner == msg.sender) {
            daoAddr = _daoAddr;
        }
    }

    /* Agent function */

    function getBalance() returns(uint _balance) {
        return tokenBalanceOf[msg.sender];
    }

    function sendToken(address receiver, uint amount) returns(bool result) {
        if (tokenBalanceOf[msg.sender] < amount) {return false;}
        tokenBalanceOf[msg.sender] -= amount;
        tokenBalanceOf[receiver] += amount;
        return true;
    }
}

contract DAO {
    address public daoFounder;
    address public daoFounderContr;
    address public daoMarketContr;
    address public daoGovermentContr;
    bool public initialization;
    uint public creditAmount;
    uint public sharesAmount;
    uint public creditTurn;
    uint public numAgents;

    token public daoShares;
    token public daoCredits;

    /* Assets data */
    Asset[] public assetsList;
    mapping (address => uint) public assetDataOf;
    mapping (address => bool) public assetExistOf;
    struct Asset {
        address assetAddr;
    }

    /* Agents data */
    Agent[] public agentsList;
    mapping (address => uint) public agentDataOf;
    mapping (address => bool) public agentActiveOf;
    struct Agent {
        address agentContrAddr;
        uint joinData;
    }

    function DAO(token _shares, token _credits, market _daoMarketContr, goverment _daoGovermentContr) {
        daoFounder = msg.sender;
        daoShares = token(_shares);
        daoCredits = token(_credits);
        daoMarketContr = _daoMarketContr;
        daoGovermentContr = _daoGovermentContr;
    }

    function initializationDaoBalances(uint _founderSharesAmount, uint _founderCreditsAmount) returns (bool result) {
        if(!initialization) {
        daoShares.emission(msg.sender, _founderSharesAmount);
        sharesAmount = _founderSharesAmount;
        daoCredits.emission(msg.sender, _founderCreditsAmount);
        creditAmount = _founderCreditsAmount;
        return true;
        }
    }

    function daoEfficiency() returns (uint daoEfficiency) {
        daoEfficiency = creditTurn*100/creditAmount;
    }

    function daoShareCost() returns (uint shareCost) {
        shareCost = creditTurn/sharesAmount;
    }

    function daoCreditPower() returns (uint creditPower) {
        creditPower = sharesAmount*100/creditTurn;
    }

    function daoShareSale(uint _shareAmount) returns (uint creditReward) {
        if(daoShares.tokenBalanceOf(msg.sender)>=_shareAmount) {
            creditReward = daoShareCost()*_shareAmount;
            daoCredits.emission(msg.sender, creditReward);
            daoShares.burn(msg.sender, _shareAmount);
        }
    }

    function daoShareBuy(uint _creditAmount) returns (uint shares) {
        if(daoCredits.tokenBalanceOf(msg.sender)>=_creditAmount) {
            shares = daoCreditPower()*_creditAmount;
            daoShares.emission(msg.sender, shares);
            daoCredits.burn(msg.sender, _creditAmount);
        }
    }

    function daoSharesEmission(address _agentContrAddr, uint _sharesAmount) {
        daoShares.emission(_agentContrAddr, _sharesAmount);
    }

    function daoCreditEmission(uint _creditsAMount) {
        daoCredits.emission(msg.sender, _creditsAMount);
    }

    function setAgent(address _agentContAddr) returns(uint agentID) {
        if(daoShares.tokenBalanceOf(msg.sender)>0) {
            agentID = agentsList.length++;
            Agent a = agentsList[agentID];
            a.agentContrAddr = _agentContAddr;
            a.joinData = now;
            uint newAgentSharesAmount;
            newAgentSharesAmount = sharesAmount/numAgents;
            daoShares.emission(_agentContAddr, newAgentSharesAmount);
            numAgents = agentID;
            agentDataOf[_agentContAddr] = agentID;
            agentActiveOf[_agentContAddr] = true;
            return agentID;
        }
    }

    function setAssets(address _assetAddr) returns(uint assetID) {
        if (msg.sender == daoMarketContr) {
            assetID = assetsList.length++;
            Asset a = assetsList[assetID];
            a.assetAddr = _assetAddr;
            assetDataOf[_assetAddr] = assetID;
            assetExistOf[_assetAddr] = true;
            return assetID;
        }
    }
}

contract agent {
    address agentAddr;
    address controlAddr;
    address daoAddr;
    DAO public dao;

    /* Agents contract list*/

    AgentContract[] public agentContracts;
    struct AgentContract {
        address agentContractAddr;
        string abi;
    }

    modifier controlCheck { if (msg.sender == controlAddr) _ }

    function agent(address _daoAddr) {
        agentAddr = msg.sender;
        controlAddr = msg.sender;
        daoAddr = _daoAddr;
    }

    function setControlAddr(address _controlAddr) returns(bool result) {
        if(msg.sender == agentAddr) {
            controlAddr = _controlAddr;
        }
    }

    function setNewAgent(address _agentAddr) controlCheck returns(bool result) {
        dao.setAgent(_agentAddr);
        return true;
    }
}

contract market {
    address daoAddr;
    DAO public dao;

    struct Order {
        uint orderID;
        address owner;
        uint amount;
        uint price;
    }

    struct OrderList {
        address assetAddr;
        Order[] orders;
    }

    OrderList[] public sellList;
    Order[] public sellOrders;
    mapping (address => bool) sellExistOf;
    mapping (address => uint) sellDataOf;

    OrderList[] public buyList;
    Order[] public buyOrders;
    mapping (address => bool) buyExistOf;
    mapping (address => uint) buyDataOf;

    function getSellList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function getBuyList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function addSell(address _assetAddr, uint _amount, uint _price) returns(uint sellID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(sellExistOf[_assetAddr]) {
                uint assetID;
                assetID = sellDataOf[_assetAddr];
                OrderList[] assetOrders = sellList[assetID];
                sellID = sellOrders.sellOrders.length++;
                sellOrders.orders[sellID] = Order({orderID: sellID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function addBuy(address _assetAddr, uint _amount, uint _price) returns(uint buyID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(buyExistOf[_assetAddr]) {
                uint assetID;
                assetID = buyDataOf[_assetAddr];
                OrderList[] buyOrders = buyList[assetID];
                buyID = buyOrders.orders.length++;
                buyOrders.orders[buyID] = Order({orderID: buyID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function BuyDeal(address _assetAddr, uint _buyID) {
        uint profit = msg.value*dao.daoEfficiency()/100;
        dao.daoCredits.emission(daoAddr, profit);
        return true;
    }

    function SellDeal(address _assetAddr, uint sellID) returns(bool result) {
        return true;
    }

}

contract goverment {
    address daoAddr;
    DAO public dao;

}

contract token {
    address public daoAddr;
    address public owner;
    mapping (address => uint) public tokenBalanceOf;
    DAO daoToken;

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

    /* DAO functions */
    function emission(address _agentContrAddr, uint _amount) returns(bool result) {
        if(msg.sender==daoAddr)
        {
            tokenBalanceOf[_agentContrAddr] += _amount;
            return true;
        }
        return false;
    }

    function burn(address _agentContrAddr, uint _amount) returns(bool result) {
        if(msg.sender==daoAddr && tokenBalanceOf[_agentContrAddr]>=_amount)
        {
            tokenBalanceOf[_agentContrAddr] -= _amount;
            return true;
        }
        return false;
    }

    function setDaoAddr(address _daoAddr) {
        daoToken = DAO(_daoAddr);
        if(daoToken.daoFounder() == msg.sender && owner == msg.sender) {
            daoAddr = _daoAddr;
        }
    }

    /* Agent function */

    function getBalance() returns(uint _balance) {
        return tokenBalanceOf[msg.sender];
    }

    function sendToken(address receiver, uint amount) returns(bool result) {
        if (tokenBalanceOf[msg.sender] < amount) {return false;}
        tokenBalanceOf[msg.sender] -= amount;
        tokenBalanceOf[receiver] += amount;
        return true;
    }
}

contract DAO {
    address public daoFounder;
    address public daoFounderContr;
    address public daoMarketContr;
    address public daoGovermentContr;
    bool public initialization;
    uint public creditAmount;
    uint public sharesAmount;
    uint public creditTurn;
    uint public numAgents;

    token public daoShares;
    token public daoCredits;

    /* Assets data */
    Asset[] public assetsList;
    mapping (address => uint) public assetDataOf;
    mapping (address => bool) public assetExistOf;
    struct Asset {
        address assetAddr;
    }

    /* Agents data */
    Agent[] public agentsList;
    mapping (address => uint) public agentDataOf;
    mapping (address => bool) public agentActiveOf;
    struct Agent {
        address agentContrAddr;
        uint joinData;
    }

    function DAO(token _shares, token _credits, market _daoMarketContr, goverment _daoGovermentContr) {
        daoFounder = msg.sender;
        daoShares = token(_shares);
        daoCredits = token(_credits);
        daoMarketContr = _daoMarketContr;
        daoGovermentContr = _daoGovermentContr;
    }

    function initializationDaoBalances(uint _founderSharesAmount, uint _founderCreditsAmount) returns (bool result) {
        if(!initialization) {
        daoShares.emission(msg.sender, _founderSharesAmount);
        sharesAmount = _founderSharesAmount;
        daoCredits.emission(msg.sender, _founderCreditsAmount);
        creditAmount = _founderCreditsAmount;
        return true;
        }
    }

    function daoEfficiency() returns (uint daoEfficiency) {
        daoEfficiency = creditTurn*100/creditAmount;
    }

    function daoShareCost() returns (uint shareCost) {
        shareCost = creditTurn*100/sharesAmount;
    }

    function daoCreditPower() returns (uint creditPower) {
        creditPower = sharesAmount*100/creditTurn;
    }

    function daoShareSale(uint _shareAmount) returns (uint creditReward) {
        if(daoShares.tokenBalanceOf(msg.sender)>=_shareAmount) {
            creditReward = daoShareCost()*_shareAmount/100;
            daoCredits.emission(msg.sender, creditReward);
            daoShares.burn(msg.sender, _shareAmount);
        }
    }

    function daoShareBuy(uint _creditAmount) returns (uint shares) {
        if(daoCredits.tokenBalanceOf(msg.sender)>=_creditAmount) {
            shares = daoCreditPower()*_creditAmount/100;
            daoShares.emission(msg.sender, shares);
            daoCredits.burn(msg.sender, _creditAmount);
        }
    }

    function daoSharesEmission(address _agentContrAddr, uint _sharesAmount) {
        daoShares.emission(_agentContrAddr, _sharesAmount);
    }

    function daoCreditEmission(uint _creditsAMount) {
        daoCredits.emission(msg.sender, _creditsAMount);
    }

    function setAgent(address _agentContAddr) returns(uint agentID) {
        if(daoShares.tokenBalanceOf(msg.sender)>0) {
            agentID = agentsList.length++;
            Agent a = agentsList[agentID];
            a.agentContrAddr = _agentContAddr;
            a.joinData = now;
            uint newAgentSharesAmount;
            newAgentSharesAmount = sharesAmount/numAgents;
            daoShares.emission(_agentContAddr, newAgentSharesAmount);
            numAgents = agentID;
            agentDataOf[_agentContAddr] = agentID;
            agentActiveOf[_agentContAddr] = true;
            return agentID;
        }
    }

    function setAssets(address _assetAddr) returns(uint assetID) {
        if (msg.sender == daoMarketContr) {
            assetID = assetsList.length++;
            Asset a = assetsList[assetID];
            a.assetAddr = _assetAddr;
            assetDataOf[_assetAddr] = assetID;
            assetExistOf[_assetAddr] = true;
            return assetID;
        }
    }
}

contract agent {
    address agentAddr;
    address controlAddr;
    address daoAddr;
    DAO public dao;

    /* Agents contract list*/

    AgentContract[] public agentContracts;
    struct AgentContract {
        address agentContractAddr;
        string abi;
    }

    modifier controlCheck { if (msg.sender == controlAddr) _ }

    function agent(address _daoAddr) {
        agentAddr = msg.sender;
        controlAddr = msg.sender;
        daoAddr = _daoAddr;
    }

    function setControlAddr(address _controlAddr) returns(bool result) {
        if(msg.sender == agentAddr) {
            controlAddr = _controlAddr;
        }
    }

    function setNewAgent(address _agentAddr) controlCheck returns(bool result) {
        dao.setAgent(_agentAddr);
        return true;
    }
}

contract market {
    address daoAddr;
    DAO public dao;

    struct Order {
        uint orderID;
        address owner;
        uint amount;
        uint price;
    }

    struct OrderList {
        address assetAddr;
        Order[] orders;
    }

    OrderList[] public sellList;
    mapping (address => bool) sellExistOf;
    mapping (address => uint) sellDataOf;

    OrderList[] public buyList;
    mapping (address => bool) buyExistOf;
    mapping (address => uint) buyDataOf;

    function getSellList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function getBuyList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function addSell(address _assetAddr, uint _amount, uint _price) returns(uint sellID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(sellExistOf[_assetAddr]) {
                uint assetID;
                assetID = sellDataOf[_assetAddr];
                OrderList[] sellOrders = sellList[assetID];
                sellID = sellOrders.orders.length++;
                sellOrders.orders[sellID] = Order({orderID: sellID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function addBuy(address _assetAddr, uint _amount, uint _price) returns(uint buyID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(buyExistOf[_assetAddr]) {
                uint assetID;
                assetID = buyDataOf[_assetAddr];
                OrderList[] buyOrders = buyList[assetID];
                buyID = buyOrders.orders.length++;
                buyOrders.orders[buyID] = Order({orderID: buyID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function сloseBuyDeal(address _assetAddr, buyID) returns(bool result) {
        return true;
    }

    function сloseSellDeal(address _assetAddr, sellID) returns(bool result) {
        return true;
    }

}

contract goverment {
    address daoAddr;
    DAO public dao;

}


Made buy/sell consistent

Made buy/sell consistent

pragma solidity ^0.4.4;

// ------------------------------------------------------------------------
// TokenTraderFactory
//
// Decentralised trustless ERC20-compliant token to ETH exchange contract
// on the Ethereum blockchain.
//
// Enjoy. (c) JonnyLatte & BokkyPooBah 2016. The MIT licence.
// ------------------------------------------------------------------------

// https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
    function totalSupply() constant returns (uint totalSupply);
    function balanceOf(address _owner) constant returns (uint balance);
    function transfer(address _to, uint _value) returns (bool success);
    function transferFrom(address _from, address _to, uint _value) returns (bool success);
    function approve(address _spender, uint _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint remaining);
    event Transfer(address indexed _from, address indexed _to, uint _value);
    event Approval(address indexed _owner, address indexed _spender, uint _value);
}

contract Owned {
    address public owner;
    event OwnershipTransferred(address indexed _from, address indexed _to);

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

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

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

// contract can buy or sell tokens for ETH
// prices are in amount of wei per batch of token units

contract TokenTrader is Owned {

    address public asset;       // address of token
    uint256 public buyPrice;    // contract buys lots of token at this price
    uint256 public sellPrice;   // contract sells lots at this price
    uint256 public units;       // lot size (token-wei)

    bool public buysTokens;     // is contract buying
    bool public sellsTokens;    // is contract selling

    event ActivatedEvent(bool buys, bool sells);
    event EtherDeposited(uint256 amount);
    event AssetWithdrawn(uint256 value);
    event TokenWithdrawn(address token, uint256 value);
    event EtherWithdrawn(uint256 value);
    event AssetBought(address indexed buyer, uint256 amount, uint256 value, uint256 change);
    event AssetSold(address indexed seller, uint256 amount, uint256 value);

    // Constructor
    function TokenTrader (
        address _asset,
        uint256 _buyPrice,
        uint256 _sellPrice,
        uint256 _units,
        bool    _buysTokens,
        bool    _sellsTokens
    ) {
        asset       = _asset;
        buyPrice    = _buyPrice;
        sellPrice   = _sellPrice;
        units       = _units;
        buysTokens  = _buysTokens;
        sellsTokens = _sellsTokens;
        ActivatedEvent(buysTokens, sellsTokens);
    }

    // modify trading behavior
    function activate (
        bool _buysTokens,
        bool _sellsTokens
    ) onlyOwner {
        buysTokens  = _buysTokens;
        sellsTokens = _sellsTokens;
        ActivatedEvent(buysTokens, sellsTokens);
    }

    // allows owner to deposit ETH
    // deposit tokens by sending them directly to contract
    // buyers must not send tokens to the contract, use: sell(...)
    function deposit() payable onlyOwner {
        EtherDeposited(msg.value);
    }

    // allow owner to remove trade token
    function withdrawAsset(uint256 _value) onlyOwner returns (bool ok) {
        AssetWithdrawn(_value);
        return ERC20(asset).transfer(owner, _value);
    }

    // allow owner to remove arbitrary tokens
    // included just in case contract receives wrong token
    function withdrawToken(address _token, uint256 _value) onlyOwner returns (bool ok) {
        TokenWithdrawn(_token, _value);
        return ERC20(_token).transfer(owner, _value);
    }

    // allow owner to remove ETH
    function withdraw(uint256 _value) onlyOwner returns (bool ok) {
        if (this.balance >= _value) {
            EtherWithdrawn(_value);
            return owner.send(_value);
        }
    }

    // user buys token with ETH
    function buy() payable {
        if (sellsTokens || msg.sender == owner) {
            uint order    = msg.value / sellPrice;
            uint can_sell = ERC20(asset).balanceOf(address(this)) / units;
            uint256 change = 0;
            if (order > can_sell) {
                change = msg.value - (can_sell * sellPrice);
                order = can_sell;
                if (!msg.sender.send(change)) throw;
            }
            if (order > 0) {
                if(!ERC20(asset).transfer(msg.sender, order * units)) throw;
            }
            AssetBought(msg.sender, msg.value, order * units, change);
        }
        else if (!msg.sender.send(msg.value)) throw;  // return user funds if the contract is not selling
    }

    // user sells token for ETH
    // user must set allowance for this contract before calling
    function sell(uint256 amount) {
        if (buysTokens || msg.sender == owner) {
            uint256 can_buy = this.balance / buyPrice;  // token lots contract can buy
            uint256 order = amount / units;             // token lots available
            if (order > can_buy) order = can_buy;       // adjust order for funds
            if (order > 0) {
                // extract user tokens
                if(!ERC20(asset).transferFrom(msg.sender, address(this), order * units)) throw;
                // pay user
                if(!msg.sender.send(order * buyPrice)) throw;
            }
            AssetSold(msg.sender, amount, order * buyPrice);
        }
    }

    // sending ETH to contract sells tokens to user
    function () payable {
        buy();
    }
}

// This contract deploys TokenTrader contracts and logs the event
contract TokenTraderFactory is Owned {

    event TradeListing(address owner, address addr);
    event TokenWithdrawn(address token, uint256 value);

    mapping(address => bool) _verify;

    function verify(address tradeContract) constant returns (
        bool valid,
        address asset,
        uint256 buyPrice,
        uint256 sellPrice,
        uint256 units,
        bool    buysTokens,
        bool    sellsTokens
    ) {
        valid = _verify[tradeContract];
        if (valid) {
            TokenTrader t = TokenTrader(tradeContract);
            asset       = t.asset();
            buyPrice    = t.buyPrice();
            sellPrice   = t.sellPrice();
            units       = t.units();
            buysTokens  = t.buysTokens();
            sellsTokens = t.sellsTokens();
        }
    }

    function createTradeContract(
        address _asset,
        uint256 _buyPrice,
        uint256 _sellPrice,
        uint256 _units,
        bool    _buysTokens,
        bool    _sellsTokens
    ) returns (address) {
        if (_buyPrice > _sellPrice) throw; // must make profit on spread
        if (_units == 0) throw;            // can't sell zero units
        address trader = new TokenTrader(
            _asset,
            _buyPrice,
            _sellPrice,
            _units,
            _buysTokens,
            _sellsTokens);
        _verify[trader] = true; // record that this factory created the trader
        TokenTrader(trader).transferOwnership(msg.sender); // set the owner to whoever called the function
        TradeListing(msg.sender, trader);
    }

    // allow owner to remove arbitrary tokens
    // included just in case contract receives some tokens
    function withdrawToken(address _token, uint256 _value) onlyOwner returns (bool ok) {
        TokenWithdrawn(_token, _value);
        return ERC20(_token).transfer(owner, _value);
    }

    function () {
        throw;     // Prevents accidental sending of ether to the factory
    }
}

pragma solidity ^0.4.4;

// ------------------------------------------------------------------------
// TokenTraderFactory
//
// Decentralised trustless ERC20-compliant token to ETH exchange contract
// on the Ethereum blockchain.
//
// Enjoy. (c) JonnyLatte & BokkyPooBah 2016. The MIT licence.
// ------------------------------------------------------------------------

// https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
    function totalSupply() constant returns (uint totalSupply);
    function balanceOf(address _owner) constant returns (uint balance);
    function transfer(address _to, uint _value) returns (bool success);
    function transferFrom(address _from, address _to, uint _value) returns (bool success);
    function approve(address _spender, uint _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint remaining);
    event Transfer(address indexed _from, address indexed _to, uint _value);
    event Approval(address indexed _owner, address indexed _spender, uint _value);
}

contract Owned {
    address public owner;
    event OwnershipTransferred(address indexed _from, address indexed _to);

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

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

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

// contract can buy or sell tokens for ETH
// prices are in amount of wei per batch of token units

contract TokenTrader is Owned {

    address public asset;       // address of token
    uint256 public buyPrice;    // contract buys lots of token at this price
    uint256 public sellPrice;   // contract sells lots at this price
    uint256 public units;       // lot size (token-wei)

    bool public sellsTokens;    // is contract selling
    bool public buysTokens;     // is contract buying

    event ActivatedEvent(bool sells, bool buys);
    event EtherDeposited(uint256 amount);
    event AssetWithdrawn(uint256 value);
    event TokenWithdrawn(address token, uint256 value);
    event EtherWithdrawn(uint256 value);
    event AssetBought(address indexed buyer, uint256 amount, uint256 value, uint256 change);
    event AssetSold(address indexed seller, uint256 amount, uint256 value);

    // Constructor
    function TokenTrader (
        address _asset,
        uint256 _buyPrice,
        uint256 _sellPrice,
        uint256 _units,
        bool    _sellsTokens,
        bool    _buysTokens
    ) {
        asset       = _asset;
        buyPrice    = _buyPrice;
        sellPrice   = _sellPrice;
        units       = _units;
        sellsTokens = _sellsTokens;
        buysTokens  = _buysTokens;
        ActivatedEvent(sellsTokens, buysTokens);
    }

    // modify trading behavior
    function activate (
        bool _sellsTokens,
        bool _buysTokens
    ) onlyOwner {
        sellsTokens = _sellsTokens;
        buysTokens  = _buysTokens;
        ActivatedEvent(sellsTokens, buysTokens);
    }

    // allows owner to deposit ETH
    // deposit tokens by sending them directly to contract
    // buyers must not send tokens to the contract, use: sell(...)
    function deposit() payable onlyOwner {
        EtherDeposited(msg.value);
    }

    // allow owner to remove trade token
    function withdrawAsset(uint256 _value) onlyOwner returns (bool ok) {
        AssetWithdrawn(_value);
        return ERC20(asset).transfer(owner, _value);
    }

    // allow owner to remove arbitrary tokens
    // included just in case contract receives wrong token
    function withdrawToken(address _token, uint256 _value) onlyOwner returns (bool ok) {
        TokenWithdrawn(_token, _value);
        return ERC20(_token).transfer(owner, _value);
    }

    // allow owner to remove ETH
    function withdraw(uint256 _value) onlyOwner returns (bool ok) {
        if (this.balance >= _value) {
            EtherWithdrawn(_value);
            return owner.send(_value);
        }
    }

    // user buys token with ETH
    function buy() payable {
        if (sellsTokens || msg.sender == owner) {
            uint order    = msg.value / sellPrice;
            uint can_sell = ERC20(asset).balanceOf(address(this)) / units;
            uint256 change = 0;
            if (order > can_sell) {
                change = msg.value - (can_sell * sellPrice);
                order = can_sell;
                if (!msg.sender.send(change)) throw;
            }
            if (order > 0) {
                if(!ERC20(asset).transfer(msg.sender, order * units)) throw;
            }
            AssetBought(msg.sender, msg.value, order * units, change);
        }
        else if (!msg.sender.send(msg.value)) throw;  // return user funds if the contract is not selling
    }

    // user sells token for ETH
    // user must set allowance for this contract before calling
    function sell(uint256 amount) {
        if (buysTokens || msg.sender == owner) {
            uint256 can_buy = this.balance / buyPrice;  // token lots contract can buy
            uint256 order = amount / units;             // token lots available
            if (order > can_buy) order = can_buy;       // adjust order for funds
            if (order > 0) {
                // extract user tokens
                if(!ERC20(asset).transferFrom(msg.sender, address(this), order * units)) throw;
                // pay user
                if(!msg.sender.send(order * buyPrice)) throw;
            }
            AssetSold(msg.sender, amount, order * buyPrice);
        }
    }

    // sending ETH to contract sells ETH to user
    function () payable {
        buy();
    }
}

// This contract deploys TokenTrader contracts and logs the event
contract TokenTraderFactory is Owned {

    event TradeListing(address owner, address addr);
    event TokenWithdrawn(address token, uint256 value);

    mapping(address => bool) _verify;

    function verify(address tradeContract) constant returns (
        bool valid,
        address asset,
        uint256 buyPrice,
        uint256 sellPrice,
        uint256 units,
        bool    sellsTokens,
        bool    buysTokens
    ) {
        valid = _verify[tradeContract];
        if (valid) {
            TokenTrader t = TokenTrader(tradeContract);
            asset       = t.asset();
            buyPrice    = t.buyPrice();
            sellPrice   = t.sellPrice();
            units       = t.units();
            sellsTokens = t.sellsTokens();
            buysTokens  = t.buysTokens();
        }
    }

    function createTradeContract(
        address _asset,
        uint256 _buyPrice,
        uint256 _sellPrice,
        uint256 _units,
        bool    _sellsTokens,
        bool    _buysTokens
    ) returns (address) {
        if (_buyPrice > _sellPrice) throw; // must make profit on spread
        if (_units == 0) throw;            // can't sell zero units
        address trader = new TokenTrader(
            _asset,
            _buyPrice,
            _sellPrice,
            _units,
            _sellsTokens,
            _buysTokens);
        _verify[trader] = true; // record that this factory created the trader
        TokenTrader(trader).transferOwnership(msg.sender); // set the owner to whoever called the function
        TradeListing(msg.sender, trader);
    }

    // allow owner to remove arbitrary tokens
    // included just in case contract receives some tokens
    function withdrawToken(address _token, uint256 _value) onlyOwner returns (bool ok) {
        TokenWithdrawn(_token, _value);
        return ERC20(_token).transfer(owner, _value);
    }

    function () {
        throw;     // Prevents accidental sending of ether to the factory
    }
}


alternate approach

alternate approach

contract ForumContract {

    mapping ( uint => Forum ) public forums;
    // mapping( uint => Message ) public messages;

    uint public forumCount;

    struct Forum {
        address owner;
        string name;
        mapping( uint => Message ) messages;
        uint messageCount;
    }

    struct Message {
        string title;
        string content;
    }

    function createForum( string name ) returns( uint forumID ) {
        forumID = forumCount++;
        Forum f = forums[ forumID ];
        f.name = name;
        f.owner = msg.sender;
    }
    function createMessage( string title, string content, uint forum ) returns( uint messageID ) {

        Forum f = forums[ forum ];
        messageID = f.messageCount++;
        Message m = f.messages[ messageID ];

        m.title = title;
        m.content = content;

    }

    function getMessage( uint forum, uint message ) returns( string content ) {
        Forum f = forums[ forum ];
        Message m = f.messages[ message ];
        content = m.content;
    }

}

contract Forum {

  address public owner;
  string public name;

  struct Topic {
    string title;
    string content;
  }

  mapping ( uint => Topic ) public topics;
  uint public numTopics;

  function Forum( string _name ) {
    name = _name;
    owner = msg.sender;

    numTopics = 0;
  }

  function addTopic( string title, string content ) public returns ( uint topicId ) {

    // topics.push( Topic( title, content, msg.sender  ) );
    topicId = numTopics++;

    Topic topic = topics[topicId];
    topic.title = title;
    topic.content = content;

  }

  function getTopic( uint id ) public returns( string topic_title ) {
      Topic topic = topics[id];
      topic_title = topic.title;
  }

}


fix compilation error

fix compilation error

pragma solidity ^0.4.8;

import "./Ownable.sol";
import "./SafeMath.sol";
import "./ERC20.sol";
import "./TokenSpender.sol";

contract RLC is ERC20, SafeMath, Ownable {

    /* Public variables of the token */
  string public name;       //fancy name
  string public symbol;
  uint8 public decimals;    //How many decimals to show.
  string public version = 'v0.1';
  uint256 public initialSupply;
  address public burnAddress;
  uint256 public totalSupply;
  bool public locked;
  uint public unlockBlock;

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

  // lock transfer during the ICO
  modifier onlyUnlocked() {
    if (msg.sender != owner && locked) throw;
    _;
  }

  /*
   *  The RLC Token created with the time at which the crowdsale end
   */

  function RLC(uint _unlock) {
    // lock the transfer function during the crowdsale
    locked = true;
    unlockBlock=  _unlock;

    initialSupply = 87000000000000000;
    totalSupply = initialSupply;
    balances[msg.sender] = initialSupply;// Give the creator all initial tokens
    name = 'iEx.ec Network Token';        // Set the name for display purposes
    symbol = 'RLC';                       // Set the symbol for display purposes
    decimals = 9;                        // Amount of decimals for display purposes
    burnAddress = 0x1b32000000000000000000000000000000000000;
  }

  function unlock() {
    if (now < unlockBlock) throw;
    if (!locked) throw;   // to allow only 1 call
    locked = false;
  }

  function burn(uint256 _value) returns (bool success){
    balances[msg.sender] = safeSub(balances[msg.sender], _value) ;
    balances[burnAddress] = safeAdd(balances[burnAddress], _value);
    totalSupply = safeSub(totalSupply, _value);
    Transfer(msg.sender, burnAddress, _value);
    return true;
  }

  function transfer(address _to, uint _value) onlyUnlocked returns (bool success) {
    Transfer(msg.sender, _to, _value);
    balances[msg.sender] = safeSub(balances[msg.sender], _value);
    balances[_to] = safeAdd(balances[_to], _value);

    return true;
  }

  function transferFrom(address _from, address _to, uint _value) onlyUnlocked returns (bool success) {
    var _allowance = allowed[_from][msg.sender];

    balances[_to] = safeAdd(balances[_to], _value);
    balances[_from] = safeSub(balances[_from], _value);
    allowed[_from][msg.sender] = safeSub(_allowance, _value);
    Transfer(_from, _to, _value);
    return true;
  }

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

  function approve(address _spender, uint _value) returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
  }

    /* Approve and then comunicate the approved contract in a single tx */
  function approveAndCall(address _spender, uint256 _value, string _extraData, string _extraData2){
      TokenSpender spender = TokenSpender(_spender);
      if (approve(_spender, _value)) {
          spender.receiveApproval(msg.sender, _value, this, _extraData, _extraData2);
      }
  }

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

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

pragma solidity ^0.4.8;

import "./Ownable.sol";
import "./SafeMath.sol";
import "./ERC20.sol";
import "./TokenSpender.sol";

contract RLC is ERC20, SafeMath, Ownable {

    /* Public variables of the token */
  string public name;       //fancy name
  string public symbol;
  uint8 public decimals;    //How many decimals to show.
  string public version = 'v0.1';
  uint256 public initialSupply;
  address public burnAddress;
  uint256 public totalSupply;
  bool public locked;
  uint public unlockBlock;

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

  // lock transfer during the ICO
  modifier onlyUnlocked() {
    if (msg.sender != owner && locked) throw;
    _;
  }

  /*
   *  The RLC Token created with the time at which the crowdsale end
   */

  function RLC(uint _unlock) {
    // for lock the transfer function during the crowdsale
    locked = true;
    unlockBlock =  _unlock;

    initialSupply = 87000000000000000;
    totalSupply = initialSupply;
    balances[msg.sender] = initialSupply;// Give the creator all initial tokens
    name = 'iEx.ec Network Token';        // Set the name for display purposes
    symbol = 'RLC';                       // Set the symbol for display purposes
    decimals = 9;                        // Amount of decimals for display purposes
    burnAddress = 0x1b32000000000000000000000000000000000000;
  }

  function unlock() {
    if (now < endLock) throw;
    if (!locked) throw;   // to allow only 1 call
    locked = false;
  }

  function burn(uint256 _value) returns (bool success){
    balances[msg.sender] = safeSub(balances[msg.sender], _value) ;
    balances[burnAddress] = safeAdd(balances[burnAddress], _value);
    totalSupply = safeSub(totalSupply, _value);
    Transfer(msg.sender, burnAddress, _value);
    return true;
  }

  function transfer(address _to, uint _value) onlyUnlocked returns (bool success) {
    Transfer(msg.sender, _to, _value);
    balances[msg.sender] = safeSub(balances[msg.sender], _value);
    balances[_to] = safeAdd(balances[_to], _value);

    return true;
  }

  function transferFrom(address _from, address _to, uint _value) onlyUnlocked returns (bool success) {
    var _allowance = allowed[_from][msg.sender];

    balances[_to] = safeAdd(balances[_to], _value);
    balances[_from] = safeSub(balances[_from], _value);
    allowed[_from][msg.sender] = safeSub(_allowance, _value);
    Transfer(_from, _to, _value);
    return true;
  }

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

  function approve(address _spender, uint _value) returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
  }

    /* Approve and then comunicate the approved contract in a single tx */
  function approveAndCall(address _spender, uint256 _value, string _extraData, string _extraData2){
      TokenSpender spender = TokenSpender(_spender);
      if (approve(_spender, _value)) {
          spender.receiveApproval(msg.sender, _value, this, _extraData, _extraData2);
      }
  }

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

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


adding distinct events for success and failure of oracle queries.

/*
    Copyright 2017 Phillip A. Elsasser

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

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

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

pragma solidity ^0.4.0;

import "./Creatable.sol";
import "./oraclize/oraclizeAPI.sol";
import "./libraries/MathLib.sol";
import "./libraries/HashLib.sol";

//TODO: fix style issues
//      add accounting for users and positions
//      add failsafe for pool distribution.
//      push as much into library as possible
contract MarketContract is Creatable, usingOraclize  {
    using MathLib for uint256;
    using MathLib for int;
    using HashLib for address;

    struct UserNetPosition {
        address userAddress;
        Position[] positions;   // all open positions (lifo upon exit - allows us to not reindex array!)
        int netPosition;        // net position across all prices / executions
    }

    struct Position {
        uint price;
        int qty;
    }

    struct Order {
        address maker;
        address taker;
        address feeRecipient;
        uint makerFee;
        uint takerFee;
        uint qty;
        uint price;
        uint8 makerSide;            // 0=Buy 1=Sell
        uint expirationTimeStamp;
        bytes32 orderHash;
    }

    // constants
    string public CONTRACT_NAME;
    address public BASE_TOKEN;
    uint public PRICE_CAP;
    uint public PRICE_FLOOR;
    uint public PRICE_DECIMAL_PLACES;   // how to convert the pricing from decimal format (if valid) to integer
    uint public EXPIRATION;
    string public ORACLE_DATA_SOURCE;
    string public ORACLE_QUERY;
    uint public ORACLE_QUERY_REPEAT;
    uint8 constant public BUY_SIDE = 0;
    uint8 constant public SELL_SIDE = 1;
    uint constant public COST_PER_QUERY = 2 finney;    // leave static for now, price of first query from oraclize is 0
    uint constant public QUERY_CALLBACK_GAS = 300000;

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

    // accounting
    mapping(address => UserNetPosition) addressToUserPosition;

    // events
    event OracleQuerySuccess();
    event OracleQueryFailed();
    event UpdatedLastPrice(string price);
    event ContractSettled();

    function MarketContract(
        string contractName,
        address baseToken,
        string oracleDataSource,
        string oracleQuery,
        uint oracleQueryRepeatSeconds,
        uint floorPrice,
        uint capPrice,
        uint priceDecimalPlaces,
        uint secondsToExpiration
    ) payable {

        require(capPrice > floorPrice);
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        CONTRACT_NAME = contractName;
        BASE_TOKEN = baseToken;
        PRICE_CAP = capPrice;
        PRICE_FLOOR = floorPrice;
        EXPIRATION = now + secondsToExpiration;
        ORACLE_DATA_SOURCE = oracleDataSource;
        ORACLE_QUERY = oracleQuery;
        ORACLE_QUERY_REPEAT = oracleQueryRepeatSeconds;
        PRICE_DECIMAL_PLACES = priceDecimalPlaces;
        require(checkSufficientStartingBalance(secondsToExpiration));
        queryOracle();  // schedules recursive calls to oracle
    }

    function __callback(bytes32 queryID, string result, bytes proof) {
        require(validQueryIDs[queryID]);
        require(msg.sender == oraclize_cbAddress());
        lastPriceQueryResult = result;
        lastPrice = parseInt(result, PRICE_DECIMAL_PLACES);
        UpdatedLastPrice(result);
        delete validQueryIDs[queryID];
        checkSettlement();
        if (!isExpired) {
            queryOracle();  // set up our next query
        }
    }

    function trade(address maker, address taker) {
        require(maker != address(0) && maker != taker);     // do not allow self trade
        // TODO validate orders, etc
    }

    function updatePositions(address maker, address taker, int qty, uint price) private {
        updatePosition(addressToUserPosition[maker], qty, price);
        // continue process for taker, but qty is opposite sign for taker
        updatePosition(addressToUserPosition[taker], qty * -1, price);
    }

    function updatePosition(UserNetPosition storage userNetPosition, int qty, uint price) private {
        if(userNetPosition.netPosition == 0 ||  userNetPosition.netPosition.isSameSign(qty)) {
            // new position or adding to open pos, no collateral returned
            userNetPosition.positions.push(Position(price, newNetPos)); //append array with new position
        }
        else {
            // opposite side from open position, reduce, flattened, or flipped.
            if(userNetPosition.netPosition >= qty * -1) { // pos is reduced of flattened
                reduceUserNetPosition(userNetPosition, qty, price);
            } else {    // pos is flipped, reduce and then create new open pos!
                reduceUserNetPosition(userNetPosition, userNetPosition.netPosition * -1, price); // flatten completely
                int newNetPos = userNetPosition.netPosition + qty;            // the portion remaining after flattening
                userNetPosition.positions.push(Position(price, newNetPos));   // append array with new position
            }
        }
        userNetPosition.netPosition += qty;
    }

    function reduceUserNetPosition(UserNetPosition storage userNetPos, int qty, uint price) private {
        int qtyToReduce = qty;
        assert(userNetPos.positions.length != 0);  // sanity check
        while(qtyToReduce != 0) {
            Position storage position = userNetPos.positions[userNetPos.positions.length - 1];  // get the last pos (LIFO)
            if(position.qty.abs() <= qtyToReduce.abs()) { // this position is completely consumed!
                qtyToReduce = qtyToReduce + position.qty;
                // TODO: work on refunding correct amount of collateral.
                userNetPos.positions.length--;  // remove this position from our array.
            }
            else {  // this position stays, just reduce the qty.
                position.qty += qtyToReduce;
                // TODO: return collateral
                //qtyToReduce = 0; // completely reduced now!
                break;
            }
        }
    }

    function commitCollateralToPool(address fromAddress, uint collateralAmount) private
    {

    }

    function withdrawCollateralFromPool(address toAddress, uint collateralAmount) private
    {

    }

    function queryOracle() private
    {
        if (oraclize_getPrice(ORACLE_DATA_SOURCE) > this.balance) {
            OracleQueryFailed();
            lastPriceQueryResult = "FAILED"; //TODO: failsafe
        } else {
            OracleQuerySuccess();
            bytes32 queryId = oraclize_query(ORACLE_QUERY_REPEAT, ORACLE_DATA_SOURCE, ORACLE_QUERY, QUERY_CALLBACK_GAS);
            validQueryIDs[queryId] = true;
        }
    }

    function checkSettlement() private
    {
        if(isExpired)   // already expired.
            return;

        if(now > EXPIRATION) {
            isExpired = true;   // time based expiration has occurred.
        } else if(lastPrice >= PRICE_CAP || lastPrice <= PRICE_FLOOR) {
            isExpired = true;   // we have breached/touched our pricing bands
        }

        if(isExpired) {
            settleContract();
        }
    }

    function settleContract() private
    {
        // TODO: build mechanism for distribution of collateral
        ContractSettled();
    }

    // for now lets require alot of padding for the settlement,
    function checkSufficientStartingBalance(uint secondsToExpiration) private returns (bool isSufficient) {
        //uint costPerQuery = oraclize_getPrice(ORACLE_DATA_SOURCE); this doesn't work prior to first query(its free)
        uint expectedNoOfQueries = secondsToExpiration / ORACLE_QUERY_REPEAT;
        uint approxGasRequired = COST_PER_QUERY * expectedNoOfQueries;
        return this.balance > (approxGasRequired * 2);
    }
}

/*
    Copyright 2017 Phillip A. Elsasser

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

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

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

pragma solidity ^0.4.0;

import "./Creatable.sol";
import "./oraclize/oraclizeAPI.sol";
import "./libraries/MathLib.sol";
import "./libraries/HashLib.sol";

//TODO: fix style issues
//      add accounting for users and positions
//      add failsafe for pool distribution.
//      push as much into library as possible
contract MarketContract is Creatable, usingOraclize  {
    using MathLib for uint256;
    using MathLib for int;
    using HashLib for address;

    struct UserNetPosition {
        address userAddress;
        Position[] positions;   // all open positions (lifo upon exit - allows us to not reindex array!)
        int netPosition;        // net position across all prices / executions
    }

    struct Position {
        uint price;
        int qty;
    }

    struct Order {
        address maker;
        address taker;
        address feeRecipient;
        uint makerFee;
        uint takerFee;
        uint qty;
        uint price;
        uint8 makerSide;            // 0=Buy 1=Sell
        uint expirationTimeStamp;
        bytes32 orderHash;
    }

    // constants
    string public CONTRACT_NAME;
    address public BASE_TOKEN;
    uint public PRICE_CAP;
    uint public PRICE_FLOOR;
    uint public PRICE_DECIMAL_PLACES;   // how to convert the pricing from decimal format (if valid) to integer
    uint public EXPIRATION;
    string public ORACLE_DATA_SOURCE;
    string public ORACLE_QUERY;
    uint public ORACLE_QUERY_REPEAT;
    uint8 constant public BUY_SIDE = 0;
    uint8 constant public SELL_SIDE = 1;
    uint constant public COST_PER_QUERY = 2 finney;    // leave static for now, price of first query from oraclize is 0
    uint constant public QUERY_CALLBACK_GAS = 300000;

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

    // accounting
    mapping(address => UserNetPosition) addressToUserPosition;

    // events
    event NewOracleQuery(string description);
    event UpdatedLastPrice(string price);
    event ContractSettled();

    function MarketContract(
        string contractName,
        address baseToken,
        string oracleDataSource,
        string oracleQuery,
        uint oracleQueryRepeatSeconds,
        uint floorPrice,
        uint capPrice,
        uint priceDecimalPlaces,
        uint secondsToExpiration
    ) payable {

        require(capPrice > floorPrice);
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        CONTRACT_NAME = contractName;
        BASE_TOKEN = baseToken;
        PRICE_CAP = capPrice;
        PRICE_FLOOR = floorPrice;
        EXPIRATION = now + secondsToExpiration;
        ORACLE_DATA_SOURCE = oracleDataSource;
        ORACLE_QUERY = oracleQuery;
        ORACLE_QUERY_REPEAT = oracleQueryRepeatSeconds;
        PRICE_DECIMAL_PLACES = priceDecimalPlaces;
        require(checkSufficientStartingBalance(secondsToExpiration));
        queryOracle();  // schedules recursive calls to oracle
    }

    function __callback(bytes32 queryID, string result, bytes proof) {
        require(validQueryIDs[queryID]);
        require(msg.sender == oraclize_cbAddress());
        lastPriceQueryResult = result;
        lastPrice = parseInt(result, PRICE_DECIMAL_PLACES);
        UpdatedLastPrice(result);
        delete validQueryIDs[queryID];
        checkSettlement();
        if (!isExpired) {
            queryOracle();  // set up our next query
        }
    }

    function trade(address maker, address taker) {
        require(maker != address(0) && maker != taker);     // do not allow self trade
        // TODO validate orders, etc
    }

    function updatePositions(address maker, address taker, int qty, uint price) private {
        updatePosition(addressToUserPosition[maker], qty, price);
        // continue process for taker, but qty is opposite sign for taker
        updatePosition(addressToUserPosition[taker], qty * -1, price);
    }

    function updatePosition(UserNetPosition storage userNetPosition, int qty, uint price) private {
        if(userNetPosition.netPosition == 0 ||  userNetPosition.netPosition.isSameSign(qty)) {
            // new position or adding to open pos, no collateral returned
            userNetPosition.positions.push(Position(price, newNetPos)); //append array with new position
        }
        else {
            // opposite side from open position, reduce, flattened, or flipped.
            if(userNetPosition.netPosition >= qty * -1) { // pos is reduced of flattened
                reduceUserNetPosition(userNetPosition, qty, price);
            } else {    // pos is flipped, reduce and then create new open pos!
                reduceUserNetPosition(userNetPosition, userNetPosition.netPosition * -1, price); // flatten completely
                int newNetPos = userNetPosition.netPosition + qty;            // the portion remaining after flattening
                userNetPosition.positions.push(Position(price, newNetPos));   // append array with new position
            }
        }
        userNetPosition.netPosition += qty;
    }

    function reduceUserNetPosition(UserNetPosition storage userNetPos, int qty, uint price) private {
        int qtyToReduce = qty;
        assert(userNetPos.positions.length != 0);  // sanity check
        while(qtyToReduce != 0) {
            Position storage position = userNetPos.positions[userNetPos.positions.length - 1];  // get the last pos (LIFO)
            if(position.qty.abs() <= qtyToReduce.abs()) { // this position is completely consumed!
                qtyToReduce = qtyToReduce + position.qty;
                // TODO: work on refunding correct amount of collateral.
                userNetPos.positions.length--;  // remove this position from our array.
            }
            else {  // this position stays, just reduce the qty.
                position.qty += qtyToReduce;
                // TODO: return collateral
                //qtyToReduce = 0; // completely reduced now!
                break;
            }
        }
    }

    function commitCollateralToPool(address fromAddress, uint collateralAmount) private
    {

    }

    function withdrawCollateralFromPool(address toAddress, uint collateralAmount) private
    {

    }

    function queryOracle() private
    {
        if (oraclize_getPrice(ORACLE_DATA_SOURCE) > this.balance) {
            NewOracleQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
            lastPriceQueryResult = "FAILED"; //TODO: failsafe
        } else {
            NewOracleQuery("Oraclize query was sent, standing by for the answer..");
            bytes32 queryId = oraclize_query(ORACLE_QUERY_REPEAT, ORACLE_DATA_SOURCE, ORACLE_QUERY, QUERY_CALLBACK_GAS);
            validQueryIDs[queryId] = true;
        }
    }

    function checkSettlement() private
    {
        if(isExpired)   // already expired.
            return;

        if(now > EXPIRATION) {
            isExpired = true;   // time based expiration has occurred.
        } else if(lastPrice >= PRICE_CAP || lastPrice <= PRICE_FLOOR) {
            isExpired = true;   // we have breached/touched our pricing bands
        }

        if(isExpired) {
            settleContract();
        }
    }

    function settleContract() private
    {
        // TODO: build mechanism for distribution of collateral
        ContractSettled();
    }

    // for now lets require alot of padding for the settlement,
    function checkSufficientStartingBalance(uint secondsToExpiration) private returns (bool isSufficient) {
        //uint costPerQuery = oraclize_getPrice(ORACLE_DATA_SOURCE); this doesn't work prior to first query(its free)
        uint expectedNoOfQueries = secondsToExpiration / ORACLE_QUERY_REPEAT;
        uint approxGasRequired = COST_PER_QUERY * expectedNoOfQueries;
        return this.balance > (approxGasRequired * 2);
    }
}


contract was minimized

contract was minimized

pragma solidity 0.4.18;

import "github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol";
import "github.com/OpenZeppelin/zeppelin-solidity/contracts/token/ERC20Basic.sol";
import "github.com/OpenZeppelin/zeppelin-solidity/contracts/token/ERC20.sol";
import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol";

contract ApprovalContract is ERC20 {
    using SafeMath for uint256;

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

    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     *
     * Beware that changing an allowance with this method brings the risk that someone may use both the old
     * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
     * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     */
    function approve(address _spender, uint256 _value) public returns (bool) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return A uint256 specifying the amount of tokens still available for the spender.
     */
    function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
    }

    /**
     * approve should be called when allowed[_spender] == 0. To increment
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     */
    function increaseApproval (address _spender, uint _addedValue) public
    returns (bool success) {
        allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }

    function decreaseApproval (address _spender, uint _subtractedValue) public
    returns (bool success) {
        uint oldValue = allowed[msg.sender][_spender];
        if (_subtractedValue > oldValue) {
            allowed[msg.sender][_spender] = 0;
        } else {
            allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
        }
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
}

/**
 * @title Mintable token
 * @dev Simple ERC20 Token example, with mintable token creation
 * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
 */
contract MintableToken is ApprovalContract, Ownable {

    uint256 public hardCap;
    mapping(address => uint256) public balances;

    event Mint(address indexed to, uint256 amount);

    modifier canMint() {
        require(totalSupply == 0);
        _;
    }

    /**
     * @dev Function to mint tokens
     * @param _to The address that will receive the minted tokens.
     * @param _amount The amount of tokens to mint.
     * @return A boolean that indicates if the operation was successful.
     */
    function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
        require(_amount < hardCap);
        totalSupply = totalSupply.add(_amount);
        balances[_to] = balances[_to].add(_amount);
        Mint(_to, _amount);
        Transfer(0x0, _to, _amount);
        return true;
    }
}

/**
 * @title Vesting token
 * @dev TODO.
 */
contract Vesting is MintableToken {

    event VestingMemberAdded(address indexed _address, uint256 _amount, uint _start, uint _end);

    struct _Vesting {
        uint256 totalSum;     //total amount
        uint256 start;        //start block
        uint256 end;          //end block
        uint256 usedAmount;   //the amount of paid payments
    }

    mapping (address => _Vesting ) public vestingMembers;

    function addVestingMember(
    address _address,
    uint256 _amount,
    uint256 _start,
    uint256 _end
    ) onlyOwner public returns (bool) {
        require(
        _address != address(0) &&
        _amount > 0 &&
        _start < _end &&
        vestingMembers[_address].totalSum == 0 &&
        balances[msg.sender] > _amount
        );

        balances[msg.sender] = balances[msg.sender].sub(_amount);

        vestingMembers[_address].totalSum = _amount;    //total amount
        vestingMembers[_address].start = _start;        //start block
        vestingMembers[_address].end = _end;            //end block
        vestingMembers[_address].usedAmount = 0;        //the amount of paid payments

        VestingMemberAdded(_address, _amount, _start, _end);

        return true;
    }

    function currentPart(address _address) private constant returns (uint256) {
        if (vestingMembers[_address].totalSum == 0) {
            return 0;
        }
        if (block.number >= vestingMembers[_address].end) {
            return vestingMembers[_address].totalSum.sub(vestingMembers[_address].usedAmount);
        }

        return vestingMembers[_address].totalSum
        .mul(block.number - vestingMembers[_address].start)
        .div(vestingMembers[_address].end - vestingMembers[_address].start)
        .sub(vestingMembers[_address].usedAmount);
    }

    function subFromBalance(address _address, uint256 _amount) private returns (uint256) {
        require(_address != address(0));

        if (vestingMembers[_address].totalSum == 0) {
            balances[_address] = balances[_address].sub(_amount);
            return balances[_address];
        }
        uint256 summary = balanceOf(_address);
        require(summary >= _amount);

        if (balances[_address] > _amount) {
            balances[_address] = balances[_address].sub(_amount);
        } else {
            uint256 part = currentPart(_address);
            if (block.number >= vestingMembers[_address].end) {
                vestingMembers[_address].totalSum = 0;          //total amount
                vestingMembers[_address].start = 0;             //start block
                vestingMembers[_address].end = 0;               //end block
                vestingMembers[_address].usedAmount = 0;        //the amount of paid payments
            } else {
                vestingMembers[_address].usedAmount = vestingMembers[_address].usedAmount.add(part);
            }
            balances[_address] = balances[_address].add(part).sub(_amount);
        }

        return balances[_address];
    }

    function balanceOf(address _owner) public constant returns (uint256 balance) {
        if (vestingMembers[_owner].totalSum == 0) {
            return balances[_owner];
        } else {
            return balances[_owner].add(currentPart(_owner));
        }
    }

    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balanceOf(msg.sender));

        subFromBalance(msg.sender, _value);

        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));

        uint256 _allowance = allowed[_from][msg.sender];

        subFromBalance(_from, _value);

        balances[_to] = balances[_to].add(_value);
        allowed[_from][msg.sender] = _allowance.sub(_value);
        Transfer(_from, _to, _value);
        return true;
    }
}

contract DMToken is Vesting {

    string public name = "DMarket Token";
    string public symbol = "MARK";
    uint256 public decimals = 8;

    function DMToken() public {
        hardCap = 15644283100000000;
    }

    function multiTransfer(address[] recipients, uint256[] amounts) public onlyOwner {
        require(recipients.length == amounts.length);
        uint256 sum = 0;
        for (uint i = 0; i < amounts.length; i++) {
            require(recipients[i] != address(0));
            sum += amounts[i];
        }
        require(sum <= balances[msg.sender]);
        for (i = 0; i < recipients.length; i++) {
            transfer(recipients[i], amounts[i]);
        }
    }

    function multiVesting(
    address[] _address,
    uint256[] _amount,
    uint256[] _start,
    uint256[] _end
    ) public onlyOwner {
        require(
        _address.length == _amount.length &&
        _address.length == _start.length &&
        _address.length == _end.length
        );

        uint256 sum = 0;
        for (uint i = 0; i < _amount.length; i++) {
            require(_address[i] != address(0));
            sum += _amount[i];
        }
        require(sum <= balances[msg.sender]);

        for (i = 0; i < _address.length; i++) {
            addVestingMember(_address[i], _amount[i], _start[i], _end[i]);
        }
    }
}

pragma solidity 0.4.18;

/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a * b;
        assert(a == 0 || c / a == b);
        return c;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // assert(b > 0); // Solidity automatically throws when dividing by 0
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        return c;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }
}

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
    address public owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
     * account.
     */
    function Ownable() public {
        owner = msg.sender;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function transferOwnership(address newOwner) onlyOwner public {
        require(newOwner != address(0));
        OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }
}

/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
    uint256 public totalSupply;
    function balanceOf(address who) public constant returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 is ERC20Basic {
    function allowance(address owner, address spender) public constant returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract ApprovalContract is ERC20 {
    using SafeMath for uint256;

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

    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     *
     * Beware that changing an allowance with this method brings the risk that someone may use both the old
     * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
     * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     */
    function approve(address _spender, uint256 _value) public returns (bool) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return A uint256 specifying the amount of tokens still available for the spender.
     */
    function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
    }

    /**
     * approve should be called when allowed[_spender] == 0. To increment
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     */
    function increaseApproval (address _spender, uint _addedValue) public
    returns (bool success) {
        allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }

    function decreaseApproval (address _spender, uint _subtractedValue) public
    returns (bool success) {
        uint oldValue = allowed[msg.sender][_spender];
        if (_subtractedValue > oldValue) {
            allowed[msg.sender][_spender] = 0;
        } else {
            allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
        }
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
}

/**
 * @title Mintable token
 * @dev Simple ERC20 Token example, with mintable token creation
 * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
 */
contract MintableToken is ApprovalContract, Ownable {

    uint256 public hardCap;
    mapping(address => uint256) public balances;

    event Mint(address indexed to, uint256 amount);

    modifier canMint() {
        require(totalSupply == 0);
        _;
    }

    /**
     * @dev Function to mint tokens
     * @param _to The address that will receive the minted tokens.
     * @param _amount The amount of tokens to mint.
     * @return A boolean that indicates if the operation was successful.
     */
    function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
        require(_amount < hardCap);
        totalSupply = totalSupply.add(_amount);
        balances[_to] = balances[_to].add(_amount);
        Mint(_to, _amount);
        Transfer(0x0, _to, _amount);
        return true;
    }
}

/**
 * @title Vesting token
 * @dev TODO.
 */
contract Vesting is MintableToken {

    event VestingMemberAdded(address indexed _address, uint256 _amount, uint _start, uint _end);

    struct _Vesting {
        uint256 totalSum;     //total amount
        uint256 start;        //start block
        uint256 end;          //end block
        uint256 usedAmount;   //the amount of paid payments
    }

    mapping (address => _Vesting ) public vestingMembers;

    function addVestingMember(
    address _address,
    uint256 _amount,
    uint256 _start,
    uint256 _end
    ) onlyOwner public returns (bool) {
        require(
        _address != address(0) &&
        _amount > 0 &&
        _start < _end &&
        vestingMembers[_address].totalSum == 0 &&
        balances[msg.sender] > _amount
        );

        balances[msg.sender] = balances[msg.sender].sub(_amount);

        vestingMembers[_address].totalSum = _amount;    //total amount
        vestingMembers[_address].start = _start;        //start block
        vestingMembers[_address].end = _end;            //end block
        vestingMembers[_address].usedAmount = 0;        //the amount of paid payments

        VestingMemberAdded(_address, _amount, _start, _end);

        return true;
    }

    function currentPart(address _address) private constant returns (uint256) {
        if (vestingMembers[_address].totalSum == 0) {
            return 0;
        }
        if (block.number >= vestingMembers[_address].end) {
            return vestingMembers[_address].totalSum.sub(vestingMembers[_address].usedAmount);
        }

        return vestingMembers[_address].totalSum
        .mul(block.number - vestingMembers[_address].start)
        .div(vestingMembers[_address].end - vestingMembers[_address].start)
        .sub(vestingMembers[_address].usedAmount);
    }

    function subFromBalance(address _address, uint256 _amount) private returns (uint256) {
        require(_address != address(0));

        if (vestingMembers[_address].totalSum == 0) {
            balances[_address] = balances[_address].sub(_amount);
            return balances[_address];
        }
        uint256 summary = balanceOf(_address);
        require(summary >= _amount);

        if (balances[_address] > _amount) {
            balances[_address] = balances[_address].sub(_amount);
        } else {
            uint256 part = currentPart(_address);
            if (block.number >= vestingMembers[_address].end) {
                vestingMembers[_address].totalSum = 0;          //total amount
                vestingMembers[_address].start = 0;             //start block
                vestingMembers[_address].end = 0;               //end block
                vestingMembers[_address].usedAmount = 0;        //the amount of paid payments
            } else {
                vestingMembers[_address].usedAmount = vestingMembers[_address].usedAmount.add(part);
            }
            balances[_address] = balances[_address].add(part).sub(_amount);
        }

        return balances[_address];
    }

    function balanceOf(address _owner) public constant returns (uint256 balance) {
        if (vestingMembers[_owner].totalSum == 0) {
            return balances[_owner];
        } else {
            return balances[_owner].add(currentPart(_owner));
        }
    }

    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balanceOf(msg.sender));

        subFromBalance(msg.sender, _value);

        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));

        uint256 _allowance = allowed[_from][msg.sender];

        subFromBalance(_from, _value);

        balances[_to] = balances[_to].add(_value);
        allowed[_from][msg.sender] = _allowance.sub(_value);
        Transfer(_from, _to, _value);
        return true;
    }
}

contract DMToken is Vesting {

    string public name = "DMarket Token";
    string public symbol = "MARK";
    uint256 public decimals = 8;

    function DMToken() public {
        hardCap = 15644283100000000;
    }

    function multiTransfer(address[] recipients, uint256[] amounts) public onlyOwner {
        require(recipients.length == amounts.length);
        uint256 sum = 0;
        for (uint i = 0; i < amounts.length; i++) {
            require(recipients[i] != address(0));
            sum += amounts[i];
        }
        require(sum <= balances[msg.sender]);
        for (i = 0; i < recipients.length; i++) {
            transfer(recipients[i], amounts[i]);
        }
    }

    function multiVesting(
    address[] _address,
    uint256[] _amount,
    uint256[] _start,
    uint256[] _end
    ) public onlyOwner {
        require(
        _address.length == _amount.length &&
        _address.length == _start.length &&
        _address.length == _end.length
        );

        uint256 sum = 0;
        for (uint i = 0; i < _amount.length; i++) {
            require(_address[i] != address(0));
            sum += _amount[i];
        }
        require(sum <= balances[msg.sender]);

        for (i = 0; i < _address.length; i++) {
            addVestingMember(_address[i], _amount[i], _start[i], _end[i]);
        }
    }
}


Added currentRuleOf method for DAOMarketRegulator

import 'market/MarketRegulator.sol';
import 'market/MarketRule.sol';
import 'lib/Voting.sol';
import 'dao/Core.sol';
import 'creator/CreatorDAOMarketAgent.sol';

/**
 * @title The DAO market regulator is a market regulator with voting procedure
 */
contract DAOMarketRegulator is MarketRegulator {
    /* The DAO shares token */
    Token public shares;

    /* The DAO Core register */
    Core public core;

    /* The rule poll by asset address */
    mapping(address => Voting.Poll) ruleOf;
    using Voting for Voting.Poll;

    /**
     * @dev Rule by asset getter
     * @param _asset is asset address
     * @return rule address or `0x` when no rule setted
     */
    function currentRuleOf(address _asset) constant returns (address)
    { return ruleOf[_asset].current(); }

    /**
     * @dev DAO Market regulator
     * @param _shares is a share holders token for voting actions
     * @param _core is a DAO core ref for asset exist checks
     * @param _market is a DAO market address
     * @param _dao_credits is a common traded asset
     */
    function DAOMarketRegulator(address _shares, address _core,
                                address _market, address _dao_credits)
            MarketRegulator(_market, _dao_credits) {
        shares = Token(_shares);
        core   = Core(_core);
    }

    event LotPlaced(address indexed sender, address indexed lot);

    /**
     * @dev Append new lot into market lot list
     * @param _seller is a seller address
     * @param _sale the token to sale by this lot
     * @param _value amount of saled tokens
     * @param _price how many `_buy` tokens will send for one `_sale`
     * @return new lot address
     */
    function append(address _seller, address _sale,
                    uint _value, uint _price) returns (Lot) {
        if (!core.contains(_sale)) throw;

        var lot = market.append(_seller, _sale, credits, _value, _price);
        LotPlaced(msg.sender, lot);
        return lot;
    }

    /**
     * @dev Sign a contract with sender for trading on market
     * @return `MarketAgent` instance
     */
    function sign() returns (MarketAgent) {
        // Make a new market agent
        var agent = CreatorDAOMarketAgent.create(this);

        // Store agent address for the future usage
        agents.append(agent);

        // Delegate agent to sender
        agent.delegate(msg.sender);

        // Notify client for the new agent
        MarketAgentSign(msg.sender, agent);

        // Return agent address
        return agent;
    }

    /**
     * @dev this event emmitted for every trade based emission
     */
    event DealDoneEmission(uint _value);

    /**
     * @dev Deal done callback, market regulation is maked according
     *      the rules taked from poll stack
     * @param _lot is deal description
     */
    function dealDone(Lot _lot) onlyAgents {
        // Select the traded asset
        var asset = _lot.buy() == credits ? _lot.sale() : _lot.buy();

        // Select current trade rule for traded asset
        var rule = ruleOf[asset].current();
        if (rule != 0) {
            // Get emission value based on current rule
            var emission = MarketRule(rule).getEmission(_lot);

            // Make emission and transfer to owner
            credits.emission(emission);
            credits.transfer(owner, emission);

            // Notify for emission value
            DealDoneEmission(emission);
        }
    }

    /**
     * @dev Increase poll for given asset
     * @param _asset asset for applying the rule
     * @param _rule the rule is maked for given asset
     * @param _count how much shares given for increase
     */
    function pollUp(address _asset, MarketRule _rule, uint _count)
    { ruleOf[_asset].up(msg.sender, _rule, shares, _count); }

    /**
     * @dev Decrease poll for given asset
     * @param _asset asset for applying the rule
     * @param _count count of refunded shares
     */
    function pollDown(address _asset, uint _count)
    { ruleOf[_asset].down(msg.sender, shares, _count); }
}

import 'market/MarketRegulator.sol';
import 'market/MarketRule.sol';
import 'lib/Voting.sol';
import 'dao/Core.sol';
import 'creator/CreatorDAOMarketAgent.sol';

/**
 * @title The DAO market regulator is a market regulator with voting procedure
 */
contract DAOMarketRegulator is MarketRegulator {
    /* The DAO shares token */
    Token public shares;

    /* The DAO Core register */
    Core public core;

    /* The rule poll by asset address */
    mapping(address => Voting.Poll) ruleOf;
    using Voting for Voting.Poll;

    function DAOMarketRegulator(address _shares, address _core,
                                address _market, address _dao_credits)
            MarketRegulator(_market, _dao_credits) {
        shares = Token(_shares);
        core   = Core(_core);
    }

    event LotPlaced(address indexed sender, address indexed lot);

    /**
     * @dev Append new lot into market lot list
     * @param _seller is a seller address
     * @param _sale the token to sale by this lot
     * @param _value amount of saled tokens
     * @param _price how many `_buy` tokens will send for one `_sale`
     * @return new lot address
     */
    function append(address _seller, address _sale,
                    uint _value, uint _price) returns (Lot) {
        if (!core.contains(_sale)) throw;

        var lot = market.append(_seller, _sale, credits, _value, _price);
        LotPlaced(msg.sender, lot);
        return lot;
    }

    /**
     * @dev Sign a contract with sender for trading on market
     * @return `MarketAgent` instance
     */
    function sign() returns (MarketAgent) {
        // Make a new market agent
        var agent = CreatorDAOMarketAgent.create(this);

        // Store agent address for the future usage
        agents.append(agent);

        // Delegate agent to sender
        agent.delegate(msg.sender);

        // Notify client for the new agent
        MarketAgentSign(msg.sender, agent);

        // Return agent address
        return agent;
    }

    /**
     * @dev this event emmitted for every trade based emission
     */
    event DealDoneEmission(uint _value);

    /**
     * @dev Deal done callback, market regulation is maked according
     *      the rules taked from poll stack
     * @param _lot is deal description
     */
    function dealDone(Lot _lot) onlyAgents {
        // Select the traded asset
        var asset = _lot.buy() == credits ? _lot.sale() : _lot.buy();

        // Select current trade rule for traded asset
        var rule = ruleOf[asset].current();
        if (rule != 0) {
            // Get emission value based on current rule
            var emission = MarketRule(rule).getEmission(_lot);

            // Make emission and transfer to owner
            credits.emission(emission);
            credits.transfer(owner, emission);

            // Notify for emission value
            DealDoneEmission(emission);
        }
    }

    /**
     * @dev Increase poll for given asset
     * @param _asset asset for applying the rule
     * @param _rule the rule is maked for given asset
     * @param _count how much shares given for increase
     */
    function pollUp(Knowledge _asset, MarketRule _rule, uint _count)
    { ruleOf[_asset].up(msg.sender, _rule, shares, _count); }

    /**
     * @dev Decrease poll for given asset
     * @param _asset asset for applying the rule
     * @param _count count of refunded shares
     */
    function pollDown(Knowledge _asset, uint _count)
    { ruleOf[_asset].down(msg.sender, shares, _count); }
}


Fix Allowances

Fix Allowances

pragma solidity ^0.4.4;

contract FamilyWallet {
  // TYPES

  // Still Debating using mappings/array - or both for adult/children.
  // Right now using both.
  address _wallet = this;
  mapping (address => Adult) _adults;
  mapping (address => Child) _children;
  Adult[] _listOfAdults;
  Child[] public _listOfChildren;
  uint _allowance;
  uint _allowancePeriodStart;
  uint _allowancePeriodEnd;
  uint _defaultAllowance;
  uint _duration;

  // TODO: Add _requireTasksForAllowance
  // This would require "tasksCompleted" in Child Object to be true before allowance can be paid
  // bool _requireTasksForAllowance;

  struct Child {
    uint allowance;
    address addr;
    uint allowanceDue;
    //bool tasksCompleted (will be added when  _requireTasksForAllowance is added)
  }

  struct Adult {
    address addr;
    bool approveRefund;
    uint256 balanceOf;
  }

  // EVENTS
  event MoneyReceived(uint payment, address sender);
  event AllowancePaid(uint allowance, address receiver);
  event NewAllowancePeriod(uint start, uint end);

  // MODIFIERS

  // Adult Confirmation modifier
  // Confirmation that message sender is an adult
  modifier isAdult() {
    for (uint i = 0; i < _listOfAdults.length; i++) {
      if (msg.sender == _listOfAdults[i].addr) _;
    }
  }

  // Child Confirmation modifier
  // Confirmation that message sender is a child
  modifier isChild() {
    for (uint i = 0; i < _listOfChildren.length; i++) {
      if (msg.sender == _listOfChildren[i].addr) _;
    }
  }

  // Refundable Modifier
  // Confirmation that each ADULT has approved the ability to withdraw
  // funds from the contract.
  modifier refundable() {
    for (uint i = 0; i < _listOfAdults.length; i++) {
        address adultAddress = _listOfAdults[i].addr;
        if(!_adults[adultAddress].approveRefund) throw;
     }
     _;
  }
  // METHODS

  // Constructor Method Initialize when contract is created
  function FamilyWallet(
    address[] adults,
    address[] children,
    uint defaultAllowanceInEther,
    uint durationInDays,
    bool firstAllowancePayment // Set true if include first payment when contract created
  ) {
    // Loop through adult array and include address in mapping and array
    _defaultAllowance = defaultAllowanceInEther * 1 ether;
    for (uint j = 0; j < adults.length; j++) {
      Adult memory adult;
      adult.addr = adults[j];
      _listOfAdults.push(adult);
      _adults[adult.addr] = adult;
    }
    // Loop through children array and include address in mapping and array
    for (uint i = 0; i < children.length; i++) {
      Child memory child;
      child.addr = children[i];
      child.allowance = _defaultAllowance;
      if(firstAllowancePayment) child.allowanceDue = _defaultAllowance;
      _listOfChildren.push(child);
      _children[child.addr] = child;
    }

    // Set Durations
    _allowancePeriodStart = now;
    _duration = durationInDays * 1 days;
    _allowancePeriodEnd = now + _duration;
  }

  // Make payment on allowance start,or when user calls getAllowance?
  // Right now child must call get allowance to receive alowance
  function nextAllowancePeriod(bool force) returns (bool) {
    if((now < _allowancePeriodEnd) && (!force)) throw;
    _allowancePeriodStart = _allowancePeriodEnd;
    _allowancePeriodEnd = _allowancePeriodEnd + _duration;
    for (uint i = 0; i < _listOfChildren.length; i++) {
      _children[_listOfChildren[i].addr].allowanceDue +=  _children[ _listOfChildren[i].addr].allowance;
    }
    NewAllowancePeriod(_allowancePeriodStart, _allowancePeriodEnd);
    return true;
  }

  function getAllowance() isChild {
    Child memory child = _children[msg.sender];
    if(child.allowanceDue == 0) throw;
    if(child.addr.send(child.allowanceDue)) throw;
    child.allowanceDue = 0;
    AllowancePaid(child.allowanceDue, msg.sender);
  }

  function approveRefund() isAdult {
    for (uint i = 0; i < _listOfAdults.length; i++) {
        if(msg.sender == _listOfAdults[i].addr) _listOfAdults[i].approveRefund = true;
     }
  }

  // Sends wallet balance to message sender
  // TODO:  Amount refunded should be same weighted average as amount deposited
  //        Rather that first person takes all.
  function refundBalance(address addr) isAdult refundable {
     if(_adults[msg.sender].addr.send(_wallet.balance)) throw;
  }

  // TESTING FUNCTIONS
  // NOT NECESSARY FOR DEPLOYMENTS
  function getChild() returns (address)  {
    return _listOfChildren[0].addr;
  }

  function getAllowanceAmount(address addr) returns(uint) {
    return _children[addr].allowanceDue;
  }

  function getChildsAmount(address addr) returns(uint) {
    return _children[addr].allowance;
  }

  function getDefaultAllowance(string addr) returns(uint) {
    return _defaultAllowance;
  }

  // Fallback method, send event once mony is paid
  function() payable {
    _adults[msg.sender].balanceOf += msg.value;
    MoneyReceived(msg.value, msg.sender);
  }
// TODO:    Allow Removal of Childen/Adult
// REASON:  In case of mental/physical inability of adult
//          to withdraw funds on his own behalf (Lost Private Key/Death)
//          Allow Remove of his account in order to be able to let other
//          adults withdraw funds. Contributions will be evenly split among
//          Other adults.
// NOTES:   Must allow a "checkin" method of some sort, if adult does not
//          check in after a period of time - allow other to vote him out
//          Otherwise if a user is checked in, there is no way he can be
//          voted out of the family.

}

pragma solidity ^0.4.4;

contract FamilyWallet {
  // TYPES

  // Still Debating using mappings/array - or both for adult/children.
  // Right now using both.
  address _wallet = this;
  mapping (address => Adult) _adults;
  mapping (address => Child) _children;
  Adult[] _listOfAdults;
  Child[] _listOfChildren;
  uint _allowance;
  uint _allowancePeriodStart;
  uint _allowancePeriodEnd;
  uint _duration;

  // TODO: Add _requireTasksForAllowance
  // This would require "tasksCompleted" in Child Object to be true before allowance can be paid
  // bool _requireTasksForAllowance;

  struct Child {
    uint allowance;
    address addr;
    uint allowanceDue;
    //bool tasksCompleted (will be added when  _requireTasksForAllowance is added)
  }

  struct Adult {
    address addr;
    bool approveRefund;
    uint256 balanceOf;
  }

  // EVENTS
  event MoneyReceived(uint payment, address sender);
  event AllowancePaid(uint allowance, address receiver);

  // MODIFIERS

  // Adult Confirmation modifier
  // Confirmation that message sender is an adult
  modifier isAdult() {
    for (uint i = 0; i < _listOfAdults.length; i++) {
      if (msg.sender == _listOfAdults[i].addr) _;
    }
  }

  // Child Confirmation modifier
  // Confirmation that message sender is a child
  modifier isChild() {
    for (uint i = 0; i < _listOfChildren.length; i++) {
      if (msg.sender == _listOfChildren[i].addr) _;
    }
  }

  // Refundable Modifier
  // Confirmation that each ADULT has approved the ability to withdraw
  // funds from the contract.
  modifier refundable() {
    for (uint i = 0; i < _listOfAdults.length; i++) {
        address adultAddress = _listOfAdults[i].addr;
        if(!_adults[adultAddress].approveRefund) throw;
     }
     _;
  }
  // METHODS

  // Constructor Method Initialize when contract is created
  function FamilyWallet(
    address[] adults,
    address[] children,
    uint durationInDays
  ) {
    // Loop through adult array and include address in mapping and array
    for (uint j = 0; j < adults.length; j++) {
      Adult memory adult;
      adult.addr = adults[j];
      _listOfAdults.push(adult);
      _adults[adult.addr] = adult;
    }
    // Loop through children array and include address in mapping and array
    for (uint i = 0; i < children.length; i++) {
      Child memory child;
      child.addr = children[i];
      _listOfChildren.push(child);
      _children[child.addr] = child;
    }

    // Set Durations
    _allowancePeriodStart = now;
    _duration = durationInDays * 1 days;
    _allowancePeriodEnd = now + _duration;
  }

  // Make payment on allowance start,or when user calls getAllowance?
  // Right now child must call get allowance to receive alowance
  function nextAllowancePeriod() {
    if(now < _allowancePeriodEnd) throw;
    _allowancePeriodStart = _allowancePeriodEnd;
    _allowancePeriodEnd = _allowancePeriodEnd + _duration;
    for (uint i = 0; i < _listOfChildren.length; i++) {
      _listOfChildren[i].allowanceDue +=  _listOfChildren[i].allowance;
    }
  }

  function getAllowance() isChild {
    Child memory child = _children[msg.sender];
    if(child.allowanceDue == 0) throw;
    if(child.addr.send(child.allowanceDue)) throw;
    child.allowanceDue = 0;
    AllowancePaid(child.allowanceDue, msg.sender);
  }
  function approveRefund() isAdult {
    for (uint i = 0; i < _listOfAdults.length; i++) {
        if(msg.sender == _listOfAdults[i].addr) _listOfAdults[i].approveRefund = true;
     }
  }

  // Sends wallet balance to message sender
  // TODO:  Amount refunded should be same weighted average as amount deposited
  //        Rather that first person takes all.
  function refundBalance(address addr) isAdult refundable {
     if(_adults[msg.sender].addr.send(_wallet.balance)) throw;
  }

  function getChild() returns (address)  {
    return _listOfChildren[0].addr;
  }

  // Fallback method, send event once mony is paid
  function() payable {
    _adults[msg.sender].balanceOf += msg.value;
    MoneyReceived(msg.value, msg.sender);
  }
// TODO:    Allow Removal of Childen/Adult
// REASON:  In case of mental/physical inability of adult
//          to withdraw funds on his own behalf (Lost Private Key/Death)
//          Allow Remove of his account in order to be able to let other
//          adults withdraw funds. Contributions will be evenly split among
//          Other adults.
// NOTES:   Must allow a "checkin" method of some sort, if adult does not
//          check in after a period of time - allow other to vote him out
//          Otherwise if a user is checked in, there is no way he can be
//          voted out of the family.

}