missing update to balance

missing update to balance

/*
    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.18;

import "./Creatable.sol";
import "./oraclize/oraclizeAPI.sol";
import "./libraries/MathLib.sol";
import "./libraries/HashLib.sol";
import "zeppelin-solidity/contracts/token/ERC20.sol";
import "zeppelin-solidity/contracts/token/SafeERC20.sol";

//TODO: fix style issues
//      add failsafe for pool distribution.
//      push as much into library as possible
//      create mappings for deposit tokens and balance of collateral pool
//      think about circuit breaker in case of issues
contract MarketContract is Creatable, usingOraclize  {
    using MathLib for uint256;
    using MathLib for int;
    using HashLib for address;
    using SafeERC20 for ERC20;

    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_ADDRESS;
    ERC20 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 QTY_DECIMAL_PLACES;     // how many tradeable units make up a whole pricing increment
    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;
    mapping(address => uint) userAddressToAccountBalance;   // stores account balances allowed to be allocated to orders
    uint collateralPoolBalance = 0;                         // current balance of all collateral committed

    // events
    event OracleQuerySuccess();
    event OracleQueryFailed();
    event UpdatedLastPrice(string price);
    event ContractSettled();
    event DepositReceived(address user, uint depositAmount, uint totalBalance);
    event WithdrawCompleted(address user, uint withdrawAmount, uint totalBalance);

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

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

    function __callback(bytes32 queryID, string result, bytes proof) public {
        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 getUserPosition(address userAddress) external view returns (int)  {
        return addressToUserPosition[userAddress].netPosition;
    }

    function depositEtherForTrading() external payable {
        // should we allow ether or force users to use WETH?
    }

    // allows for all ERC20 tokens to be used for collateral and trading.
    function depositTokensForTrading(uint256 depositAmount) external {
        // user must call approve!
        BASE_TOKEN.safeTransferFrom(msg.sender, this, depositAmount);
        uint256 balanceAfterDeposit = userAddressToAccountBalance[msg.sender].add(depositAmount);
        userAddressToAccountBalance[msg.sender] = balanceAfterDeposit;
        DepositReceived(msg.sender, depositAmount, balanceAfterDeposit);
    }

    // allows user to remove token from trading account that have not been allocated to open positions
    function withdrawTokens(uint256 withdrawAmount) external {
        require(userAddressToAccountBalance[msg.sender] >= withdrawAmount);   // ensure sufficient balance
        uint256 balanceAfterWithdrawal = userAddressToAccountBalance[msg.sender].subtract(withdrawAmount);
        userAddressToAccountBalance[msg.sender] = balanceAfterWithdrawal;   // update balance before external call!
        BASE_TOKEN.safeTransfer(msg.sender, withdrawAmount);
        WithdrawCompleted(msg.sender, withdrawAmount, balanceAfterWithdrawal);
    }

    function trade(address maker, address taker) external {
        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 view 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.18;

import "./Creatable.sol";
import "./oraclize/oraclizeAPI.sol";
import "./libraries/MathLib.sol";
import "./libraries/HashLib.sol";
import "zeppelin-solidity/contracts/token/ERC20.sol";
import "zeppelin-solidity/contracts/token/SafeERC20.sol";

//TODO: fix style issues
//      add failsafe for pool distribution.
//      push as much into library as possible
//      create mappings for deposit tokens and balance of collateral pool
//      think about circuit breaker in case of issues
contract MarketContract is Creatable, usingOraclize  {
    using MathLib for uint256;
    using MathLib for int;
    using HashLib for address;
    using SafeERC20 for ERC20;

    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_ADDRESS;
    ERC20 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 QTY_DECIMAL_PLACES;     // how many tradeable units make up a whole pricing increment
    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;
    mapping(address => uint) userAddressToAccountBalance;   // stores account balances allowed to be allocated to orders
    uint collateralPoolBalance = 0;                         // current balance of all collateral committed

    // events
    event OracleQuerySuccess();
    event OracleQueryFailed();
    event UpdatedLastPrice(string price);
    event ContractSettled();
    event DepositReceived(address user, uint depositAmount, uint totalBalance);
    event WithdrawCompleted(address user, uint withdrawAmount, uint totalBalance);

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

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

    function __callback(bytes32 queryID, string result, bytes proof) public {
        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 getUserPosition(address userAddress) external view returns (int)  {
        return addressToUserPosition[userAddress].netPosition;
    }

    function depositEtherForTrading() external payable {
        // should we allow ether or force users to use WETH?
    }

    // allows for all ERC20 tokens to be used for collateral and trading.
    function depositTokensForTrading(uint256 depositAmount) external {
        // user must call approve!
        BASE_TOKEN.safeTransferFrom(msg.sender, this, depositAmount);
        uint256 balanceAfterDeposit = userAddressToAccountBalance[msg.sender].add(depositAmount);
        userAddressToAccountBalance[msg.sender] = balanceAfterDeposit;
        DepositReceived(msg.sender, depositAmount, balanceAfterDeposit);
    }

    // allows user to remove token from trading account that have not been allocated to open positions
    function withdrawTokens(uint256 withdrawAmount) external {
        require(userAddressToAccountBalance[msg.sender] >= withdrawAmount);   // ensure sufficient balance
        uint256 balanceAfterWithdrawal = userAddressToAccountBalance[msg.sender].subtract(withdrawAmount);
        BASE_TOKEN.safeTransfer(msg.sender, withdrawAmount);
        WithdrawCompleted(msg.sender, withdrawAmount, balanceAfterWithdrawal);
    }

    function trade(address maker, address taker) external {
        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 view 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);
    }
}


simpifying

simpifying

pragma solidity 0.4.15;

import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/token/StandardToken.sol';

/**
* Health Decentralized Record Service (DRS)
* This contract enables creation of url/key sets which can
* be managed, shared, traded, and sold using Health Cash (HLTH).
*
* These url/key sets enable data gatekeeper services and
* cryptographically secure data exchanges.
*/

