Add commitment retrival functions to smart contract.

contract RunKeeper {

    struct Commitment {
        uint factId;
        bytes32 factHash;
        uint amount;
        address owner;
        address defaultAccount;
        address oracle;
        uint threshold;
    }

    mapping (bytes32 => Commitment) commitments;
    mapping (address => bytes32[]) accountCommitments;

    function makeCommitment(uint factId, bytes32 factHash, address defaultAccount, address oracle, uint threshold) external returns (bytes32 hash) {
        hash = sha3(this, msg.sender, msg.value, msg.data);
        commitments[hash] = Commitment({
            factId: factId,
            factHash: factHash,
            amount: msg.value,
            owner: msg.sender,
            defaultAccount: defaultAccount,
            oracle: oracle,
            threshold: threshold,
        });
        accountCommitments[msg.sender].push(hash);
    }

    function settle(bytes32 hash, bytes32 resultHex, uint8 v, bytes32 r, bytes32 s) external returns (bool) {
        Commitment commitment = commitments[hash];

        bytes32 result_hash = sha3(commitment.factHash, resultHex);
        address signer_address = ecrecover(result_hash, v, r, s);

        if (signer_address != commitment.oracle) {
            throw;
        }

        uint result = uint(resultHex);

        if (result > commitment.threshold) {
            commitment.owner.send(commitment.amount);
            return true;
        }
        else {
            commitment.defaultAccount.send(commitment.amount);
            return false;
        }
    }

    function getMyCommitmentCount() external constant returns (uint) {
        return accountCommitments[msg.sender].length;
    }

    function getMyCommitmentHash(uint i) external constant returns (bytes32) {
        return accountCommitments[msg.sender][i];
    }

    function getCommitment(bytes32 hash) external constant returns (uint factId, bytes32 factHash, uint amount, address owner, address defaultAccount, address oracle, uint threshold) {
        Commitment commitment = commitments[hash];
        factId = commitment.factId;
        factHash = commitment.factHash;
        amount = commitment.amount;
        owner = commitment.owner;
        defaultAccount = commitment.defaultAccount;
        oracle = commitment.oracle;
        threshold = commitment.threshold;
    }

}

contract RunKeeper {

    struct Commitment {
        uint factId;
        bytes32 factHash;
        uint amount;
        address owner;
        address defaultAccount;
        address oracle;
        uint threshold;
    }

    mapping (bytes32 => Commitment) commitments;
    mapping (address => bytes32[]) accountCommitments;

    function makeCommitment(uint factId, bytes32 factHash, address defaultAccount, address oracle, uint threshold) external returns (bytes32 hash) {
        hash = sha3(this, msg.sender, msg.value, msg.data);
        commitments[hash] = Commitment({
            factId: factId,
            factHash: factHash,
            amount: msg.value,
            owner: msg.sender,
            defaultAccount: defaultAccount,
            oracle: oracle,
            threshold: threshold,
        });
        accountCommitments[msg.sender].push(hash);
    }

    function settle(bytes32 hash, bytes32 resultHex, uint8 v, bytes32 r, bytes32 s) external returns (bool) {
        Commitment commitment = commitments[hash];

        bytes32 result_hash = sha3(commitment.factHash, resultHex);
        address signer_address = ecrecover(result_hash, v, r, s);

        if (signer_address != commitment.oracle) {
            throw;
        }

        uint result = uint(resultHex);

        if (result > commitment.threshold) {
            commitment.owner.send(commitment.amount);
            return true;
        }
        else {
            commitment.defaultAccount.send(commitment.amount);
            return false;
        }
    }

}


build out of accounting and position functions

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

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

    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;
        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 public BUY_SIDE = 0;
    uint8 public SELL_SIDE = 1;
    uint public COST_PER_QUERY = 2 finney;    // leave static for now, price of first query from oraclize is 0

    // 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);   // TODO: ensure struct is passed as storage!
        // continue process for taker, but qty is opposite sign for taker
        updatePosition(addressToUserPosition[taker], qty * -1, price);   // TODO: ensure struct is passed as storage!
    }

    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 {
        // TODO: determine collateral to return
    }

    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);
            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";

//TODO: fix style issues
//      add accounting for users and positions
//      how to hold ether for needed gas
//      how to hold collateral pool
//      add failsafe for pool distribution.
contract MarketContract is Creatable, usingOraclize  {
    using MathLib for uint256;
    using MathLib for int;

    struct UserPosition {
        address userAddress;
        uint[] prices;                      // prices of open positions (fifo upon exit)
        mapping(uint => int) priceToQty;    // prices to qty at price for open positions
        int netPosition;                    // net position across all prices / executions
    }

    struct Order {
        address maker;
        address taker;
        address feeRecipient;
        uint makerFee;
        uint takerFee;
        uint qty;
        uint price;
        uint8 makerSide;
        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 public BUY_SIDE = 0;
    uint8 public SELL_SIDE = 1;
    uint public COST_PER_QUERY = 2 finney;    // leave static for now, price of first query from oraclize is 0

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

    // accounting
    mapping(address => UserPosition) 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, int qty, uint price) {
        // TODO validate orders, etc
        require(maker != address(0) && maker != taker);     // do not allow self trade
        UserPosition storage makerPosition = addressToUserPosition[maker];
        // TODO create library to handle most bookeeping so we can reuse code and save gas!

        if(makerPosition.netPosition == 0 ||  makerPosition.netPosition.isSameSign(qty))
        {
            // new position or adding to open pos, no collateral returned
        }
        else
        {
            // taking position or part of position off, collateral needs to be returned
        }

        // continue process for taker.
    }

    function queryOracle() internal
    {
        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);
            validQueryIDs[queryId] = true;
        }
    }

    function checkSettlement() internal
    {
        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() internal
    {
        // 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);
    }
}


Add missing letter (#3034)

Add missing letter (#3034)

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorTimelockControl.sol)

pragma solidity ^0.8.0;

import "./IGovernorTimelock.sol";
import "../Governor.sol";
import "../TimelockController.sol";

/**
 * @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a
 * delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The
 * {Governor} needs the proposer (and ideally the executor) roles for the {Governor} to work properly.
 *
 * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
 * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
 * inaccessible.
 *
 * _Available since v4.3._
 */
abstract contract GovernorTimelockControl is IGovernorTimelock, Governor {
    TimelockController private _timelock;
    mapping(uint256 => bytes32) private _timelockIds;

    /**
     * @dev Emitted when the timelock controller used for proposal execution is modified.
     */
    event TimelockChange(address oldTimelock, address newTimelock);

    /**
     * @dev Set the timelock.
     */
    constructor(TimelockController timelockAddress) {
        _updateTimelock(timelockAddress);
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
        return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Overriden version of the {Governor-state} function with added support for the `Queued` status.
     */
    function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
        ProposalState status = super.state(proposalId);

        if (status != ProposalState.Succeeded) {
            return status;
        }

        // core tracks execution, so we just have to check if successful proposal have been queued.
        bytes32 queueid = _timelockIds[proposalId];
        if (queueid == bytes32(0)) {
            return status;
        } else if (_timelock.isOperationDone(queueid)) {
            return ProposalState.Executed;
        } else if (_timelock.isOperationPending(queueid)) {
            return ProposalState.Queued;
        } else {
            return ProposalState.Canceled;
        }
    }

    /**
     * @dev Public accessor to check the address of the timelock
     */
    function timelock() public view virtual override returns (address) {
        return address(_timelock);
    }

    /**
     * @dev Public accessor to check the eta of a queued proposal
     */
    function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
        uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]);
        return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
    }

    /**
     * @dev Function to queue a proposal to the timelock.
     */
    function queue(
        address[] memory targets,
        uint256[] memory values,
        bytes[] memory calldatas,
        bytes32 descriptionHash
    ) public virtual override returns (uint256) {
        uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);

        require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");

        uint256 delay = _timelock.getMinDelay();
        _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);
        _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay);

        emit ProposalQueued(proposalId, block.timestamp + delay);

        return proposalId;
    }

    /**
     * @dev Overriden execute function that run the already queued proposal through the timelock.
     */
    function _execute(
        uint256, /* proposalId */
        address[] memory targets,
        uint256[] memory values,
        bytes[] memory calldatas,
        bytes32 descriptionHash
    ) internal virtual override {
        _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
    }

    /**
     * @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
     * been queued.
     */
    function _cancel(
        address[] memory targets,
        uint256[] memory values,
        bytes[] memory calldatas,
        bytes32 descriptionHash
    ) internal virtual override returns (uint256) {
        uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);

        if (_timelockIds[proposalId] != 0) {
            _timelock.cancel(_timelockIds[proposalId]);
            delete _timelockIds[proposalId];
        }

        return proposalId;
    }

    /**
     * @dev Address through which the governor executes action. In this case, the timelock.
     */
    function _executor() internal view virtual override returns (address) {
        return address(_timelock);
    }

    /**
     * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
     * must be proposed, scheduled and executed using the {Governor} workflow.
     */
    function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance {
        _updateTimelock(newTimelock);
    }

    function _updateTimelock(TimelockController newTimelock) private {
        emit TimelockChange(address(_timelock), address(newTimelock));
        _timelock = newTimelock;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorTimelockControl.sol)

pragma solidity ^0.8.0;

import "./IGovernorTimelock.sol";
import "../Governor.sol";
import "../TimelockController.sol";

/**
 * @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a
 * delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The
 * {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly.
 *
 * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
 * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
 * inaccessible.
 *
 * _Available since v4.3._
 */
abstract contract GovernorTimelockControl is IGovernorTimelock, Governor {
    TimelockController private _timelock;
    mapping(uint256 => bytes32) private _timelockIds;

    /**
     * @dev Emitted when the timelock controller used for proposal execution is modified.
     */
    event TimelockChange(address oldTimelock, address newTimelock);

    /**
     * @dev Set the timelock.
     */
    constructor(TimelockController timelockAddress) {
        _updateTimelock(timelockAddress);
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
        return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Overriden version of the {Governor-state} function with added support for the `Queued` status.
     */
    function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
        ProposalState status = super.state(proposalId);

        if (status != ProposalState.Succeeded) {
            return status;
        }

        // core tracks execution, so we just have to check if successful proposal have been queued.
        bytes32 queueid = _timelockIds[proposalId];
        if (queueid == bytes32(0)) {
            return status;
        } else if (_timelock.isOperationDone(queueid)) {
            return ProposalState.Executed;
        } else if (_timelock.isOperationPending(queueid)) {
            return ProposalState.Queued;
        } else {
            return ProposalState.Canceled;
        }
    }

    /**
     * @dev Public accessor to check the address of the timelock
     */
    function timelock() public view virtual override returns (address) {
        return address(_timelock);
    }

    /**
     * @dev Public accessor to check the eta of a queued proposal
     */
    function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
        uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]);
        return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
    }

    /**
     * @dev Function to queue a proposal to the timelock.
     */
    function queue(
        address[] memory targets,
        uint256[] memory values,
        bytes[] memory calldatas,
        bytes32 descriptionHash
    ) public virtual override returns (uint256) {
        uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);

        require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");

        uint256 delay = _timelock.getMinDelay();
        _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);
        _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay);

        emit ProposalQueued(proposalId, block.timestamp + delay);

        return proposalId;
    }

    /**
     * @dev Overriden execute function that run the already queued proposal through the timelock.
     */
    function _execute(
        uint256, /* proposalId */
        address[] memory targets,
        uint256[] memory values,
        bytes[] memory calldatas,
        bytes32 descriptionHash
    ) internal virtual override {
        _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
    }

    /**
     * @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
     * been queued.
     */
    function _cancel(
        address[] memory targets,
        uint256[] memory values,
        bytes[] memory calldatas,
        bytes32 descriptionHash
    ) internal virtual override returns (uint256) {
        uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);

        if (_timelockIds[proposalId] != 0) {
            _timelock.cancel(_timelockIds[proposalId]);
            delete _timelockIds[proposalId];
        }

        return proposalId;
    }

    /**
     * @dev Address through which the governor executes action. In this case, the timelock.
     */
    function _executor() internal view virtual override returns (address) {
        return address(_timelock);
    }

    /**
     * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
     * must be proposed, scheduled and executed using the {Governor} workflow.
     */
    function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance {
        _updateTimelock(newTimelock);
    }

    function _updateTimelock(TimelockController newTimelock) private {
        emit TimelockChange(address(_timelock), address(newTimelock));
        _timelock = newTimelock;
    }
}


removed extra commission field from Transfer Struct

pragma solidity 0.4.15;
import './Owned.sol';
import './SafeMath.sol';

contract VerifiedProxy is Ownable, SafeMath {

  // Status codes
  enum Statuses {
    ACTIVE, // awaiting withdrawal
    COMPLETED, // recepient have withdrawn the transfer
    CANCELLED  // sender has cancelled the transfer
  }

  // fixed amount of wei accrued to verifier with each transfer
  uint public commissionFee;

  // verifier can withdraw this amount from smart-contract
  uint public commissionToWithdraw; // in wei

  // gas cost to withdraw transfer
  uint private WITHDRAW_GAS_COST = 60000;

  /*
   * EVENTS
   */
  event LogDeposit(
		   address indexed from,
		   bytes32 indexed transferId,
		   uint amount,
		   uint commission,
		   uint gasPrice // for verifier to withdraw to recipient with the same gas price
		   );

  event LogCancel(
		  address indexed from,
		  bytes32 indexed transferId,
		            uint amount
		  );

  event LogWithdraw(
		    bytes32 indexed transferId,
		    address indexed sender,
		    address indexed recipient,
		                  uint amount
		    );

  event LogWithdrawCommission(uint commissionAmount);

  event LogChangeFixedCommissionFee(
				    uint oldCommissionFee,
				    uint newCommissionFee
				    );

  struct Transfer {
    uint8 status; // 0 - active, 1 - completed, 2 - cancelled;
    address from;
    uint amount; // in wei
    address verificationPubKey;
  }

  // Mappings of TransferId => Transfer Struct
  mapping (bytes32 => Transfer) transferDct;

  // CONSTRUCTOR
  function VerifiedProxy(uint _commissionFee) {
    commissionFee = _commissionFee;
  }

  // deposit ether to smart contract
  function deposit(address _verPubKey, bytes32 _transferId)
                payable
    returns(bool)
  {
    // can not override old transfer
    require(transferDct[_transferId].verificationPubKey == 0);

    uint transferGasCommission = safeMul(tx.gasprice, WITHDRAW_GAS_COST);
    uint transferCommission = safeAdd(commissionFee,transferGasCommission);
    require(msg.value > transferCommission);

    // saving transfer details
    transferDct[_transferId] = Transfer(
					uint8(Statuses.ACTIVE),
					msg.sender,
					safeSub(msg.value, transferCommission), // excluding comission
					 _verPubKey
					);

    // verification server commission accrued
    commissionToWithdraw = safeAdd(commissionToWithdraw, transferCommission);
    LogDeposit(msg.sender, _transferId, msg.value, transferCommission, tx.gasprice);
    return true;
  }

  function changeFixedCommissionFee(uint _newCommissionFee)
              onlyOwner
    returns(bool success)
  {
    uint oldCommissionFee = commissionFee;
    commissionFee = _newCommissionFee;
    LogChangeFixedCommissionFee(oldCommissionFee, commissionFee);
    return true;
  }

  function withdrawCommission()
    returns(bool success)
  {
    uint commissionToTransfer = commissionToWithdraw;
    commissionToWithdraw = 0;
    owner.transfer(commissionToTransfer);

    LogWithdrawCommission(commissionToTransfer);
    return true;
  }

  function getTransfer(bytes32 _transferId)
                constant
    returns (
	     bytes32 id,
	     uint status, // 0 - active, 1 - completed, 2 - cancelled;
	     address from,
	     uint amount)
  {
    Transfer memory transfer = transferDct[_transferId];
    return (
	    _transferId,
	    transfer.status,
	    transfer.from,
	    transfer.amount
	    );
  }

  function cancelTransfer(bytes32 _transferId) returns (bool success) {
    Transfer storage transferOrder = transferDct[_transferId];
    // checks
    require(msg.sender == transferOrder.from); // only sender can cancel transfer;
    require(transferOrder.status == uint8(Statuses.ACTIVE)); // only pending transfers can be cancelled;
    transferOrder.status = uint8(Statuses.CANCELLED);

    // transfer ether back to sender
    transferOrder.from.transfer(transferOrder.amount);
    LogCancel(msg.sender, _transferId, transferOrder.amount);
    return true;
  }

  function verifySignature(
			   address _verPubKey,
			   address _recipient,
			   uint8 _v,
			   bytes32 _r,
			   bytes32 _s)
    constant returns(bool success)
  {
    bytes32 prefixedHash = sha3("\x19Ethereum Signed Message:\n32", _recipient);
    address retAddr = ecrecover(prefixedHash, _v, _r, _s);
    return retAddr == _verPubKey;
  }

  function verifyTransferSignature(
				   bytes32 _transferId,
				   address _to,
				   uint8 _v,
				   bytes32 _r,
				   bytes32 _s)
    constant returns(bool success)
  {
    Transfer memory transferOrder = transferDct[_transferId];
    return (verifySignature(transferOrder.verificationPubKey, _to, _v, _r, _s));
  }

  function withdraw(
		    bytes32 _transferId,
		    address _recipient,
		    uint8 _v,
		    bytes32 _r,
		    bytes32 _s)
    onlyOwner // only through verifier can withdraw transfer;
    returns (bool success)
  {
    Transfer storage transferOrder = transferDct[_transferId];

    // checks
    require(transferOrder.status == uint8(Statuses.ACTIVE)); // only active transfers can be withdrawn;
    require(verifySignature(transferOrder.verificationPubKey, _recipient, _v, _r, _s )); // verifying signature

    transferOrder.status = uint8(Statuses.COMPLETED);

    // transfer ether back to sender
    _recipient.transfer(transferOrder.amount);
    LogWithdraw(_transferId, transferOrder.from, _recipient, transferOrder.amount);
    return true;
  }

  // fallback function - do not receive ether by default
  function() payable {
    revert();
  }
}