contract HealthDRS is Ownable {

    struct Key {
        uint8 depth;
        bool shareable;
        bool tradeable;
        bool salable;
        bytes32 parent;
        address owner;
    }

    struct SalesOffer {
        address buyer;
        uint price;
    }

    mapping (bytes32 => string) urls;
    mapping(bytes32 => Key) keys;
    mapping(bytes32 => bytes32) public keyData;
    mapping(bytes32 => address[]) public sharedOwners;
    mapping(address => bytes32[]) public accountKeys;
    mapping(bytes32 => SalesOffer) public salesOffers;
    mapping(bytes32 => bytes32) public tradeOffers;

    StandardToken public token;
    address public latestContract = address(this);
    uint8 public version = 1;

    event KeyCreated(address indexed _owner, bytes32 indexed _key);
    event KeySold(bytes32 _key, address indexed _seller, address indexed _buyer, uint _price);
    event KeysTraded(bytes32 indexed _key1, bytes32 indexed _key2);
    event KeyMoved(bytes32 indexed _key, bytes32 _from, bytes32 _to);
    event Access(address indexed _owner, bytes32 indexed _from, bytes32 indexed _to, uint _time, string _data);
    event Message(address indexed _owner, bytes32 indexed _from, bytes32 indexed _to, uint _time, string _category, string _data);
    event Log(address indexed _owner, bytes32 indexed _from, uint _time, string _data);

    modifier ownsKey(bytes32 key) {
        require(isOwner(key, msg.sender));
        _;
    }

    modifier validKey(bytes32 key) {
      require(keys[key].owner != address(0));
      _;
    }

    modifier canSell(bytes32 key) {
      require(keys[key].salable);
      _;
    }

    modifier canTrade(bytes32 key) {
      require(keys[key].tradeable);
      _;
    }

    modifier canShare(bytes32 key) {
      require(keys[key].shareable);
      _;
    }

    /**
    * URLs
    * used to refrence gatekeeper services
    * which use these keys to permission access
    */

    function getURL(bytes32 key)
        public
        constant
        validKey(key)
        returns (string)
    {
        if (keys[key].depth == 0) {
            return urls[key];
        } else {
           return getURL(keys[key].parent);
        }
    }

    //owners of root keys can update the url
    function updateURL(bytes32 key, string url) public ownsKey(key) {
       require(keys[key].depth == 0); //root key only
       urls[key] = url;
    }

    //to purchase keys a user must authorize this contract to spend HLTH
    function authorizedToSpend() public constant returns (uint) {
        return token.allowance(msg.sender, address(this));
    }

    //allow owner access to tokens erroneously transfered to this contract
    function recoverTokens(StandardToken _token, uint amount) public onlyOwner {
        _token.transfer(owner, amount);
    }

    function setHealthCashToken(StandardToken _token) public onlyOwner {
        token = _token;
    }

    function setLatestContract(address _contract) public onlyOwner {
        latestContract = _contract;
    }

    function createKey(string url) public {

        bytes32 id = keccak256(url,now,msg.sender);

        //do not recreate keys
        require(keys[id].owner == address(0));
        keys[id].owner = msg.sender;
        keys[id].depth = 0;
        keys[id].shareable = true;
        keys[id].tradeable = true;
        keys[id].salable = true;
        urls[id] = url; //save the url

        accountKeys[msg.sender].push(id);
        KeyCreated(msg.sender, id);
    }

    function createChildKey(bytes32 key)
        public
        ownsKey(key)
        returns (bytes32 id)
    {
        //depth limited to 100
        require(keys[key].depth < 100);

        //create a unique id
        id = keccak256(key,now,msg.sender);

        //do not recreate keys
        require(keys[id].owner == address(0));
        keys[id].owner = msg.sender;
        keys[id].depth = keys[key].depth + 1;
        keys[id].parent = key;

        accountKeys[msg.sender].push(id);
        KeyCreated(msg.sender, id);
    }

    function shareKey(bytes32 key, address account)
        public
        ownsKey(key)
        canShare(key)
    {
        if (isOwner(key, account) == false) {
            sharedOwners[key].push(account);
            accountKeys[account].push(key);
        }
    }

    function unShareKey(bytes32 key, address account)
        public
        ownsKey(key)
    {
        if (keys[key].owner != account) {
            bool foundKey = false;
            for (uint i = 0; i < sharedOwners[key].length; i++) {
                if (sharedOwners[key][i] == account) {
                    foundKey = true;
                    break;
                }
            }
            if (foundKey) {
                if (i != sharedOwners[key].length - 1) {
                    sharedOwners[key][i] = sharedOwners[key][sharedOwners[key].length - 1];
                }
                sharedOwners[key].length--;
                removeFromAccountKeys(account, key);
            }
        }
    }

    /**
    * Sell Keys
    */
    function createSalesOffer(bytes32 key, address buyer, uint price)
        public
        ownsKey(key)
        canSell(key)
    {
        //cancell trade offer & create sales offer
        tradeOffers[key] = bytes32(0);
        salesOffers[key].buyer = buyer;
        salesOffers[key].price = price;
    }

    function cancelSalesOffer(bytes32 key)
        public
        ownsKey(key)
        canSell(key)
    {
        salesOffers[key].buyer = address(0);
        salesOffers[key].price = 0;
    }

    function purchaseKey(bytes32 key, uint value)
        public
        canSell(key)
    {

       //require explictit authority to spend tokens on the purchasers behalf
       require(value <= authorizedToSpend());
       require(salesOffers[key].buyer == msg.sender);
       require(salesOffers[key].price == value);

       //price is in HLTH tokens
       assert(token.transferFrom(msg.sender, keys[key].owner, value));

       KeySold(key, keys[key].owner, msg.sender, value);

       removeFromAccountKeys(keys[key].owner, key);
       accountKeys[msg.sender].push(key);
       keys[key].owner = msg.sender;

       //key is no longer for sale
       salesOffers[key].buyer = 0;
       salesOffers[key].price = 0;
    }

    /**
    * Trade Keys
    */
    function tradeKey(bytes32 have, bytes32 want)
        public
        ownsKey(have)
        canTrade(have)
        canTrade(want)
    {
       if (tradeOffers[want] == have) {

           KeysTraded(want, have);
           tradeOffers[want] = ""; //remove the tradeOffer

           //complete the trade
           removeFromAccountKeys(keys[have].owner, have);
           removeFromAccountKeys(keys[want].owner, want);
           accountKeys[keys[want].owner].push(have);
           accountKeys[msg.sender].push(want);

           keys[have].owner = keys[want].owner;
           keys[want].owner = msg.sender;

        } else {
            //create a trade offer & cancel sales offer
            cancelSalesOffer(have);
            tradeOffers[have] = want;
        }
    }

    /**
    * Manage Keys
    * manage, update, and inspect keys
    */

    function getKey(bytes32 key)
        public
        constant
        validKey(key)
        returns(address, uint8, bool, bool, bool, bytes32)
    {
       return (keys[key].owner,
               keys[key].depth,
               keys[key].shareable,
               keys[key].tradeable,
               keys[key].salable,
               keys[key].parent);
    }

    //only allow ancestor to grant/deny permission they have
    function setKeyPermissions(
        bytes32 ancestor,
        bytes32 descendant,
        bool shareable,
        bool tradeable,
        bool salable)
        public
        ownsKey(ancestor)
        validKey(descendant)
    {
        require(isAncestor(ancestor, descendant));

        if (keys[ancestor].shareable) {
            keys[descendant].shareable = shareable;
            //unshare if shared
            if (shareable == false) {
                for (uint i = 0; i < sharedOwners[descendant].length; i++) {
                    removeFromAccountKeys(sharedOwners[descendant][i], descendant);
                }
                sharedOwners[descendant].length = 0;
            }
        }

        if (keys[ancestor].tradeable) {
            keys[descendant].tradeable = tradeable;
            //cancel any existing trades
            if (tradeable == false) {
                tradeOffers[descendant] = "";
            }
        }

        if (keys[ancestor].salable) {
            keys[descendant].salable = salable;
            //cancel any existing sales
            if (salable == false) {
                salesOffers[descendant].buyer = 0;
                salesOffers[descendant].price = 0;
            }
        }

    }

    function isOwner(bytes32 key, address account)
        public
        constant
        validKey(key)
        returns (bool)
    {
        bool owns = false;
        if (keys[key].owner == account) {
            owns = true;
        }
        if (owns == false && keys[key].shareable) {
            for (uint i = 0; i < sharedOwners[key].length; i++) {
                if (sharedOwners[key][i] == account) {
                    owns = true;
                    break;
                }
           }
        }

        return owns;
    }

    /* Recursive implementation limits the
       ancestry dept to around 100, we impose this
       limit in the createChild function to avoid
       this.
    */
    function isAncestor(bytes32 ancestor, bytes32 key)
        public
        constant
        validKey(ancestor)
        validKey(key)
        returns (bool)
    {
        if (keys[key].depth == 0) {
            return false;
        } else if (keys[key].parent == ancestor) {
            return true;
        } else {
            return isAncestor(ancestor, keys[key].parent);
        }
    }

    function moveKey(bytes32 ancestor, bytes32 key, bytes32 destination)
        public
        ownsKey(ancestor)
        ownsKey(destination)
    {
        require(isAncestor(ancestor, key));
        keys[key].parent = destination;
    }

    function getAncestorCount(bytes32 key)
        public
        constant
        validKey(key)
        returns(uint)
    {
       return keys[key].depth;
    }

    function getAncestor(bytes32 key, uint depth)
        public
        constant
        validKey(key)
        returns (bytes32)
    {
        require(depth <= getAncestorCount(key));

        if (keys[key].depth == depth) {
            return key;
        } else {
            return getAncestor(keys[key].parent, depth);
        }
    }

    function removeFromAccountKeys(address account, bytes32 key) private {

       bool foundKey = false;

       for (uint i = 0; i < accountKeys[account].length; i++) {
           if (accountKeys[account][i] == key) {
               foundKey = true;
               break;
           }
       }
       if (foundKey) {
           if (i != accountKeys[account].length - 1) {
               accountKeys[account][i] = accountKeys[account][accountKeys[account].length - 1];
           }
           accountKeys[account].length--;
       }
    }

    /**
    * Key Data
    * data, such as permissions, can be stored
    * on the blockchain for any of your descendant keys
    */

    function getKeyData(bytes32 ancestor, bytes32 child, bytes32 dataKey)
        public
        constant
        ownsKey(ancestor)
        validKey(child)
        returns (bytes32)
    {
        require(isAncestor(ancestor, child));
        return keyData[keccak256(child,dataKey)];
    }

    function setKeyData(bytes32 ancestor, bytes32 child, bytes32 dataKey, bytes32 dataValue)
        public
        ownsKey(ancestor)
        validKey(child)
    {
        require(isAncestor(ancestor, child));
        keyData[keccak256(child,dataKey)] = dataValue;
    }

    /**
    * ECRecover
    */
    function recoverAddress(
        bytes32 msgHash,
        uint8 v,
        bytes32 r,
        bytes32 s)
        constant
        returns (address)
    {
      return ecrecover(msgHash, v, r, s);
    }

    /**
    * Logging & Messaging
    * functions for creating an auditable record of activity
    */
    function logAccess(bytes32 from, bytes32 to, string data)
        public
        ownsKey(from)
        validKey(to)
    {
        require(isAncestor(from, to));
        Access(msg.sender, from, to, now, data);
    }

    function message(bytes32 from, bytes32 to, string category, string data)
        public
        ownsKey(from)
        validKey(to)
    {
        Message(msg.sender, from, to, now, category, data);
    }

    function log(bytes32 from, string data)
        public
        ownsKey(from)
    {
        Log(msg.sender, from, now, data);
    }

}