pragma solidity 0.4.15;
import './Owned.sol';
import './SafeMath.sol';

contract VerifiedProxy is Ownable, SafeMath {

  // Status codes
  enum Statuses {
    ACTIVE, // awaiting withdrawal
    COMPLETED, // recepient have withdrawn the transfer
    CANCELLED  // sender has cancelled the transfer
  }

  // fixed amount of wei accrued to verifier with each transfer
  uint public commissionFee;

  // verifier can withdraw this amount from smart-contract
  uint public commissionToWithdraw; // in wei

  // gas cost to withdraw transfer
  uint private WITHDRAW_GAS_COST = 60000;
  /*
   * EVENTS
   */
  event LogDeposit(
		   address indexed from,
		   bytes32 indexed transferId,
		   uint amount,
		   uint commission,
		   uint gasPrice // for verifier to withdraw to recipient with the same gas price
		   );

  event LogCancel(
		  address indexed from,
		  bytes32 indexed transferId,
		            uint amount
		  );

  event LogWithdraw(
		    bytes32 indexed transferId,
		    address indexed sender,
		    address indexed recipient,
		                  uint amount
		    );

  event LogWithdrawCommission(
			                      uint commissionAmount
			      );

  event LogChangeFixedCommissionFee(
				    uint oldCommissionFee,
				        uint newCommissionFee
				    );

  struct Transfer {
    uint8 status; // 0 - active, 1 - completed, 2 - cancelled;
    address from;
    uint amount; // in wei
    uint commission; // in wei
    address verificationPubKey;
  }

  // Mappings of TransferId => Transfer Struct
  mapping (bytes32 => Transfer) transferDct;

  // CONSTRUCTOR
  function VerifiedProxy(uint _commissionFee) {
    commissionFee = _commissionFee;
  }

  // deposit ether to smart contract
  function deposit(address _verPubKey, bytes32 _transferId)
                payable
    returns(bool)
  {
    // can not override old transfer
    require(transferDct[_transferId].verificationPubKey == 0);

    uint transferGasCommission = safeMul(tx.gasprice, WITHDRAW_GAS_COST);
    uint transferCommission = safeAdd(commissionFee,transferGasCommission);
    require(msg.value > transferCommission);

    // saving transfer details
    transferDct[_transferId] = Transfer(
					uint8(Statuses.ACTIVE),
					msg.sender,
					safeSub(msg.value, transferCommission), // excluding comission
					commissionFee,
					 _verPubKey
					);

    // verification server commission accrued
    commissionToWithdraw = safeAdd(commissionToWithdraw, transferCommission);
    LogDeposit(msg.sender, _transferId, msg.value, transferCommission, tx.gasprice);
    return true;
  }

  function changeFixedCommissionFee(uint _newCommissionFee)
              onlyOwner
    returns(bool success)
  {
    uint oldCommissionFee = commissionFee;
    commissionFee = _newCommissionFee;
    LogChangeFixedCommissionFee(oldCommissionFee, commissionFee);
    return true;
  }

  function withdrawCommission()
    returns(bool success)
  {
    uint commissionToTransfer = commissionToWithdraw;
    commissionToWithdraw = 0;
    owner.transfer(commissionToTransfer);

    LogWithdrawCommission(commissionToTransfer);
    return true;
  }

  function getTransfer(bytes32 _transferId)
                constant
    returns (
	     bytes32 id,
	     uint status, // 0 - active, 1 - completed, 2 - cancelled;
	     address from,
	     uint amount,
	     uint commsission)
  {
    Transfer memory transfer = transferDct[_transferId];
    return (
	    _transferId,
	    transfer.status,
	    transfer.from,
	    transfer.amount,
	            transfer.commission
	    );
  }

  function cancelTransfer(bytes32 _transferId) returns (bool success) {
    Transfer storage transferOrder = transferDct[_transferId];
    // checks
    require(msg.sender == transferOrder.from); // only sender can cancel transfer;
    require(transferOrder.status == uint8(Statuses.ACTIVE)); // only pending transfers can be cancelled;
    transferOrder.status = uint8(Statuses.CANCELLED);

    // transfer ether back to sender
    transferOrder.from.transfer(transferOrder.amount);
    LogCancel(msg.sender, _transferId, transferOrder.amount);
    return true;
  }

  function verifySignature(
			   address _verPubKey,
			   address _recipient,
			   uint8 _v,
			   bytes32 _r,
			   bytes32 _s)
    constant returns(bool success)
  {
    bytes32 prefixedHash = sha3("\x19Ethereum Signed Message:\n32", _recipient);
    address retAddr = ecrecover(prefixedHash, _v, _r, _s);
    return retAddr == _verPubKey;
  }

  function verifyTransferSignature(
				   bytes32 _transferId,
				   address _to,
				   uint8 _v,
				   bytes32 _r,
				   bytes32 _s)
    constant returns(bool success)
  {
    Transfer memory transferOrder = transferDct[_transferId];
    return (verifySignature(transferOrder.verificationPubKey, _to, _v, _r, _s));
  }

  function withdraw(
		    bytes32 _transferId,
		    address _recipient,
		    uint8 _v,
		    bytes32 _r,
		    bytes32 _s)
    onlyOwner // only through verifier can withdraw transfer;
    returns (bool success)
  {
    Transfer storage transferOrder = transferDct[_transferId];

    // checks
    require(transferOrder.status == uint8(Statuses.ACTIVE)); // only active transfers can be withdrawn;
    require(verifySignature(transferOrder.verificationPubKey, _recipient, _v, _r, _s )); // verifying signature

    transferOrder.status = uint8(Statuses.COMPLETED);

    // transfer ether back to sender
    _recipient.transfer(transferOrder.amount);
    LogWithdraw(_transferId, transferOrder.from, _recipient, transferOrder.amount);
    return true;
  }

  // fallback function - do not receive ether by default
  function() payable {
    revert();
  }
}


Use bytes1 and avoid using the obsolete byte type (#2438)

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    /**
     * @dev Converts a `uint256` to its ASCII `string` representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        uint256 index = digits - 1;
        temp = value;
        while (temp != 0) {
            buffer[index--] = bytes1(uint8(48 + temp % 10));
            temp /= 10;
        }
        return string(buffer);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    /**
     * @dev Converts a `uint256` to its ASCII `string` representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        uint256 index = digits - 1;
        temp = value;
        while (temp != 0) {
            buffer[index--] = byte(uint8(48 + temp % 10));
            temp /= 10;
        }
        return string(buffer);
    }
}


Prevent overflow

Prevent overflow

Fix the following vulnerability:
The owner can set a high value in _additionalSeconds which will make closingTime overflow.
This can be used to set a closing time in the past, allowing the Owner to withdraw the funds at any time.

// The contract that allows DTH to withdraw funds that the white hat
// group has managed to retrieve.
//
// There are 2 ways to use the contract:
// 1. withdraw()
// 2. proxyWithdraw()
//
// For a description of each method, take a look at the docstrings.
//
// License: BSD3

contract DAOBalanceSnapShot {
    function balanceOf(address _dth) constant returns(uint);
    function totalSupply() constant returns(uint );
}

contract Owned {
    /// Prevents methods from perfoming any value transfer
    modifier noEther() {if (msg.value > 0) throw; _}
    /// Allows only the owner to call a function
    modifier onlyOwner { if (msg.sender != owner) throw; _ }

    address owner;

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

    function changeOwner(address _newOwner) onlyOwner {
        owner = _newOwner;
    }

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

contract WhitehatWithdraw is Owned {
    uint constant WithdrawType_DIRECT = 1;
    uint constant WithdrawType_PROXY = 2;

    DAOBalanceSnapShot daoBalance;
    mapping (address => uint) paidOut;
    mapping (bytes32 => bool) usedSignatures;
    uint totalFunds;
    uint deployTime;
    uint closingTime;
    address whg_donation;
    address escape;
    address remainingBeneficary;
    bool sealed;

    event Withdraw(address indexed dth, address indexed beneficiary, uint256  amount, uint256 percentageWHG, uint256 withdrawType);
    event CertifiedDepositorsChanged(address indexed _depositor, bool _allowed);
    event Deposit(uint amount);
    event EscapeCalled(uint amount);
    event RemainingClaimed(uint amount);

    function fill(uint[] data) onlyOwner {
        if ((msg.sender != owner)||(sealed))
            throw;

        for (uint i=0; i< data.length; i+= 2) {
            address dth = address(data[i]);
            uint amount = uint(data[i+1]);
            paidOut[dth] = amount;
            totalFunds += amount;
        }
    }

    function seal() {
        if ((msg.sender != owner)||(sealed))
            throw;

        sealed= true;
    }

    function WhitehatWithdraw(address _whg_donation, address _daoBalanceSnapshotAddress, address _escapeAddress, address _remainingBeneficiary) {
        whg_donation = _whg_donation;
        daoBalance = DAOBalanceSnapShot(_daoBalanceSnapshotAddress);
        escape = _escapeAddress;
        remainingBeneficary = _remainingBeneficiary;

        totalFunds = msg.value;
        deployTime = now;
        closingTime = 24 weeks;
    }

    /// Calculates the remaining funds available for a DTH to withdraw
    ///
    /// @param _dth          The address of the DAO Token Holder for whom
    ///                      to get the funds remaining for withdrawal
    /// @return              The amount of funds remaining for withdrawal
    function calculateWithdraw(address _dth) constant noEther returns(uint) {
        uint tokens = daoBalance.balanceOf(_dth);

        uint acumulatedReward = tokens * totalFunds / daoBalance.totalSupply();
        if (acumulatedReward < paidOut[_dth]) {
            return 0;
        }

        return acumulatedReward - paidOut[_dth];
    }

    /// The core of the withdraw functionality. It is called by all other withdraw functions
    ///
    /// @param _dth           The address of the DAO token holder for whom the
    ///                       withdrawal is going to happen
    /// @param _beneficiary   The address that will receive the _percentage of
    ///                       the funds corresponding to the _dth.
    /// @param _percentageWHG The percentage of the funds that will be donated to the
    ///                       White Hat Group. It should be a number ranging from 0
    ///                       to 100. Anything not claimed by the DTH will be going
    ///                       as a donation to the Whitehat Group.
    /// @param _withdrawType  method used to withdraw (1) Direct (2) Proxy (3) bot (4) owner
    function commonWithdraw(address _dth, address _beneficiary, uint _percentageWHG, uint _withdrawType) internal {
        if (_percentageWHG > 100) {
            throw;
        }

        uint toPay = calculateWithdraw(_dth);
        if (toPay == 0) {
            return;
        }

        if (toPay > this.balance) {
            toPay = this.balance;
        }

        uint portionWhg = toPay * _percentageWHG / 100;
        uint portionDth = toPay - portionWhg;
        paidOut[_dth] += toPay;

        // re-entrancy is not possible due to the use of send() which limits
        // the forwarded gas thanks to the gas stipend

        if (portionWhg > 0) {
             if ( !whg_donation.send(portionWhg) ) {
                throw;
             }
        }

        if (portionDth > 0) {
            if (!_beneficiary.send(portionDth) ) {
                throw;
            }
        }

        Withdraw(_dth, _beneficiary,  toPay, _percentageWHG, _withdrawType);
    }

    /// The simple withdraw function, where the message sender is considered as
    /// the DAO token holder whose ratio needs to be retrieved.
    function withdraw(address _beneficiary, uint _percentageWHG ) noEther {
        commonWithdraw(msg.sender, _beneficiary, _percentageWHG, WithdrawType_DIRECT);
    }

    /// The proxy withdraw function. Anyone can call this for someone else as long
    /// as he includes signed data retrieved by using web3.eth.sign(address, hash).
    /// The DAO token holder whose ratio needs to be retrieved is determined by
    /// performing ecrecover on the signed data.
    ///
    /// This function will also allow people to use the ETH chain to give an
    /// approval for withdrawal in the ETC chain without having to sync the
    /// ETC chain. The only requirement is that the account that gives the
    /// approval needs to be an end-user account. Multisig wallets can't do that.
    function proxyWithdraw(address _beneficiary, uint _percentageWHG, uint8 _v, bytes32 _r, bytes32 _s) noEther {
        if (usedSignatures[_r]) {
            throw;
        }
        bytes32 _hash = sha3("Withdraw DAOETC to ", _beneficiary, _percentageWHG);
        address _dth = ecrecover(_hash, _v, _r, _s);
        usedSignatures[_r] = true;
        commonWithdraw(_dth, _beneficiary, _percentageWHG, WithdrawType_PROXY);
    }

    /// This is the only way to send money to the contract, adding to the total
    /// amount of ETH to be refunded.
    function deposit() returns (bool) {
        totalFunds += msg.value;
        Deposit(msg.value);
        return true;
    }

    /// Last Resort call, to allow for a reaction if something bad happens to
    /// the contract or if some security issue is uncovered.
    function escapeHatch() noEther onlyOwner returns (bool) {
        uint total = this.balance;
        if (!escape.send(total)) {
            throw;
        }
        EscapeCalled(total);
    }

    /// Allows the claiming of the remaining funds after a given amount of time
    /// Amount is set to 6 months for now but may still change in the future.
    function claimRemaining() noEther returns (bool) {
        if (now < deployTime + closingTime) {
            throw;
        }
        uint total = this.balance;
        if (!remainingBeneficary.send(total)) {
            throw;
        }
        RemainingClaimed(total);
    }

    /// Allows the option to extend (but not shorten!) the closingTime of the
    /// contract to more than 6 months, perhaps even to infinity if that is
    /// deemed as the best choice for the DAO Token holders.
    function extendClosingTime(uint _additionalSeconds) noEther onlyOwner {
        closingTime += _additionalSeconds;
        if (closingTime<_additionalSeconds) // Prevent overflow.
            throw;
    }

    function () { //no donations
        throw;
    }

    function getPaidOut(address _account) noEther constant returns (uint) {
        return paidOut[_account];
    }

    function getMyBalance(address _account) noEther constant returns (uint) {
        return daoBalance.balanceOf(_account);
    }

    function getTotalFunds() noEther constant returns (uint) {
        return totalFunds;
    }

    function getWHGDonationAddress() noEther constant returns (address) {
        return whg_donation;
    }
}

// The contract that allows DTH to withdraw funds that the white hat
// group has managed to retrieve.
//
// There are 2 ways to use the contract:
// 1. withdraw()
// 2. proxyWithdraw()
//
// For a description of each method, take a look at the docstrings.
//
// License: BSD3

contract DAOBalanceSnapShot {
    function balanceOf(address _dth) constant returns(uint);
    function totalSupply() constant returns(uint );
}

contract Owned {
    /// Prevents methods from perfoming any value transfer
    modifier noEther() {if (msg.value > 0) throw; _}
    /// Allows only the owner to call a function
    modifier onlyOwner { if (msg.sender != owner) throw; _ }

    address owner;

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

    function changeOwner(address _newOwner) onlyOwner {
        owner = _newOwner;
    }

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

contract WhitehatWithdraw is Owned {
    uint constant WithdrawType_DIRECT = 1;
    uint constant WithdrawType_PROXY = 2;

    DAOBalanceSnapShot daoBalance;
    mapping (address => uint) paidOut;
    mapping (bytes32 => bool) usedSignatures;
    uint totalFunds;
    uint deployTime;
    uint closingTime;
    address whg_donation;
    address escape;
    address remainingBeneficary;
    bool sealed;

    event Withdraw(address indexed dth, address indexed beneficiary, uint256  amount, uint256 percentageWHG, uint256 withdrawType);
    event CertifiedDepositorsChanged(address indexed _depositor, bool _allowed);
    event Deposit(uint amount);
    event EscapeCalled(uint amount);
    event RemainingClaimed(uint amount);

    function fill(uint[] data) onlyOwner {
        if ((msg.sender != owner)||(sealed))
            throw;

        for (uint i=0; i< data.length; i+= 2) {
            address dth = address(data[i]);
            uint amount = uint(data[i+1]);
            paidOut[dth] = amount;
            totalFunds += amount;
        }
    }

    function seal() {
        if ((msg.sender != owner)||(sealed))
            throw;

        sealed= true;
    }

    function WhitehatWithdraw(address _whg_donation, address _daoBalanceSnapshotAddress, address _escapeAddress, address _remainingBeneficiary) {
        whg_donation = _whg_donation;
        daoBalance = DAOBalanceSnapShot(_daoBalanceSnapshotAddress);
        escape = _escapeAddress;
        remainingBeneficary = _remainingBeneficiary;

        totalFunds = msg.value;
        deployTime = now;
        closingTime = 24 weeks;
    }

    /// Calculates the remaining funds available for a DTH to withdraw
    ///
    /// @param _dth          The address of the DAO Token Holder for whom
    ///                      to get the funds remaining for withdrawal
    /// @return              The amount of funds remaining for withdrawal
    function calculateWithdraw(address _dth) constant noEther returns(uint) {
        uint tokens = daoBalance.balanceOf(_dth);

        uint acumulatedReward = tokens * totalFunds / daoBalance.totalSupply();
        if (acumulatedReward < paidOut[_dth]) {
            return 0;
        }

        return acumulatedReward - paidOut[_dth];
    }

    /// The core of the withdraw functionality. It is called by all other withdraw functions
    ///
    /// @param _dth           The address of the DAO token holder for whom the
    ///                       withdrawal is going to happen
    /// @param _beneficiary   The address that will receive the _percentage of
    ///                       the funds corresponding to the _dth.
    /// @param _percentageWHG The percentage of the funds that will be donated to the
    ///                       White Hat Group. It should be a number ranging from 0
    ///                       to 100. Anything not claimed by the DTH will be going
    ///                       as a donation to the Whitehat Group.
    /// @param _withdrawType  method used to withdraw (1) Direct (2) Proxy (3) bot (4) owner
    function commonWithdraw(address _dth, address _beneficiary, uint _percentageWHG, uint _withdrawType) internal {
        if (_percentageWHG > 100) {
            throw;
        }

        uint toPay = calculateWithdraw(_dth);
        if (toPay == 0) {
            return;
        }

        if (toPay > this.balance) {
            toPay = this.balance;
        }

        uint portionWhg = toPay * _percentageWHG / 100;
        uint portionDth = toPay - portionWhg;
        paidOut[_dth] += toPay;

        // re-entrancy is not possible due to the use of send() which limits
        // the forwarded gas thanks to the gas stipend

        if (portionWhg > 0) {
             if ( !whg_donation.send(portionWhg) ) {
                throw;
             }
        }

        if (portionDth > 0) {
            if (!_beneficiary.send(portionDth) ) {
                throw;
            }
        }

        Withdraw(_dth, _beneficiary,  toPay, _percentageWHG, _withdrawType);
    }

    /// The simple withdraw function, where the message sender is considered as
    /// the DAO token holder whose ratio needs to be retrieved.
    function withdraw(address _beneficiary, uint _percentageWHG ) noEther {
        commonWithdraw(msg.sender, _beneficiary, _percentageWHG, WithdrawType_DIRECT);
    }

    /// The proxy withdraw function. Anyone can call this for someone else as long
    /// as he includes signed data retrieved by using web3.eth.sign(address, hash).
    /// The DAO token holder whose ratio needs to be retrieved is determined by
    /// performing ecrecover on the signed data.
    ///
    /// This function will also allow people to use the ETH chain to give an
    /// approval for withdrawal in the ETC chain without having to sync the
    /// ETC chain. The only requirement is that the account that gives the
    /// approval needs to be an end-user account. Multisig wallets can't do that.
    function proxyWithdraw(address _beneficiary, uint _percentageWHG, uint8 _v, bytes32 _r, bytes32 _s) noEther {
        if (usedSignatures[_r]) {
            throw;
        }
        bytes32 _hash = sha3("Withdraw DAOETC to ", _beneficiary, _percentageWHG);
        address _dth = ecrecover(_hash, _v, _r, _s);
        usedSignatures[_r] = true;
        commonWithdraw(_dth, _beneficiary, _percentageWHG, WithdrawType_PROXY);
    }

    /// This is the only way to send money to the contract, adding to the total
    /// amount of ETH to be refunded.
    function deposit() returns (bool) {
        totalFunds += msg.value;
        Deposit(msg.value);
        return true;
    }

    /// Last Resort call, to allow for a reaction if something bad happens to
    /// the contract or if some security issue is uncovered.
    function escapeHatch() noEther onlyOwner returns (bool) {
        uint total = this.balance;
        if (!escape.send(total)) {
            throw;
        }
        EscapeCalled(total);
    }

    /// Allows the claiming of the remaining funds after a given amount of time
    /// Amount is set to 6 months for now but may still change in the future.
    function claimRemaining() noEther returns (bool) {
        if (now < deployTime + closingTime) {
            throw;
        }
        uint total = this.balance;
        if (!remainingBeneficary.send(total)) {
            throw;
        }
        RemainingClaimed(total);
    }

    /// Allows the option to extend (but not shorten!) the closingTime of the
    /// contract to more than 6 months, perhaps even to infinity if that is
    /// deemed as the best choice for the DAO Token holders.
    function extendClosingTime(uint _additionalSeconds) noEther onlyOwner {
        closingTime += _additionalSeconds;
    }

    function () { //no donations
        throw;
    }

    function getPaidOut(address _account) noEther constant returns (uint) {
        return paidOut[_account];
    }

    function getMyBalance(address _account) noEther constant returns (uint) {
        return daoBalance.balanceOf(_account);
    }

    function getTotalFunds() noEther constant returns (uint) {
        return totalFunds;
    }

    function getWHGDonationAddress() noEther constant returns (address) {
        return whg_donation;
    }
}


refactor(catalogo): renomear parametros para facilitar uso via remix

pragma solidity ^0.4.11;

/// @title Catalogo de Ouvidorias para o Barramento de Ouvidorias
/*
    Cada ouvidoria somente pode autorizar uma vez.
*/
contract CatalogoOuvidorias {

    uint constant NUMERO_DE_AUTORIZACOES_EXIGIDAS_PARA_UMA_NOVA_OUVIDORIA_PODER_CADASTRARSE = 3;

    enum TipoEnte { Uniao, Estado, Municipio }

    struct Ente {
        TipoEnte tipo;
        bytes32 nome;   // nome do ente, caso se aplique (Uniao nao eh necessario). Ex.: 'Bahia', 'Salvador-BA'
    }

    struct Ouvidoria {
        address conta; // account Ethereum desta ouvidoria
        bytes32 nome;   // nome do orgao
        Ente ente; // ente a qual a ouvidoria pertence
        bytes32 endpoint;   // URL da aplicacao/web service desta ouvidoria

        // variavel de controle pq o solidity eh peh duro e nao fornece maneiras de testar se uma chave existe no map
        // https://ethereum.stackexchange.com/a/13029
        // https://ethereum.meta.stackexchange.com/questions/443/blog-simple-storage-patterns-in-solidity
        bool existe;
    }

    address[] enderecosOuvidorias;

    mapping(address => Ouvidoria) private ouvidorias;

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

    event ouvidoriaCadastrada(address conta, bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint);

    event ouvidoriaAutorizada(address ouvidoriaAutorizadora, address ouvidoriaCandidata);

    /// Cria o catalogo com uma ouvidoria -- nao exigi tres porque seriam tantas variaveis que o solarity nao permite:
    /// Compiler error (...): Stack too deep, try removing local variables.
    function CatalogoOuvidorias(bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint) {
        inserirOuvidoriaNoCadastro(msg.sender, nome, tipoEnte, nomeEnte, endpoint);
    }

    function inserirOuvidoriaNoCadastro(address conta, bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint) private {
        ouvidorias[conta] = Ouvidoria({
            conta: conta,
            nome: nome,
            ente: Ente({tipo: toTipoEnte(tipoEnte), nome: nomeEnte}),
            endpoint: endpoint,
            existe: true
        });
        enderecosOuvidorias.push(conta);
    }

    function toTipoEnte(uint8 tipo) returns (TipoEnte) {
        if (tipo == 0) return TipoEnte.Uniao;
        if (tipo == 1) return TipoEnte.Estado;
        if (tipo == 2) return TipoEnte.Municipio;
        throw;
    }

    function getNumeroDeOuvidorias() constant returns (uint) {
        return enderecosOuvidorias.length;
    }

    function getEnderecoOuvidoria(uint indiceDaOuvidoriaNoArray) constant returns (address) {
        return enderecosOuvidorias[indiceDaOuvidoriaNoArray];
    }

    function getOuvidoriaNome(address contaOuvidoria) constant returns (string) {
        return toString(ouvidorias[contaOuvidoria].nome);
    }

    function getOuvidoriaEndpoint(address contaOuvidoria) constant returns (string) {
        return toString(ouvidorias[contaOuvidoria].endpoint);
    }

    function getOuvidoriaEnteTipo(address contaOuvidoria) constant returns (uint) {
        return uint(ouvidorias[contaOuvidoria].ente.tipo);
    }

    function getOuvidoriaEnteNome(address contaOuvidoria) constant returns (string) {
        return toString(ouvidorias[contaOuvidoria].ente.nome);
    }

    /// Uma ouvidoria cadastrada pode autorizar outra que ainda nao se cadastrou
    function autorizar(address contaOuvidoriaCandidata) {
        require(
            isOuvidoriaCadastrada(msg.sender) &&
            !isOuvidoriaCadastrada(contaOuvidoriaCandidata) &&
            autorizadoraNuncaAutorizouCandidata(msg.sender, contaOuvidoriaCandidata)
        );
        ouvidoriasCandidatasComAutorizacoes[contaOuvidoriaCandidata].push(msg.sender);

        ouvidoriaAutorizada(msg.sender, contaOuvidoriaCandidata);
    }

    function isOuvidoriaCadastrada(address contaOuvidoria) constant returns (bool) {
        return ouvidorias[contaOuvidoria].existe;
    }

    function autorizadoraNuncaAutorizouCandidata(address contaOuvidoriaAutorizadora, address contaOuvidoriaCandidata) constant returns (bool) {
        var quemJahAutorizouEstaCandidata = ouvidoriasCandidatasComAutorizacoes[contaOuvidoriaCandidata];
        for (uint i = 0; i < quemJahAutorizouEstaCandidata.length; i++) {
            if (quemJahAutorizouEstaCandidata[i] == contaOuvidoriaAutorizadora) {
                return false;
            }
        }
        return true;
    }

    /// Uma ouvidoria que recebeu autorizacoes suficientes pode cadastrar-se
    function cadastrar(bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint) {
        require(quantidadeDeAutorizacoes(msg.sender) >= quantidadeDeAutorizacoesNecessariasParaUmaNovaOuvidoriaPoderSeCadastrar());

        inserirOuvidoriaNoCadastro(msg.sender, nome, tipoEnte, nomeEnte, endpoint);
        ouvidoriaCadastrada(msg.sender, nome, tipoEnte, nomeEnte, endpoint);
    }

    function quantidadeDeAutorizacoes(address contaOuvidoriaCandidata) constant returns (uint) {
        return ouvidoriasCandidatasComAutorizacoes[contaOuvidoriaCandidata].length;
    }

    function quantidadeDeAutorizacoesNecessariasParaUmaNovaOuvidoriaPoderSeCadastrar() constant returns (uint) {
        if (enderecosOuvidorias.length < NUMERO_DE_AUTORIZACOES_EXIGIDAS_PARA_UMA_NOVA_OUVIDORIA_PODER_CADASTRARSE) {
            return enderecosOuvidorias.length;
        }
        return NUMERO_DE_AUTORIZACOES_EXIGIDAS_PARA_UMA_NOVA_OUVIDORIA_PODER_CADASTRARSE;
    }

    // converte bytes32 em string
    function toString(bytes32 x) private constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

}

pragma solidity ^0.4.11;

/// @title Catalogo de Ouvidorias para o Barramento de Ouvidorias
/*
    Cada ouvidoria somente pode autorizar uma vez.
*/
contract CatalogoOuvidorias {

    uint constant NUMERO_DE_AUTORIZACOES_EXIGIDAS_PARA_UMA_NOVA_OUVIDORIA_PODER_CADASTRARSE = 3;

    enum TipoEnte { Uniao, Estado, Municipio }

    struct Ente {
        TipoEnte tipo;
        bytes32 nome;   // nome do ente, caso se aplique (Uniao nao eh necessario). Ex.: 'Bahia', 'Salvador-BA'
    }

    struct Ouvidoria {
        address conta; // account Ethereum desta ouvidoria
        bytes32 nome;   // nome do orgao
        Ente ente; // ente a qual a ouvidoria pertence
        bytes32 endpoint;   // URL da aplicacao/web service desta ouvidoria

        // variavel de controle pq o solidity eh peh duro e nao fornece maneiras de testar se uma chave existe no map
        // https://ethereum.stackexchange.com/a/13029
        // https://ethereum.meta.stackexchange.com/questions/443/blog-simple-storage-patterns-in-solidity
        bool existe;
    }

    address[] enderecosOuvidorias;

    mapping(address => Ouvidoria) private ouvidorias;

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

    event ouvidoriaCadastrada(address conta, bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint);

    event ouvidoriaAutorizada(address ouvidoriaAutorizadora, address ouvidoriaCandidata);

    /// Cria o catalogo com uma ouvidoria -- nao exigi tres porque seriam tantas variaveis que o solarity nao permite:
    /// Compiler error (...): Stack too deep, try removing local variables.
    function CatalogoOuvidorias(bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint) {
        inserirOuvidoriaNoCadastro(msg.sender, nome, tipoEnte, nomeEnte, endpoint);
    }

    function inserirOuvidoriaNoCadastro(address conta, bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint) private {
        ouvidorias[conta] = Ouvidoria({
            conta: conta,
            nome: nome,
            ente: Ente({tipo: toTipoEnte(tipoEnte), nome: nomeEnte}),
            endpoint: endpoint,
            existe: true
        });
        enderecosOuvidorias.push(conta);
    }

    function toTipoEnte(uint8 tipo) returns (TipoEnte) {
        if (tipo == 0) return TipoEnte.Uniao;
        if (tipo == 1) return TipoEnte.Estado;
        if (tipo == 2) return TipoEnte.Municipio;
        throw;
    }

    function getNumeroDeOuvidorias() constant returns (uint) {
        return enderecosOuvidorias.length;
    }

    function getEnderecoOuvidoria(uint i) constant returns (address) {
        return enderecosOuvidorias[i];
    }

    function getOuvidoriaNome(address ouvidoria) constant returns (string) {
        return toString(ouvidorias[ouvidoria].nome);
    }

    function getOuvidoriaEndpoint(address ouvidoria) constant returns (string) {
        return toString(ouvidorias[ouvidoria].endpoint);
    }

    function getOuvidoriaEnteTipo(address ouvidoria) constant returns (uint) {
        return uint(ouvidorias[ouvidoria].ente.tipo);
    }

    function getOuvidoriaEnteNome(address ouvidoria) constant returns (string) {
        return toString(ouvidorias[ouvidoria].ente.nome);
    }

    /// Uma ouvidoria cadastrada pode autorizar outra que ainda nao se cadastrou
    function autorizar(address ouvidoriaCandidata) {
        require(
            isOuvidoriaCadastrada(msg.sender) &&
            !isOuvidoriaCadastrada(ouvidoriaCandidata) &&
            autorizadoraNuncaAutorizouCandidata(msg.sender, ouvidoriaCandidata)
        );
        ouvidoriasCandidatasComAutorizacoes[ouvidoriaCandidata].push(msg.sender);

        ouvidoriaAutorizada(msg.sender, ouvidoriaCandidata);
    }

    function isOuvidoriaCadastrada(address enderecoOuvidoria) constant returns (bool) {
        return ouvidorias[enderecoOuvidoria].existe;
    }

    function autorizadoraNuncaAutorizouCandidata(address ouvidoriaAutorizadora, address ouvidoriaCandidata) constant returns (bool) {
        var quemJahAutorizouEstaCandidata = ouvidoriasCandidatasComAutorizacoes[ouvidoriaCandidata];
        for (uint i = 0; i < quemJahAutorizouEstaCandidata.length; i++) {
            if (quemJahAutorizouEstaCandidata[i] == ouvidoriaAutorizadora) {
                return false;
            }
        }
        return true;
    }

    /// Uma ouvidoria que recebeu autorizacoes suficientes pode cadastrar-se
    function cadastrar(bytes32 nome, uint8 tipoEnte, bytes32 nomeEnte, bytes32 endpoint) {
        require(quantidadeDeAutorizacoes(msg.sender) >= quantidadeDeAutorizacoesNecessariasParaUmaNovaOuvidoriaPoderSeCadastrar());

        inserirOuvidoriaNoCadastro(msg.sender, nome, tipoEnte, nomeEnte, endpoint);
        ouvidoriaCadastrada(msg.sender, nome, tipoEnte, nomeEnte, endpoint);
    }

    function quantidadeDeAutorizacoes(address ouvidoriaCandidata) constant returns (uint) {
        return ouvidoriasCandidatasComAutorizacoes[ouvidoriaCandidata].length;
    }

    function quantidadeDeAutorizacoesNecessariasParaUmaNovaOuvidoriaPoderSeCadastrar() constant returns (uint) {
        if (enderecosOuvidorias.length < NUMERO_DE_AUTORIZACOES_EXIGIDAS_PARA_UMA_NOVA_OUVIDORIA_PODER_CADASTRARSE) {
            return enderecosOuvidorias.length;
        }
        return NUMERO_DE_AUTORIZACOES_EXIGIDAS_PARA_UMA_NOVA_OUVIDORIA_PODER_CADASTRARSE;
    }

    // converte bytes32 em string
    function toString(bytes32 x) private constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

}


fixed import path of ConvertLib.sol

fixed import path of ConvertLib.sol

pragma solidity ^0.4.2;

import "./ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {
	mapping (address => uint) balances;

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

	function MetaCoin() {
		balances[tx.origin] = 10000;
	}

	function sendCoin(address receiver, uint amount) returns(bool sufficient) {
		if (balances[msg.sender] < amount) return false;
		balances[msg.sender] -= amount;
		balances[receiver] += amount;
		Transfer(msg.sender, receiver, amount);
		return true;
	}

	function getBalanceInEth(address addr) returns(uint){
		return ConvertLib.convert(getBalance(addr),2);
	}

	function getBalance(address addr) returns(uint) {
		return balances[addr];
	}
}