pragma solidity 0.4.15;

import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/token/StandardToken.sol';

/**
* Health Decentralized Record Service (DRS)
* This contract enables creation of url/key sets which can
* be managed, shared, traded, and sold using Health Cash (HLTH).
*
* These url/key sets enable data gatekeeper services and
* cryptographically secure data exchanges.
*/

contract HealthDRS is Ownable {

    struct Key {
        address owner;
        uint8 depth;
        bool shareable;
        bool tradeable;
        bool salable;
        bytes32 parent;
        mapping(bytes32 => bytes32) data;
    }

    struct SalesOffer {
        address buyer;
        uint price;
    }

    mapping (bytes32 => string) urls;
    mapping(bytes32 => Key) keys;
    mapping(bytes32 => address[]) sharedOwners;
    mapping(address => bytes32[]) public accountKeys;
    mapping(bytes32 => SalesOffer) public salesOffers;
    mapping(bytes32 => bytes32) public tradeOffers;
    address public latestContract = address(this);
    StandardToken public token;
    uint16 public version = 1;

    event KeyCreated(address indexed _owner, bytes32 indexed _key);
    event KeySold(bytes32 _key, address indexed _seller, address indexed _buyer, uint _price);
    event KeysTraded(bytes32 indexed _key1, bytes32 indexed _key2);
    event KeyMoved(bytes32 indexed _key, bytes32 _from, bytes32 _to);
    event Access(address indexed _owner, bytes32 indexed _from, bytes32 indexed _to, uint _time, string _data);
    event Message(address indexed _owner, bytes32 indexed _from, bytes32 indexed _to, uint _time, string _category, string _data);
    event Log(address indexed _owner, bytes32 indexed _from, uint _time, string _data);

    modifier ownsKey(bytes32 key) {
        require(isOwner(key, msg.sender));
        _;
    }

    modifier validKey(bytes32 key) {
      require(keys[key].owner != address(0));
      _;
    }

    modifier canSell(bytes32 key) {
      require(keys[key].salable);
      _;
    }

    modifier canTrade(bytes32 key) {
      require(keys[key].tradeable);
      _;
    }

    modifier canShare(bytes32 key) {
      require(keys[key].shareable);
      _;
    }

    /**
    * URLs
    * used to refrence gatekeeper services
    * which use these keys to permission access
    */

    function getURL(bytes32 key)
        public
        constant
        validKey(key)
        returns (string)
    {
        if (keys[key].depth == 0) {
            return urls[key];
        } else {
           return getURL(keys[key].parent);
        }
    }

    //owners of root keys can update the url
    function updateURL(bytes32 key, string url) public ownsKey(key) {
       require(keys[key].depth == 0); //root key only
       urls[key] = url;
    }

    //to purchase keys a user must authorize this contract to spend HLTH
    function authorizedToSpend() public constant returns (uint) {
        return token.allowance(msg.sender, address(this));
    }

    //allow owner access to tokens erroneously transfered to this contract
    function recoverTokens(StandardToken _token, uint amount) public onlyOwner {
        _token.transfer(owner, amount);
    }

    function setHealthCashToken(StandardToken _token) public onlyOwner {
        token = _token;
    }

    function setLatestContract(address _contract) public onlyOwner {
        latestContract = _contract;
    }

    function createKey(string url) public {

        bytes32 id = keccak256(url,now,msg.sender);

        //do not recreate keys
        require(keys[id].owner == address(0));
        keys[id].owner = msg.sender;
        keys[id].depth = 0;
        keys[id].shareable = true;
        keys[id].tradeable = true;
        keys[id].salable = true;
        urls[id] = url; //save the url

        accountKeys[msg.sender].push(id);
        KeyCreated(msg.sender, id);
    }

    function createChildKey(bytes32 key)
        public
        ownsKey(key)
        returns (bytes32 id)
    {
        //depth limited to 100
        require(keys[key].depth < 100);

        //create a unique id
        id = keccak256(key,now,msg.sender);

        //do not recreate keys
        require(keys[id].owner == address(0));
        keys[id].owner = msg.sender;
        keys[id].depth = keys[key].depth + 1;
        keys[id].parent = key;

        accountKeys[msg.sender].push(id);
        KeyCreated(msg.sender, id);
    }

    function shareKey(bytes32 key, address account)
        public
        ownsKey(key)
        canShare(key)
    {
        if (isOwner(key, account) == false) {
            sharedOwners[key].push(account);
            accountKeys[account].push(key);
        }
    }

    function unShareKey(bytes32 key, address account)
        public
        ownsKey(key)
    {
        if (keys[key].owner != account) {
            bool foundKey = false;
            for (uint i = 0; i < sharedOwners[key].length; i++) {
                if (sharedOwners[key][i] == account) {
                    foundKey = true;
                    break;
                }
            }
            if (foundKey) {
                if (i != sharedOwners[key].length - 1) {
                    sharedOwners[key][i] = sharedOwners[key][sharedOwners[key].length - 1];
                }
                sharedOwners[key].length--;
                removeFromAccountKeys(account, key);
            }
        }
    }

    /**
    * Sell Keys
    */
    function createSalesOffer(bytes32 key, address buyer, uint price)
        public
        ownsKey(key)
        canSell(key)
    {
        //cancell trade offer & create sales offer
        tradeOffers[key] = bytes32(0);
        salesOffers[key].buyer = buyer;
        salesOffers[key].price = price;
    }

    function cancelSalesOffer(bytes32 key)
        public
        ownsKey(key)
        canSell(key)
    {
        salesOffers[key].buyer = address(0);
        salesOffers[key].price = 0;
    }

    function purchaseKey(bytes32 key, uint value)
        public
        canSell(key)
    {

       //require explictit authority to spend tokens on the purchasers behalf
       require(value <= authorizedToSpend());
       require(salesOffers[key].buyer == msg.sender);
       require(salesOffers[key].price == value);

       //price is in HLTH tokens
       assert(token.transferFrom(msg.sender, keys[key].owner, value));

       KeySold(key, keys[key].owner, msg.sender, value);

       removeFromAccountKeys(keys[key].owner, key);
       accountKeys[msg.sender].push(key);
       keys[key].owner = msg.sender;

       //key is no longer for sale
       salesOffers[key].buyer = 0;
       salesOffers[key].price = 0;
    }

    /**
    * Trade Keys
    */
    function tradeKey(bytes32 have, bytes32 want)
        public
        ownsKey(have)
        canTrade(have)
        canTrade(want)
    {
       if (tradeOffers[want] == have) {

           KeysTraded(want, have);
           tradeOffers[want] = ""; //remove the tradeOffer

           //complete the trade
           removeFromAccountKeys(keys[have].owner, have);
           removeFromAccountKeys(keys[want].owner, want);
           accountKeys[keys[want].owner].push(have);
           accountKeys[msg.sender].push(want);

           keys[have].owner = keys[want].owner;
           keys[want].owner = msg.sender;

        } else {
            //create a trade offer & cancel sales offer
            cancelSalesOffer(have);
            tradeOffers[have] = want;
        }
    }

    /**
    * Manage Keys
    * manage, update, and inspect keys
    */

    function getKey(bytes32 key)
        public
        constant
        validKey(key)
        returns(address, uint8, bool, bool, bool, bytes32)
    {
       return (keys[key].owner,
               keys[key].depth,
               keys[key].shareable,
               keys[key].tradeable,
               keys[key].salable,
               keys[key].parent);
    }

    //only allow ancestor to grant/deny permission they have
    function setKeyPermissions(
        bytes32 ancestor,
        bytes32 descendant,
        bool shareable,
        bool tradeable,
        bool salable)
        public
        ownsKey(ancestor)
        validKey(descendant)
    {
        require(isAncestor(ancestor, descendant));

        if (keys[ancestor].shareable) {
            keys[descendant].shareable = shareable;
            //unshare if shared
            if (shareable == false) {
                for (uint i = 0; i < sharedOwners[descendant].length; i++) {
                    removeFromAccountKeys(sharedOwners[descendant][i], descendant);
                }
                sharedOwners[descendant].length = 0;
            }
        }

        if (keys[ancestor].tradeable) {
            keys[descendant].tradeable = tradeable;
            //cancel any existing trades
            if (tradeable == false) {
                tradeOffers[descendant] = "";
            }
        }

        if (keys[ancestor].salable) {
            keys[descendant].salable = salable;
            //cancel any existing sales
            if (salable == false) {
                salesOffers[descendant].buyer = 0;
                salesOffers[descendant].price = 0;
            }
        }

    }

    function isOwner(bytes32 key, address account)
        public
        constant
        validKey(key)
        returns (bool)
    {
        bool owns = false;
        if (keys[key].owner == account) {
            owns = true;
        }
        if (owns == false && keys[key].shareable) {
            for (uint i = 0; i < sharedOwners[key].length; i++) {
                if (sharedOwners[key][i] == account) {
                    owns = true;
                    break;
                }
           }
        }

        return owns;
    }

    /* Recursive implementation limits the
       ancestry dept to around 100, we impose this
       limit in the createChild function to avoid
       this.
    */
    function isAncestor(bytes32 ancestor, bytes32 key)
        public
        constant
        validKey(ancestor)
        validKey(key)
        returns (bool)
    {
        if (keys[key].depth == 0) {
            return false;
        } else if (keys[key].parent == ancestor) {
            return true;
        } else {
            return isAncestor(ancestor, keys[key].parent);
        }
    }

    function moveKey(bytes32 ancestor, bytes32 key, bytes32 destination)
        public
        ownsKey(ancestor)
        ownsKey(destination)
    {
        require(isAncestor(ancestor, key));
        keys[key].parent = destination;
    }

    function getAncestorCount(bytes32 key)
        public
        constant
        validKey(key)
        returns(uint)
    {
       return keys[key].depth;
    }

    function getAncestor(bytes32 key, uint depth)
        public
        constant
        validKey(key)
        returns (bytes32)
    {
        require(depth <= getAncestorCount(key));

        if (keys[key].depth == depth) {
            return key;
        } else {
            return getAncestor(keys[key].parent, depth);
        }
    }

    function removeFromAccountKeys(address account, bytes32 key) private {

       bool foundKey = false;

       for (uint i = 0; i < accountKeys[account].length; i++) {
           if (accountKeys[account][i] == key) {
               foundKey = true;
               break;
           }
       }
       if (foundKey) {
           if (i != accountKeys[account].length - 1) {
               accountKeys[account][i] = accountKeys[account][accountKeys[account].length - 1];
           }
           accountKeys[account].length--;
       }
    }

    /**
    * Key Data
    * data, such as permissions, can be stored
    * on the blockchain for any of your descendant keys
    */

    function getKeyData(bytes32 ancestor, bytes32 child, bytes32 dataKey)
        public
        constant
        ownsKey(ancestor)
        returns (bytes32)
    {
        require(isAncestor(ancestor, child));
        return keys[child].data[dataKey];
    }

    function setKeyData(bytes32 ancestor, bytes32 child, bytes32 dataKey, bytes32 dataValue)
        public
        ownsKey(ancestor)
    {
        require(isAncestor(ancestor, child));
        keys[child].data[dataKey] = dataValue;
    }

    /**
    * ECRecover
    */
    function recoverAddress(
        bytes32 msgHash,
        uint8 v,
        bytes32 r,
        bytes32 s)
        constant
        returns (address)
    {
      return ecrecover(msgHash, v, r, s);
    }

    /**
    * Logging & Messaging
    * functions for creating an auditable record of activity
    */
    function logAccess(bytes32 from, bytes32 to, string data)
        public
        ownsKey(from)
        validKey(to)
    {
        require(isAncestor(from, to));
        Access(msg.sender, from, to, now, data);
    }

    function message(bytes32 from, bytes32 to, string category, string data)
        public
        ownsKey(from)
        validKey(to)
    {
        Message(msg.sender, from, to, now, category, data);
    }

    function log(bytes32 from, string data)
        public
        ownsKey(from)
    {
        Log(msg.sender, from, now, data);
    }

}