pragma solidity ^0.4.2;

import "ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {
	mapping (address => uint) balances;

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

	function MetaCoin() {
		balances[tx.origin] = 10000;
	}

	function sendCoin(address receiver, uint amount) returns(bool sufficient) {
		if (balances[msg.sender] < amount) return false;
		balances[msg.sender] -= amount;
		balances[receiver] += amount;
		Transfer(msg.sender, receiver, amount);
		return true;
	}

	function getBalanceInEth(address addr) returns(uint){
		return ConvertLib.convert(getBalance(addr),2);
	}

	function getBalance(address addr) returns(uint) {
		return balances[addr];
	}
}


Fix constructor assert

Fix constructor assert

pragma solidity 0.5.0;

contract AssertFail {
    constructor(uint8 var1) public {
        assert(var1 > 0);
    }
}

pragma solidity ^0.4.24;

contract AssertFail {

	constructor(uint8 var1){
		assert(var1>0);
	}
}


Make memory access library shortcut future accesses once state is known invalid.

library AVMMemoryContext32 {
    struct Context {
        uint256[] readAccesses;
        uint256[] writeAccesses;
        uint writeIdx;
        uint cachedRead;
        uint cachedReadValue;
        uint addressMask;
        bool valid;
    }

    event trace(string);
    event traceNum(uint);
    event MissingRead(uint);
    event BadWriteAddress(uint, uint);
    event BadWriteValue(uint, uint, uint);
    function initContext(uint256[] memory readAccesses, uint256[] memory writeAccesses, uint addressBits) internal returns (Context memory) {
        Context memory ctx;
        ctx.readAccesses = readAccesses;
        ctx.writeAccesses = writeAccesses;
        ctx.writeIdx = 0;
        ctx.addressMask = (2 ** addressBits) - 1;
        ctx.cachedRead = (uint) (-1);
        ctx.cachedReadValue = 0;
        ctx.valid = true;
        return ctx;
    }

    function read256(Context ctx, uint addr) internal returns (uint) {
        if (!ctx.valid) return 0;

        uint v;
        addr = addr & ctx.addressMask;

        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == (addr / 32)) {
                return ctx.readAccesses[i+1];
            }
        }

        ctx.valid = false;
        MissingRead(addr / 32);
        return 0;
    }

    function read32(Context ctx, uint addr) internal returns (uint32) {
        uint v = read256(ctx, addr);

        // Shift down to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            v = v / 4294967296;
        }

        return (uint32) (v);
    }

    function readByte(Context ctx, uint addr) internal returns (uint8) {
        uint32 v = read32(ctx, addr);

        for (uint j = (addr % 4); j < 3; j++) {
            v = v / 256;
        }

        return (uint8) (v);
    }

    function write256(Context ctx, uint addr, uint value) internal {
        if (!ctx.valid) return;
        addr = addr & ctx.addressMask;

        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
            ctx.valid = false;
            return;
        }

        // Whole overwrite - ignore prior value
        ctx.writeIdx++;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != value) {
            // Wrong write value
            BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
            ctx.valid = false;
            return;
        }

        trace("Updating read values for write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function write32(Context ctx, uint addr, uint value) internal {
        if (!ctx.valid) return;
        addr = addr & ctx.addressMask;

        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
            ctx.valid = false;
            return;
        }

        trace("Reading write prior value");
        uint result = ctx.writeAccesses[ctx.writeIdx++];
        uint mask = 4294967295;
        value = value & mask;

        // Shift up to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            mask = mask * 4294967296;
            value = value * 4294967296;
        }

        result = (result & (~mask)) | value;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != result) {
            // Wrong write value
            BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
            ctx.valid = false;
            return;
        }

        trace("Updating future read values from write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function isValid(Context memory ctx) internal returns (bool) {
        if (ctx.writeAccesses.length != ctx.writeIdx) {
            // Excess reads
            ctx.valid = false;
        }
        return ctx.valid;
    }
}

library AVMMemoryContext32 {
    struct Context {
        uint256[] readAccesses;
        uint256[] writeAccesses;
        uint writeIdx;
        uint cachedRead;
        uint cachedReadValue;
        uint addressMask;
        uint addressMask32;
        uint addressMask256;
        bool valid;
    }

    event trace(string);
    event traceNum(uint);
    event MissingRead(uint);
    event BadWriteAddress(uint, uint);
    event BadWriteValue(uint, uint, uint);
    function initContext(uint256[] memory readAccesses, uint256[] memory writeAccesses, uint addressBits) internal returns (Context memory) {
        Context memory ctx;
        ctx.readAccesses = readAccesses;
        ctx.writeAccesses = writeAccesses;
        ctx.writeIdx = 0;
        ctx.addressMask = (2 ** addressBits) - 1;
        ctx.addressMask256 = ctx.addressMask ^ 31;
        ctx.addressMask32 = ctx.addressMask ^ 3;
        ctx.cachedRead = (uint) (-1);
        ctx.cachedReadValue = 0;
        ctx.valid = true;
        return ctx;
    }

    function read256(Context ctx, uint addr) internal returns (uint) {
        uint v;
        addr = addr & ctx.addressMask;

        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == (addr / 32)) {
                return ctx.readAccesses[i+1];
            }
        }

        ctx.valid = false;
        MissingRead(addr / 32);
        return 0;
    }

    function read32(Context ctx, uint addr) internal returns (uint32) {
        uint v = read256(ctx, addr);

        // Shift down to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            v = v / 4294967296;
        }

        return (uint32) (v);
    }

    function readByte(Context ctx, uint addr) internal returns (uint8) {
        uint32 v = read32(ctx, addr);

        for (uint j = (addr % 4); j < 3; j++) {
            v = v / 256;
        }

        return (uint8) (v);
    }

    function write256(Context ctx, uint addr, uint value) internal {
        addr = addr & ctx.addressMask;

        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
            ctx.valid = false;
            return;
        }

        // Whole overwrite - ignore prior value
        ctx.writeIdx++;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != value) {
            // Wrong write value
            BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
            ctx.valid = false;
            return;
        }

        trace("Updating read values for write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function write32(Context ctx, uint addr, uint value) internal {
        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
            ctx.valid = false;
            return;
        }

        trace("Reading write prior value");
        uint result = ctx.writeAccesses[ctx.writeIdx++];
        uint mask = 4294967295;
        value = value & mask;

        // Shift up to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            mask = mask * 4294967296;
            value = value * 4294967296;
        }

        result = (result & (~mask)) | value;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != result) {
            // Wrong write value
            BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
            ctx.valid = false;
            return;
        }

        trace("Updating future read values from write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function isValid(Context memory ctx) internal returns (bool) {
        if (ctx.writeAccesses.length != ctx.writeIdx) {
            // Excess reads
            ctx.valid = false;
        }
        return ctx.valid;
    }
}