Delete WeiCoinV2.sol

Delete WeiCoinV2.sol

/*Most, basic default, standardised Token contract.
Allows the creation of a token with a finite issued amount to the creator.

Based on standardised APIs: https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs
.*/

contract Token {
    function transfer(uint _value, address _to) returns (bool _success) {}
    function transferFrom(address _from, uint _value, address _to) returns (bool _success) {}
    function balanceOf(address _addr) constant returns (uint _r) {}
    function approve(address _addr) returns (bool _success) {}
    function unapprove(address _addr) returns (bool _success) {}
    function isApprovedFor(address _target, address _proxy) constant returns (bool _r) {}
    function approveOnce(address _addr, uint256 _maxValue) returns (bool _success) {}
    function isApprovedOnceFor(address _target, address _proxy) constant returns (uint _maxValue) {}

    event Transfer(address indexed from, address indexed to, uint256 value);
    event AddressApproval(address indexed addr, address indexed proxy, bool result);
    event AddressApprovalOnce(address indexed addr, address indexed proxy, uint256 value);
}

contract Standard_Token is Token {

    function Standard_Token(uint _initialAmount) {
        balances[msg.sender] = _initialAmount;
    }

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

    function transferFrom(address _from, uint _value, address _to) returns (bool _success) {
        if (balances[_from] >= _value) {
            bool transfer = false;
            if(approved[_from][msg.sender]) {
                transfer = true;
            } else {
                if(_value <= approved_once[_from][msg.sender]) {
                    transfer = true;
                    approved_once[_from][msg.sender] = 0; //reset
                }
            }

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

    function balanceOf(address _addr) constant returns (uint _r) {
        return balances[_addr];
    }

    function approve(address _addr) returns (bool _success) {
        approved[msg.sender][_addr] = true;
        AddressApproval(msg.sender, _addr, true);
        return true;
    }

    function unapprove(address _addr) returns (bool _success) {
        approved[msg.sender][_addr] = false;
        approved_once[msg.sender][_addr] = 0;
        //debatable whether to include...
        AddressApproval(msg.sender, _addr, false);
        AddressApprovalOnce(msg.sender, _addr, 0);
    }

    function isApprovedFor(address _target, address _proxy) constant returns (bool _r) {
        return approved[_target][_proxy];
    }

    function approveOnce(address _addr, uint256 _maxValue) returns (bool _success) {
        approved_once[msg.sender][_addr] = _maxValue;
        AddressApprovalOnce(msg.sender, _addr, _maxValue);
        return true;
    }

    function isApprovedOnceFor(address _target, address _proxy) constant returns (uint _maxValue) {
        return approved_once[_target][_proxy];
    }

    //explicitly not publicly accessible. Should rely on methods for purpose of standardization.
    mapping (address => uint) balances;
    mapping (address => mapping (address => bool)) approved;
    mapping (address => mapping (address => uint256)) approved_once;
}

contract Standard_Token_Factory {

    mapping(address => address[]) public created;

    function createdByMe() returns (address[]) {
        return created[msg.sender];
    }

    function createStandardToken(uint256 _initialAmount) returns (address) {

        address newTokenAddr = address(new Standard_Token(_initialAmount));
        Standard_Token newToken = Standard_Token(newTokenAddr);
        newToken.transfer(_initialAmount, msg.sender); //the factory will own the created tokens. You must transfer them.
        uint count = created[msg.sender].length += 1;
        created[msg.sender][count-1] = newTokenAddr;
        created[msg.sender].length = count;
        return newTokenAddr;
    }
}

//sol Coin
// Simple minable coin.
// @authors:
//   Gav Wood <g@ethdev.com>

contract WeiFundConfig {
    function onNewCampaign(uint cid, address addr){}
    function onContribute(uint cid, address addr, uint amount){}
    function onRefund(uint cid, address addr, uint amount) returns (bool) {}
    function onPayout(uint cid, uint amount){}
}

import "owned";

contract WeiCoin is owned {
    address public tokenAddress;
    address public weifundAddress;
    address public factoryAddress;
    uint public weiRatio;
    uint public cid;
    bool public campaignStarted;

    function WeiCoin(uint256 _initalAmount, uint _weiRatio, address _weifundAddress) {
        owner = msg.sender;
        weiRatio = _weiRatio;
        weifundAddress = _weifundAddress;
        tokenAddress = Standard_Token_Factory(factoryAddress)
                            .createStandardToken(_initalAmount);
    }

    function transfer(uint _value, address _to) returns (bool) {
        if(msg.sender == owner)
            Standard_Token(tokenAddress).transfer(_value, _to);
    }

	function onNewCampaign(uint _cid, address _addr, uint _goal) {
	    if(msg.sender != weifundAddress
	        || owner != _addr)
	        return;

	    cid = _cid;
	    campaignStarted = true;
	}

	function onContribute(uint _cid, address _addr, uint _amount) {
	    if(!campaignStarted
	    || _cid != cid
	    || msg.sender != weifundAddress
	    || _amount == 0
	    || _addr == address(0))
	        return;

	    Standard_Token(tokenAddress).transfer(_amount / weiRatio, _addr);
	}

	function onRefund(uint _cid, address _addr, uint _amount) returns (bool) {
	    if(!campaignStarted
	    || _cid != cid
	    || msg.sender != weifundAddress
	    || _amount == 0
	    || _addr == address(0))
	        return;

	    return Standard_Token(tokenAddress).transferFrom(_addr, _amount / weiRatio, this);
	}
}


minor fixes

minor fixes

pragma solidity ^0.4.21;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/SwapyExchange.sol";
import "./helpers/ThrowProxy.sol";

contract TestSwapyExchange {

    SwapyExchange protocol = SwapyExchange(DeployedAddresses.SwapyExchange());
    ThrowProxy throwProxy = new ThrowProxy(address(protocol));
    SwapyExchange throwableProtocol = SwapyExchange(address(throwProxy));
    uint256[] _assetValues;

    // Testing the createOffer() function
    function testUserCanCreateOffer() public {
        _assetValues.push(uint256(500));
        _assetValues.push(uint256(500));
        _assetValues.push(uint256(500));
        bool result = protocol.createOffer(
            uint256(360),
            uint256(10),
            bytes5("USD"),
            _assetValues
        );
        Assert.equal(result, true, "Assets must be created");
    }

}

pragma solidity ^0.4.21;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/SwapyExchange.sol";
import "./helpers/ThrowProxy.sol";

contract TestSwapyExchange {

    SwapyExchange protocol = SwapyExchange(DeployedAddresses.SwapyExchange());
    ThrowProxy throwProxy = new ThrowProxy(address(protocol));
    SwapyExchange throwableProtocol = SwapyExchange(address(throwProxy));
    uint256[] _assets;

    // Testing the createOffer() function
    function testUserCreateOffer() public {
        _assets.push(uint256(500));
        _assets.push(uint256(500));
        _assets.push(uint256(500));
        bool result = protocol.createOffer(
            uint256(360),
            uint256(10),
            bytes5("USD"),
            _assets
        );
        Assert.equal(result, true, "Five assets must be created");
    }

}


Add relation getters, auth array instead of map

pragma solidity 0.4.10;

contract DCReum {
  event LogWorkflowCreation(uint256 indexed workflowId, bytes32 indexed workflowName);
  event LogActivityCreation(uint256 indexed workflowId, uint256 indexed activityId, bytes32 indexed activityName);
  event LogExecution(uint256 indexed workflowId, uint256 indexed activityId, address indexed executor);

  enum RelationType {
    Include, Exclude, Response, Condition, Milestone
  }

  struct Workflow {
    bytes32 name;

    // note that while activities is indexed with 256 bit,
    // it must not surpass 2^32 entries
    Activity[] activities;

    // group 0-31     permits execution of activities with the corresponding auth bit set
    // group 32       permits workflow modification
    // group 33-39    reserved
    mapping (address => uint40) groupMembers;

    // names of group 0-31
    bytes32[32] groupNames;
  }

  struct Activity {
    bytes32 name;

    // activity state
    bool included;
    bool executed;
    bool pending;

    // activity relations
    uint32[] includeTo;
    uint32[] excludeTo;
    uint32[] responseTo;
    uint32[] conditionFrom;
    uint32[] milestoneFrom;

    // group execution rights bit vector
    // a set bit means the corresponding group is allowed to execute
    uint32 authGroups;

    // individual accounts with rights to execute
    address[] authAccounts;

    // if true anyone can execute
    bool authDisabled;
  }

  Workflow[] workflows;

  // not intended for use in transactions, as returned structs will exist in memory,
  // not as storage pointers
  function getWorkflowActivity(uint256 workflowId, uint256 activityId) private constant returns (Workflow, Activity) {
    var workflow = workflows[workflowId];
    var activity = workflow.activities[activityId];
    return (workflow, activity);
  }

  function isIncluded(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.included;
  }

  function isExecuted(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.executed;
  }

  function isPending(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.pending;
  }

  function getIncludes(uint256 workflowId, uint256 activityId) external constant returns (uint32[]) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.includeTo;
  }

  function getExcludes(uint256 workflowId, uint256 activityId) external constant returns (uint32[]) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.excludeTo;
  }

  function getResponses(uint256 workflowId, uint256 activityId) external constant returns (uint32[]) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.responseTo;
  }

  function getConditions(uint256 workflowId, uint256 activityId) external constant returns (uint32[]) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.conditionFrom;
  }

  function getMilestones(uint256 workflowId, uint256 activityId) external constant returns (uint32[]) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.milestoneFrom;
  }

  function canExecute(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var workflow = workflows[workflowId];
    var activity = workflow.activities[activityId];
    uint32 i;
    uint32 fromId;

    // sender address must have rights to execute or sender must be member of a group with rights to execute
    // note that the operands of the AND are of different bit lengths,
    // causing the 8 special group bits to be ignored
    if (!activity.authDisabled && (workflow.groupMembers[msg.sender] & activity.authGroups) == 0) {
      // sender not in allowed group - check individual account access rights
      for (i = 0; i < activity.authAccounts.length; i++) {
        if (activity.authAccounts[i] == msg.sender)
          break;
      }

      // sender not in authAccounts array
      if (i == activity.authAccounts.length)
        return false;
    }

    // activity must be included
    if (!activity.included) return false;

    // all conditions executed
    for (i = 0; i < activity.conditionFrom.length; i++) {
      fromId = activity.conditionFrom[i];
      if (!workflow.activities[fromId].executed) return false;
    }

    // no milestones pending
    for (i = 0; i < activity.milestoneFrom.length; i++) {
      fromId = activity.milestoneFrom[i];
      if (workflow.activities[fromId].pending) return false;
    }

    return true;
  }

  function execute(uint256 workflowId, uint256 activityId) {
    var workflow = workflows[workflowId];
    var activity = workflow.activities[activityId];
    uint32 i;
    uint32 toId;

    if (!canExecute(workflowId, activityId)) throw;

    // executed activity
    activity.executed = true;
    activity.pending = false;

    // exclude relations pass
    for (i = 0; i < activity.excludeTo.length; i++) {
      toId = activity.excludeTo[i];
      workflow.activities[toId].included = false;
    }

    // include relations pass
    // note this happens after the exlude pass
    for (i = 0; i < activity.includeTo.length; i++) {
      toId = activity.includeTo[i];
      workflow.activities[toId].included = true;
    }

    // response relations pass
    for (i = 0; i < activity.responseTo.length; i++) {
      toId = activity.responseTo[i];
      workflow.activities[toId].pending = true;
    }

    LogExecution(workflowId, activityId, msg.sender);
  }

  function createWorkflow(
    // ugly squash hack to decrease stack depth
    // 0: workflow name
    // 1-32: group names
    // 33-end: activity names
    bytes32[] names,
    bool[3][] activityStates, // included, executed, pending

    // ugly squash hack to decrease stack depth
    // length is amount of activities
    // 0: counts for relationTypes and relationActivityIds
    // 1: counts for authAccounts
    // 2: authGroups
    uint32[3][] activityData,
    RelationType[] relationTypes,
    uint32[] relationActivityIds,

    address[] groupAccounts,
    uint40[] groupMemberships,
    address[] authAccounts,
    bool[] authDisabled
  ) {
    var workflow = workflows[workflows.length++];
    uint256 i;
    uint256 j;
    uint32 relationIndex = 0;
    uint32 authAccountIndex = 0;

    assert(activityData.length == names.length - 33);
    assert(activityData.length == authDisabled.length);
    assert(groupAccounts.length == groupMemberships.length);

    workflow.name = names[0];
    for (i = 0; i < 32; i++) {
      workflow.groupNames[i] = names[1 + i];
    }

    // group accounts
    for (i = 0; i < groupAccounts.length; i++) {
      workflow.groupMembers[groupAccounts[i]] = groupMemberships[i];
    }

    // activities
    for (i = 0; i < activityData.length; i++) {
      var activity = workflow.activities[workflow.activities.length++];
      activity.name = names[33 + i];
      activity.included = activityStates[i][0];
      activity.executed = activityStates[i][1];
      activity.pending = activityStates[i][2];
      activity.authGroups = activityData[i][2];
      activity.authDisabled = authDisabled[i];

      // relations
      for (j = 0; j < activityData[i][0]; j++) {
        if (relationTypes[relationIndex] == RelationType.Include)
          activity.includeTo.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Exclude)
          activity.excludeTo.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Response)
          activity.responseTo.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Condition)
          activity.conditionFrom.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Milestone)
          activity.milestoneFrom.push(relationActivityIds[relationIndex]);

        relationIndex++;
      }

      // individual account auth
      for (j = 0; j < activityData[i][1]; j++) {
        activity.authAccounts.push(authAccounts[authAccountIndex++]);
      }
    }

    LogWorkflowCreation(workflows.length - 1, workflow.name);
  }
}