unique events, removed bookid

unique events, removed bookid

pragma solidity ^0.4.4;

// ------------------------------------------------------------------------
// TokenSellerFactory
//
// Decentralised trustless ERC20-partially-compliant token to ETH exchange
// contract on the Ethereum blockchain.
//
// This caters for the Golem Network Token which does not implement the
// transferFrom(...), approve(...) and allowance(...) methods
//
// Enjoy. (c) JonnyLatte, Cintix & BokkyPooBah 2016. The MIT licence.
// ------------------------------------------------------------------------

// https://github.com/ethereum/EIPs/issues/20
contract ERC20Partial {
    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 sell tokens for ETH
// prices are in amount of wei per batch of token units

contract TokenSeller is Owned {

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

    bool public sellsTokens;    // is contract selling

    event ActivatedEvent(bool sells);
    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 TokenSeller (
        address _asset,
        uint256 _sellPrice,
        uint256 _units,
        bool    _sellsTokens,
        bool    _buysTokens
    ) {
        asset       = _asset;
        buyPrice    = _buyPrice;
        sellPrice   = _sellPrice;
        units       = _units;
        sellsTokens = _sellsTokens;
        ActivatedEvent(sellsTokens);
    }

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

    // allow owner to remove trade token
    function withdrawAsset(uint256 _value) onlyOwner returns (bool ok) {
        AssetWithdrawn(_value);
        return ERC20Partial(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 ERC20Partial(_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 = ERC20Partial(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(!ERC20Partial(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
    }

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

// This contract deploys TokenSeller contracts and logs the event
contract TokenSellerFactory 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 sellPrice,
        uint256 units,
        bool    sellsTokens
    ) {
        valid = _verify[tradeContract];
        if (valid) {
            TokenSeller t = TokenSeller(tradeContract);
            asset       = t.asset();
            sellPrice   = t.sellPrice();
            units       = t.units();
            sellsTokens = t.sellsTokens();
        }
    }

    function createTradeContract(
        address _asset,
        uint256 _sellPrice,
        uint256 _units,
        bool    _sellsTokens
    ) returns (address) {
        if (_units == 0) throw;            // can't sell zero units
        address trader = new TokenSeller(
            _asset,
            _sellPrice,
            _units,
            _sellsTokens);
        _verify[trader] = true; // record that this factory created the trader
        TokenSeller(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 ERC20Partial(_token).transfer(owner, _value);
    }

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

pragma solidity ^0.4.0;

//https://github.com/nexusdev/erc20/blob/master/contracts/erc20.sol

contract ERC20Constant {
    function balanceOf( address who ) constant returns (uint value);
}
contract ERC20Stateful {
    function transfer( address to, uint value) returns (bool ok);
}
contract ERC20Events {
    event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC20 is ERC20Constant, ERC20Stateful, ERC20Events {}

contract owned {
    address public owner;

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

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

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

// contract can 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 sellPrice;   // contract sells lots of tokens at this price
    uint256 public units;       // lot size (token-wei)

    bool public sellsTokens;    // is contract selling

    event ActivatedEvent(bool sells);
    event UpdateEvent();

    function TokenTrader (
        address _asset,
        uint256 _sellPrice,
        uint256 _units,
        bool    _sellsTokens
        )
    {
          asset         = _asset;
          sellPrice    = _sellPrice;
          units         = _units;
          sellsTokens   = _sellsTokens;

          ActivatedEvent(sellsTokens);
    }

    // modify trading behavior
    function activate (
        bool    _sellsTokens
        ) onlyOwner
    {
          sellsTokens   = _sellsTokens;

          ActivatedEvent(sellsTokens);
    }

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

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

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

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

            if(order > can_sell)
            {
                uint256 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;
            }
            UpdateEvent();
        }
        else if(!msg.sender.send(msg.value)) throw;  // return user funds if the contract is not selling
    }

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

// This contract deploys TokenTrader contracts and logs the event
// trade pairs are identified with sha3(asset,units)

contract TokenTraderFactory {

    event TradeListing(bytes32 bookid, address owner, address addr);
    event NewBook(bytes32 bookid, address asset, uint256 units);

    mapping( address => bool ) _verify;
    mapping( bytes32 => bool ) pairExits;

    function verify(address tradeContract)  constant returns (
        bool valid,
        address asset,
        uint256 sellPrice,
        uint256 units,
        bool    sellsTokens
        ) {

            valid = _verify[tradeContract];

            if(valid) {
                TokenTrader t = TokenTrader(tradeContract);

                asset = t.asset();
                sellPrice = t.sellPrice();
                units = t.units();
                sellsTokens = t.sellsTokens();
            }

    }

    function createTradeContract(
        address _asset,
        uint256 _sellPrice,
        uint256 _units,
        bool    _sellsTokens
        ) returns (address)
    {
        if(_units == 0) throw;              // can't sell zero units

        address trader = new TokenTrader (
                     _asset,
                     _sellPrice,
                     _units,
                     _sellsTokens);

        var bookid = sha3(_asset,_units);

        _verify[trader] = true; // record that this factory created the trader

        TokenTrader(trader).transferOwnership(msg.sender); // set the owner to whoever called the function

        if(pairExits[bookid] == false) {
            pairExits[bookid] = true;
            NewBook(bookid, _asset, _units);
        }

        TradeListing(bookid,msg.sender,trader);
    }

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


Add WIP functions

Add WIP functions

contract Conference {
	string public name;
	uint256 public balance;
	uint256 public deposit;
	int public capacity;
	int public registered;
	int public attended;
	mapping (address => Participant) public participants;

	struct Participant {
		address addr;
		bool attended;
	}

	event Register(uint256 value, uint256 deposit, uint256 balance);

	function Conference() {
		name = 'CodeUp';
		deposit = 1000000000000000000;		// 1 ETH = 10**18 wai
		balance = 0;
		registered = 0;
		attended = 0;
	}

	function register(){
		if (msg.value != deposit) throw;

		participants[msg.sender] = Participant(msg.sender, false);
		balance = balance + (deposit * 1);
		registered++;
		Register(msg.value, deposit, balance);
	}

	/*function attend(){
		if (isRegistered() != true) throw;

		participants[msg.sender].attended = true;
		attended++;
	}

	function isRegistered() returns (bool){
		if (participants[msg.sender] == true){
			return true;
		} else {
			return false;
		}
	}

	function isAttended() returns (bool){
		if (isRegistered() && participants[msg.sender].attended){
			return true;
		} else {
			return false;
		}
	}*/
}

contract Conference {
	string public name;
	uint256 public balance;
	uint256 public deposit;
	int public registered;
	int public attended;

	event Register(uint256 value, uint256 deposit, uint256 balance);

	function Conference() {
		name = 'CodeUp';
		// 1 ETH = 10**18 wai
		deposit = 1000000000000000000;
		balance = 0;
		registered = 0;
		attended = 0;
	}

	function register(){
		if (msg.value != deposit) throw;

		balance = balance + (deposit * 1);
		registered++;
		Register(msg.value, deposit, balance);
	}
}