pragma solidity 0.4.10;

contract DCReum {
  event LogWorkflowCreation(uint256 indexed workflowId, bytes32 indexed workflowName);
  event LogActivityCreation(uint256 indexed workflowId, uint256 indexed activityId, bytes32 indexed activityName);
  event LogExecution(uint256 indexed workflowId, uint256 indexed activityId, address indexed executor);

  enum RelationType {
    Include, Exclude, Response, Condition, Milestone
  }

  struct Workflow {
    bytes32 name;

    // note that while activities is indexed with 256 bit,
    // it must not surpass 2^32 entries
    Activity[] activities;

    // group 0-31     permits execution of activities with the corresponding auth bit set
    // group 32       permits workflow modification
    // group 33-39    reserved
    mapping (address => uint40) groupMembers;

    // names of group 0-31
    bytes32[32] groupNames;
  }

  struct Activity {
    bytes32 name;

    // activity state
    bool included;
    bool executed;
    bool pending;

    // activity relations
    uint32[] includeTo;
    uint32[] excludeTo;
    uint32[] responseTo;
    uint32[] conditionFrom;
    uint32[] milestoneFrom;

    // group execution rights bit vector
    // a set bit means the corresponding group is allowed to execute
    uint32 authGroups;

    // individual accounts with rights to execute
    mapping(address => bool) authAccounts;

    // if true anyone can execute
    bool authDisabled;
  }

  Workflow[] workflows;

  // not intended for use in transactions, as returned structs will exist in memory,
  // not as storage pointers
  function getWorkflowActivity(uint256 workflowId, uint256 activityId) private constant returns (Workflow, Activity) {
    var workflow = workflows[workflowId];
    var activity = workflow.activities[activityId];
    return (workflow, activity);
  }

  function isIncluded(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.included;
  }

  function isExecuted(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.executed;
  }

  function isPending(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var (workflow, activity) = getWorkflowActivity(workflowId, activityId);
    return activity.pending;
  }

  function canExecute(uint256 workflowId, uint256 activityId) public constant returns (bool) {
    var workflow = workflows[workflowId];
    var activity = workflow.activities[activityId];
    uint32 i;
    uint32 fromId;

    // sender address must have rights to execute or sender must be member of a group with rights to execute
    // note that workflow.groupMembers[msg.sender] defaults to 0 for unmapped sender
    // note that the operands of the AND are of different bit lengths,
    // causing the 8 special group bits to be ignored
    if (!activity.authDisabled &&
        !activity.authAccounts[msg.sender] &&
        (workflow.groupMembers[msg.sender] & activity.authGroups) == 0)
      return false;

    // activity must be included
    if (!activity.included) return false;

    // all conditions executed
    for (i = 0; i < activity.conditionFrom.length; i++) {
      fromId = activity.conditionFrom[i];
      if (!workflow.activities[fromId].executed) return false;
    }

    // no milestones pending
    for (i = 0; i < activity.milestoneFrom.length; i++) {
      fromId = activity.milestoneFrom[i];
      if (workflow.activities[fromId].pending) return false;
    }

    return true;
  }

  function execute(uint256 workflowId, uint256 activityId) {
    var workflow = workflows[workflowId];
    var activity = workflow.activities[activityId];
    uint32 i;
    uint32 toId;

    if (!canExecute(workflowId, activityId)) throw;

    // executed activity
    activity.executed = true;
    activity.pending = false;

    // exclude relations pass
    for (i = 0; i < activity.excludeTo.length; i++) {
      toId = activity.excludeTo[i];
      workflow.activities[toId].included = false;
    }

    // include relations pass
    // note this happens after the exlude pass
    for (i = 0; i < activity.includeTo.length; i++) {
      toId = activity.includeTo[i];
      workflow.activities[toId].included = true;
    }

    // response relations pass
    for (i = 0; i < activity.responseTo.length; i++) {
      toId = activity.responseTo[i];
      workflow.activities[toId].pending = true;
    }

    LogExecution(workflowId, activityId, msg.sender);
  }

  function createWorkflow(
    // ugly squash hack to decrease stack depth
    // 0: workflow name
    // 1-32: group names
    // 33-end: activity names
    bytes32[] names,
    bool[3][] activityStates, // included, executed, pending

    // ugly squash hack to decrease stack depth
    // length is amount of activities
    // 0: counts for relationTypes and relationActivityIds
    // 1: counts for authAccounts
    // 2: authGroups
    uint32[3][] activityData,
    RelationType[] relationTypes,
    uint32[] relationActivityIds,

    address[] groupAccounts,
    uint40[] groupMemberships,
    address[] authAccounts,
    bool[] authDisabled
  ) {
    var workflow = workflows[workflows.length++];
    uint256 i;
    uint256 j;
    uint32 relationIndex = 0;
    uint32 authAccountIndex = 0;

    assert(activityData.length == names.length - 33);
    assert(activityData.length == authDisabled.length);
    assert(groupAccounts.length == groupMemberships.length);

    workflow.name = names[0];
    for (i = 0; i < 32; i++) {
      workflow.groupNames[i] = names[1 + i];
    }

    // group accounts
    for (i = 0; i < groupAccounts.length; i++) {
      workflow.groupMembers[groupAccounts[i]] = groupMemberships[i];
    }

    // activities
    for (i = 0; i < activityData.length; i++) {
      var activity = workflow.activities[workflow.activities.length++];
      activity.name = names[33 + i];
      activity.included = activityStates[i][0];
      activity.executed = activityStates[i][1];
      activity.pending = activityStates[i][2];
      activity.authGroups = activityData[i][2];
      activity.authDisabled = authDisabled[i];

      // relations
      for (j = 0; j < activityData[i][0]; j++) {
        if (relationTypes[relationIndex] == RelationType.Include)
          activity.includeTo.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Exclude)
          activity.excludeTo.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Response)
          activity.responseTo.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Condition)
          activity.conditionFrom.push(relationActivityIds[relationIndex]);
        else if (relationTypes[relationIndex] == RelationType.Milestone)
          activity.milestoneFrom.push(relationActivityIds[relationIndex]);

        relationIndex++;
      }

      // individual account auth
      for (j = 0; j < activityData[i][1]; j++) {
        activity.authAccounts[authAccounts[authAccountIndex++]] = true;
      }
    }

    LogWorkflowCreation(workflows.length - 1, workflow.name);
  }
}


Itransition opener 2015

Itransition opener 2015


Fix StandardToken

Fix StandardToken

import "./Token.sol";

contract StandardToken is Token {
	uint256 public totalSupply;
	mapping (address => uint256) public balanceOf;
	mapping (address =>
		mapping (address => uint256)) public allowance;

	function StandardToken(address _initialOwner, uint256 _supply) {
		totalSupply = _supply;
		balanceOf[_initialOwner] = _supply;
	}

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

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

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

import "./Token.sol";

contract StandardToken is Token {
	uint256 tokenSupply;
	mapping (address => uint256) balances;
	mapping (address =>
		mapping (address => uint256)) approvedTransfers;

	function StandardToken(address _initialOwner, uint256 _supply) {
		tokenSupply = _supply;
		balances[_initialOwner] = _supply;
	}

	function totalSupply() constant returns (uint256 supply) {
		return tokenSupply;
	}

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

	function transfer(address _to, uint256 _value) returns (bool success) {
		if (balances[msg.sender] >= _value) {
			balances[msg.sender] -= _value;
			balances[_to] += _value;
			Transfer(msg.sender, _to, _value);
			return true;
		}
		else {
			return false;
		}
	}

	function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
		if (approvedTransfers[_from][msg.sender] >= _value) {
			approvedTransfers[_from][msg.sender] -= _value;
			balances[_to] += _value;
			Transfer(_from, _to, _value);
			return true;
		}
		else {
			return false;
		}
	}

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

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


Upgrade Ownable

Upgrade Ownable

pragma solidity ^0.4.11;

/**
 * @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;

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() {
    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 {
    require(newOwner != address(0));
    owner = newOwner;
  }

}

pragma solidity ^0.4.8;

/*
 * Ownable
 *
 * Base contract with an owner.
 * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
 */
contract Ownable {
  address public owner;

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

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

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


Update

Update

pragma solidity ^0.4.0;

contract owned {
	address public owner;

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

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

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

}

contract Anemoi is owned {
	uint256 public totalSupply;
	// Public variables for the token
	string public name;
	string public symbol;
	uint8 public decimals = 18;
	// 18 decimals is the strongly default, avoid changing it
	uint256 public totalSuply;

	/* Creates an array with balances */
	mapping (address => uint256) public balanceOf;

	/* Initilizes contract with initial supply tokens to the creator of the contract */
	function Anemoi(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) {
		totalSupply = initialSupply;
		balanceOf[msg.sender] = initialSupply;   // Give the creator all initial tokens
		name = tokenName;                        // Set the name for display purposes
		symbol = tokenSymbol;                    // Set the symbol for display purposes
		decimals = decimalUnits;                 // Amount of decimals for display purposes
		uint256 intialSupply,
		string tokenName,
		uint8 decimalUnits,
		string tokenSymbol,
		address centralMinter) {
		if(centralMinter != 0 ) owner = centralMinter;
	}
}

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

	/* Internal transfer, only can be called by this contract */
	function _transfer(address _from, address _to, uint °value) internal {
		require (_to != 0*0);                                 // Prevent transfer to 0*0 address. Use burn() instead
		require (balanceOf[_from] > _value);                  // Check if the sender has enough
		require (balanceOf[_to] + _value > balanceOf[_to]);   // Chek for overflows
		require(!frozenAccount[_from]);                       // Check if recipient is frozenAccount
		balanceOf[_from] -= _value;                           // Substract from the sender
		balanceOf[_to] += _value;                             // Add the same to the recipient
		Transfer(_from, _to, _value);
	}

	function mintToken(address targget, uint256 mintedAmount) onlyOwner {
		balanceOf[target] += mintedAmount;
		totalSupply += mintedAmount;
		Transfer(0, owner, mintedAmount):
		Transfer(owner, target, mintedAmount);
	}

	mapping (address => bool) public frozenAccount;
	event FrozenFunds(address target, bool frozen)

	function freezeAccount(address target, bool freeze) oonlyOwner {
		frozenAccount[target] = freeze;
		FrozenFunds(target, freeze);
	}

	function transfer(address _to, uint256 _value) {    // All Accounts are frozen by default, we can easily revert that behavior by just
		require(!frozenAccount[msg.sender]);          // renaming "frozenAccount" by "approvedAccount" and change the last line to "require(approvedAccount[msg.sender])"

	}

	// Automatic selling and buying
	    uint256 public sellPrice;
    uint256 public buyPrice;

    function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
        sellPrice = newSellPrice;
        buyPrice = newBuyPrice;
    }

}

pragma solidity ^0.4.0;

contract owned {
	address public owner;

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

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

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

}

contract Anemoi is owned {
	uint256 public totalSupply;
	// Public variables for the token
	string public name;
	string public symbol;
	uint8 public decimals = 18;
	// 18 decimals is the strongly default, avoid changing it
	uint256 public totalSuply;

	/* Creates an array with balances */
	mapping (address => uint256) public balanceOf;

	/* Initilizes contract with initial supply tokens to the creator of the contract */
	function Anemoi(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) {
		totalSupply = initialSupply;
		balanceOf[msg.sender] = initialSupply;   // Give the creator all initial tokens
		name = tokenName;                        // Set the name for display purposes
		symbol = tokenSymbol;                    // Set the symbol for display purposes
		decimals = decimalUnits;                 // Amount of decimals for display purposes
		uint256 intialSupply,
		string tokenName,
		uint8 decimalUnits,
		string tokenSymbol,
		address centralMinter) {
		if(centralMinter != 0 ) owner = centralMinter;
	}
}

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

	/* Internal transfer, only can be called by this contract */
	function _transfer(address _from, address _to, uint °value) internal {
		require (_to != 0*0);                                 // Prevent transfer to 0*0 address. Use burn() instead
		require (balanceOf[_from] > _value);                  // Check if the sender has enough
		require (balanceOf[_to] + _value > balanceOf[_to]);   // Chek for overflows
		require(!frozenAccount[_from]);                       // Check if recipient is frozenAccount
		balanceOf[_from] -= _value;                           // Substract from the sender
		balanceOf[_to] += _value;                             // Add the same to the recipient
		Transfer(_from, _to, _value);
	}

	function mintToken(address targget, uint256 mintedAmount) onlyOwner {
		balanceOf[target] += mintedAmount;
		totalSupply += mintedAmount;
		Transfer(0, owner, mintedAmount):
		Transfer(owner, target, mintedAmount);
	}

	mapping (address => bool) public frozenAccount;
	event FrozenFunds(address target, bool frozen)

	function freezeAccount(address target, bool freeze) oonlyOwner {
		frozenAccount[target] = freeze;
		FrozenFunds(target, freeze);
	}

	function transfer(address _to, uint256 _value) {    // All Accounts are frozen by default, we can easily revert that behavior by just
		require(!frozenAccount[msg.sender]);          // renaming "frozenAccount" by "approvedAccount" and change the last line to "require(approvedAccount[msg.sender])"

	}

}


Update ProfitSharing.sol

Update ProfitSharing.sol

pragma solidity ^0.4.11;

import './MiniMeToken.sol';
import '../installed_contracts/zeppelin/contracts/math/SafeMath.sol';
import '../installed_contracts/zeppelin/contracts/Ownership/Ownable.sol';

contract ProfitSharing is Ownable {
  using SafeMath for uint;

  event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
  event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim);
  event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);

  MiniMeToken public miniMeToken;

  uint256 public RECYCLE_TIME = 365 days;

  struct Dividend {
    uint256 blockNumber;
    uint256 timestamp;
    uint256 amount;
    uint256 claimedAmount;
    uint256 totalSupply;
    bool recycled;
    mapping (address => bool) claimed;
  }

  Dividend[] public dividends;

  mapping (address => uint256) dividendsClaimed;

  modifier validDividendIndex(uint256 _dividendIndex) {
    require(_dividendIndex < dividends.length);
    _;
  }

  function ProfitSharing(address _miniMeToken) {
    miniMeToken = MiniMeToken(_miniMeToken);
  }

  function depositDividend() payable
  onlyOwner
  {
    uint256 currentSupply = miniMeToken.totalSupplyAt(block.number);
    uint256 dividendIndex = dividends.length;
    uint256 blockNumber = SafeMath.sub(block.number, 1);
    dividends.push(
      Dividend(
        blockNumber,
        getNow(),
        msg.value,
        0,
        currentSupply,
        false
      )
    );
    DividendDeposited(msg.sender, blockNumber, msg.value, currentSupply, dividendIndex);
  }

  function claimDividend(uint256 _dividendIndex) public
  validDividendIndex(_dividendIndex)
  {
    Dividend dividend = dividends[_dividendIndex];
    require(dividend.claimed[msg.sender] == false);
    require(dividend.recycled == false);
    uint256 balance = miniMeToken.balanceOfAt(msg.sender, dividend.blockNumber);
    uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
    dividend.claimed[msg.sender] = true;
    dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
    if (claim > 0) {
      msg.sender.transfer(claim);
      DividendClaimed(msg.sender, _dividendIndex, claim);
    }
  }

  function claimDividendAll() public {
    require(dividendsClaimed[msg.sender] < dividends.length);
    for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) {
      if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) {
        dividendsClaimed[msg.sender] = SafeMath.add(i, 1);
        claimDividend(i);
      }
    }
  }

  function recycleDividend(uint256 _dividendIndex) public
  onlyOwner
  validDividendIndex(_dividendIndex)
  {
    Dividend dividend = dividends[_dividendIndex];
    require(dividend.recycled == false);
    require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME));
    dividends[_dividendIndex].recycled = true;
    uint256 currentSupply = miniMeToken.totalSupplyAt(block.number);
    uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount);
    uint256 dividendIndex = dividends.length;
    uint256 blockNumber = SafeMath.sub(block.number, 1);
    dividends.push(
      Dividend(
        blockNumber,
        getNow(),
        remainingAmount,
        0,
        currentSupply,
        false
      )
    );
    DividendRecycled(msg.sender, blockNumber, remainingAmount, currentSupply, dividendIndex);
  }

  //Function is mocked for tests
  function getNow() internal constant returns (uint256) {
    return now;
  }

}

pragma solidity ^0.4.11;

import './MiniMeToken.sol';
import '../installed_contracts/zeppelin/contracts/math/SafeMath.sol';
import '../installed_contracts/zeppelin/contracts/Ownership/Ownable.sol';

contract ProfitSharing is Ownable {
  using SafeMath for uint;

  event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
  event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim);
  event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);

  MiniMeToken public miniMeToken;

  uint256 public RECYCLE_TIME = now + 365 days;

  struct Dividend {
    uint256 blockNumber;
    uint256 timestamp;
    uint256 amount;
    uint256 claimedAmount;
    uint256 totalSupply;
    bool recycled;
    mapping (address => bool) claimed;
  }

  Dividend[] public dividends;

  mapping (address => uint256) dividendsClaimed;

  modifier validDividendIndex(uint256 _dividendIndex) {
    require(_dividendIndex < dividends.length);
    _;
  }

  function ProfitSharing(address _miniMeToken) {
    miniMeToken = MiniMeToken(_miniMeToken);
  }

  function depositDividend() payable
  onlyOwner
  {
    uint256 currentSupply = miniMeToken.totalSupplyAt(block.number);
    uint256 dividendIndex = dividends.length;
    uint256 blockNumber = SafeMath.sub(block.number, 1);
    dividends.push(
      Dividend(
        blockNumber,
        getNow(),
        msg.value,
        0,
        currentSupply,
        false
      )
    );
    DividendDeposited(msg.sender, blockNumber, msg.value, currentSupply, dividendIndex);
  }

  function claimDividend(uint256 _dividendIndex) public
  validDividendIndex(_dividendIndex)
  {
    Dividend dividend = dividends[_dividendIndex];
    require(dividend.claimed[msg.sender] == false);
    require(dividend.recycled == false);
    uint256 balance = miniMeToken.balanceOfAt(msg.sender, dividend.blockNumber);
    uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
    dividend.claimed[msg.sender] = true;
    dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
    if (claim > 0) {
      msg.sender.transfer(claim);
      DividendClaimed(msg.sender, _dividendIndex, claim);
    }
  }

  function claimDividendAll() public {
    require(dividendsClaimed[msg.sender] < dividends.length);
    for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) {
      if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) {
        dividendsClaimed[msg.sender] = SafeMath.add(i, 1);
        claimDividend(i);
      }
    }
  }

  function recycleDividend(uint256 _dividendIndex) public
  onlyOwner
  validDividendIndex(_dividendIndex)
  {
    Dividend dividend = dividends[_dividendIndex];
    require(dividend.recycled == false);
    require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME));
    dividends[_dividendIndex].recycled = true;
    uint256 currentSupply = miniMeToken.totalSupplyAt(block.number);
    uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount);
    uint256 dividendIndex = dividends.length;
    uint256 blockNumber = SafeMath.sub(block.number, 1);
    dividends.push(
      Dividend(
        blockNumber,
        getNow(),
        remainingAmount,
        0,
        currentSupply,
        false
      )
    );
    DividendRecycled(msg.sender, blockNumber, remainingAmount, currentSupply, dividendIndex);
  }

  //Function is mocked for tests
  function getNow() internal constant returns (uint256) {
    return now;
  }

}