Added events for the common actions that an implementation may want to watch.

// This is the main contract that governs execution of auctions
// of non-fungible on-chain assets. Any user can initiate an auction
// for an item that conforms to the Asset interface described in
// Asset.sol

import "Asset.sol";

contract AuctionHouse {

    struct Bid {
	address bidder;
	uint256 amount;
	uint timestamp;
    }

    enum AuctionStatus {Pending, Active, Inactive}

    struct Auction {
	// Location and ownership information of the item for sale
	address seller;
	address contractAddress; // Contract where the item exists
	string recordId;         // RecordID within the contract as per the Asset interface

	// Auction metadata
	string title;
	string description;      // Optionally markdown formatted?
	uint blockNumberOfDeadline;
	AuctionStatus status;

	// Distribution bonus
	uint distributionCut;    // In percent, ie 10 is a 10% cut to the distribution address
	address distributionAddress;

	// Pricing
	uint256 startingPrice;   // In wei
	uint256 reservePrice;
	uint256 currentBid;

	Bid[] bids;
    }

    Auction[] public auctions;          // All auctions
    mapping(address => uint[]) public auctionsRunByUser; // Pointer to auctions index for auctions run by this user

    mapping(address => uint[]) public auctionsBidOnByUser; // Pointer to auctions index for auctions this user has bid on

    address owner;

    // Events
    event AuctionCreated(uint id, string title, uint256 startingPrice, uint256 reservePrice);
    event AuctionActivated(uint id);
    event AuctionCancelled(uint id);
    event BidPlaced(uint auctionId, address bidder, uint256 amount);
    event AuctionEndedWithWinner(uint auctionId, address winningBidder, uint256 amount);
    event AuctionEndedWithoutWinner(uint auctionId, uint256 topBid, uint256 reservePrice);

    event LogFailure(string message);

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

    modifier onlySeller(uint auctionId) {
	if (auctions[auctionId].seller != msg.sender) throw;
	_
    }

    modifier onlyLive(uint auctionId) {
	Auction a = auctions[auctionId];
	if (a.status != AuctionStatus.Active) {
	    throw;
	}

	// Auction should not be over
	if (block.number >= a.blockNumberOfDeadline) {
	    throw;
	}
	_
    }

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

    // This is a convenience function for development, testing debugging
    // and catching throws in the tests. Can remove after getting the
    // pattern down.
    function throwTest() {
	throw;
    }

    // Create an auction, transfer the item to this contract, activate the auction
    function createAuction(
	string _title,
	string _description,
	address _contractAddressOfAsset,
	string _recordIdOfAsset,
	uint _deadline,   // in blocknumber
	uint256 _startingPrice,
	uint256 _reservePrice,
	uint _distributionCut,
	address _distributionCutAddress) returns (uint auctionId) {

	    // Check to see if the seller owns the asset at the contract
	    if (!partyOwnsAsset(msg.sender, _contractAddressOfAsset, _recordIdOfAsset)) {
		throw;
	    }

	    // Check to see if the auction deadline is in the future
	    if (block.number >= _deadline) {
		throw;
	    }

	    // Price validations
	    if (_startingPrice < 0 || _reservePrice < 0) {
		throw;
	    }

	    // Distribution validations
	    if (_distributionCut < 0 || _distributionCut > 100) {
		throw;
	    }

	    auctionId = auctions.length++;
	    Auction a = auctions[auctionId];
	    a.seller = msg.sender;
	    a.contractAddress = _contractAddressOfAsset;
	    a.recordId = _recordIdOfAsset;
	    a.title = _title;
	    a.description = _description;
	    a.blockNumberOfDeadline = _deadline;
	    a.status = AuctionStatus.Pending;
	    a.distributionCut = _distributionCut;
	    a.distributionAddress = _distributionCutAddress;
	    a.startingPrice = _startingPrice;
	    a.reservePrice = _reservePrice;
	    a.currentBid = 0;

            auctionsRunByUser[a.seller].push(auctionId);
	    AuctionCreated(auctionId, a.title, a.startingPrice, a.reservePrice);

	    return auctionId;
	}

    function partyOwnsAsset(address _party, address _contract, string _recordId) returns (bool success) {
	Asset assetContract = Asset(_contract);
	return assetContract.owner(_recordId) == _party;
    }

    /**
     * The auction fields are indexed in the return val as follows
     * [0]  -> Auction.seller
     * [1]  -> Auction.contractAddress
     * [2]  -> Auction.recordId
     * [3]  -> Auction.title
     * [4]  -> Auction.description
     * [5]  -> Auction.blockNumberOfDeadline
     * [6]  -> Auction.distributionCut
     * [7]  -> Auction.distributionAddress
     * [8]  -> Auction.startingPrice
     * [9] -> Auction.reservePrice
     * [10] -> Auction.currentBid
     * [11] -> Auction.bids.length
     * []  -> Auction.status (Not included right now)
     */
    function getAuction(uint idx) returns (address, address, string, string, string, uint, uint, address, uint256, uint256, uint256, uint) {
	Auction a = auctions[idx];
	return (a.seller,
		a.contractAddress,
		a.recordId,
		a.title,
		a.description,
		a.blockNumberOfDeadline,
		a.distributionCut,
		a.distributionAddress,
		a.startingPrice,
		a.reservePrice,
		a.currentBid,
		a.bids.length
        );
    }

    function getStatus(uint idx) returns (uint) {
	Auction a = auctions[idx];
	return uint(a.status);
    }

    function getAuctionsCountForUser(address addr) returns (uint) {
        return auctionsRunByUser[addr].length;
    }

    function getAuctionIdForUserAndIdx(address addr, uint idx) returns (uint) {
        return auctionsRunByUser[addr][idx];
    }

    // Checks if this contract address is the owner of the item for the auction
    function activateAuction(uint auctionId) onlySeller(auctionId) returns (bool){
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        a.status = AuctionStatus.Active;
	AuctionActivated(auctionId);
        return true;
    }

    function cancelAuction(uint auctionId) onlySeller(auctionId) returns (bool) {
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        Asset asset = Asset(a.contractAddress);
        asset.setOwner(a.recordId, a.seller);

	AuctionCancelled(auctionId);
        a.status = AuctionStatus.Inactive;
	return true;
    }

    /* BIDS */
    function getBidCountForAuction(uint auctionId) returns (uint) {
	Auction a = auctions[auctionId];
	return a.bids.length;
    }

    function getBidForAuctionByIdx(uint auctionId, uint idx) returns (address bidder, uint256 amount, uint timestamp) {
	Auction a = auctions[auctionId];
	if(idx > a.bids.length - 1) {
	    throw;
	}

	Bid b = a.bids[idx];
	return (b.bidder, b.amount, b.timestamp);
    }

    function placeBid(uint auctionId) onlyLive(auctionId) returns (bool success) {
	uint256 amount = msg.value;
	Auction a = auctions[auctionId];

	if (a.currentBid >= amount) {
	    // Want to return the bid amount and return false
	    if(!msg.sender.send(amount)) {
		LogFailure("Could not return the invalid bid amount to the bidder");
	    }
	    return false;
	}

	uint bidIdx = a.bids.length++;
	Bid b = a.bids[bidIdx];
	b.bidder = msg.sender;
	b.amount = amount;
	b.timestamp = now;
	a.currentBid = amount;

	auctionsBidOnByUser[b.bidder].push(auctionId);

	// Return ETH to previous bidder
	if (bidIdx > 0) {
	    Bid previousBid = a.bids[bidIdx - 1];
	    if (!previousBid.bidder.send(previousBid.amount)) {
		LogFailure("Could not return the outbid amount to the previous bidder");
	    }
	}

	BidPlaced(auctionId, b.bidder, b.amount);
	return true;
    }

    function endAuction(uint auctionId) returns (bool success) {
	// Check if the auction is passed the end date
	Auction a = auctions[auctionId];
	if (block.number < a.blockNumberOfDeadline) {
	    LogFailure("Can not end an auction that hasn't hit the deadline yet");
	    return false;
	}

	// No bids, make the auction inactive
	if (a.bids.length == 0) {
	    a.status = AuctionStatus.Inactive;
	    return true;
	}

	Bid topBid = a.bids[a.bids.length - 1];
	Asset asset = Asset(a.contractAddress);

	// If the auction hit its reserve price
	if (a.currentBid >= a.reservePrice) {
	    uint distributionShare = a.currentBid * a.distributionCut / 100;  // Calculate the distribution cut
	    uint sellerShare = a.currentBid - distributionShare;

	    asset.setOwner(a.recordId, topBid.bidder);  // Set the items new owner

	    if (!a.distributionAddress.send(distributionShare)) { LogFailure("Couldn't send the marketing distribution"); }
	    if (!a.seller.send(sellerShare)) { LogFailure("Couldn't send the seller his cut"); }

	    AuctionEndedWithWinner(auctionId, topBid.bidder, a.currentBid);
	} else {
	    // Return the item to the owner and the money to the top bidder
	    asset.setOwner(a.recordId, a.seller);
	    if (!topBid.bidder.send(a.currentBid)) { LogFailure("Couldn't send the top bidder his money back on a failed to meet reserve scenario."); }

	    AuctionEndedWithoutWinner(auctionId, a.currentBid, a.reservePrice);
	}

	a.status = AuctionStatus.Inactive;
	return true;
    }

    function() {
	// Don't allow ether to be sent blindly to this contract
	throw;
    }
}

// This is the main contract that governs execution of auctions
// of non-fungible on-chain assets. Any user can initiate an auction
// for an item that conforms to the Asset interface described in
// Asset.sol

import "Asset.sol";

contract AuctionHouse {

    struct Bid {
	address bidder;
	uint256 amount;
	uint timestamp;
    }

    enum AuctionStatus {Pending, Active, Inactive}

    struct Auction {
	// Location and ownership information of the item for sale
	address seller;
	address contractAddress; // Contract where the item exists
	string recordId;         // RecordID within the contract as per the Asset interface

	// Auction metadata
	string title;
	string description;      // Optionally markdown formatted?
	uint blockNumberOfDeadline;
	AuctionStatus status;

	// Distribution bonus
	uint distributionCut;    // In percent, ie 10 is a 10% cut to the distribution address
	address distributionAddress;

	// Pricing
	uint256 startingPrice;   // In wei
	uint256 reservePrice;
	uint256 currentBid;

	Bid[] bids;
    }

    Auction[] public auctions;          // All auctions
    mapping(address => uint[]) public auctionsRunByUser; // Pointer to auctions index for auctions run by this user

    mapping(address => uint[]) public auctionsBidOnByUser; // Pointer to auctions index for auctions this user has bid on

    address owner;

    // Events
    event AuctionCreated(uint id, string title, uint256 startingPrice, uint256 reservePrice);
    event BidPlaced(uint auctionId, address bidder, uint256 amount);
    event AuctionEnded(uint auctionId, address winningBidder, uint256 amount);

    event LogFailure(string message);

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

    modifier onlySeller(uint auctionId) {
	if (auctions[auctionId].seller != msg.sender) throw;
	_
    }

    modifier onlyLive(uint auctionId) {
	Auction a = auctions[auctionId];
	if (a.status != AuctionStatus.Active) {
	    throw;
	}

	// Auction should not be over
	if (block.number >= a.blockNumberOfDeadline) {
	    throw;
	}
	_
    }

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

    // This is a convenience function for development, testing debugging
    // and catching throws in the tests. Can remove after getting the
    // pattern down.
    function throwTest() {
	throw;
    }

    // Create an auction, transfer the item to this contract, activate the auction
    function createAuction(
	string _title,
	string _description,
	address _contractAddressOfAsset,
	string _recordIdOfAsset,
	uint _deadline,   // in blocknumber
	uint256 _startingPrice,
	uint256 _reservePrice,
	uint _distributionCut,
	address _distributionCutAddress) returns (uint auctionId) {

	    // Check to see if the seller owns the asset at the contract
	    if (!partyOwnsAsset(msg.sender, _contractAddressOfAsset, _recordIdOfAsset)) {
		throw;
	    }

	    // Check to see if the auction deadline is in the future
	    if (block.number >= _deadline) {
		throw;
	    }

	    // Price validations
	    if (_startingPrice < 0 || _reservePrice < 0) {
		throw;
	    }

	    // Distribution validations
	    if (_distributionCut < 0 || _distributionCut > 100) {
		throw;
	    }

	    auctionId = auctions.length++;
	    Auction a = auctions[auctionId];
	    a.seller = msg.sender;
	    a.contractAddress = _contractAddressOfAsset;
	    a.recordId = _recordIdOfAsset;
	    a.title = _title;
	    a.description = _description;
	    a.blockNumberOfDeadline = _deadline;
	    a.status = AuctionStatus.Pending;
	    a.distributionCut = _distributionCut;
	    a.distributionAddress = _distributionCutAddress;
	    a.startingPrice = _startingPrice;
	    a.reservePrice = _reservePrice;
	    a.currentBid = 0;

            auctionsRunByUser[a.seller].push(auctionId);

	    return auctionId;
	}

    function partyOwnsAsset(address _party, address _contract, string _recordId) returns (bool success) {
	Asset assetContract = Asset(_contract);
	return assetContract.owner(_recordId) == _party;
    }

    /**
     * The auction fields are indexed in the return val as follows
     * [0]  -> Auction.seller
     * [1]  -> Auction.contractAddress
     * [2]  -> Auction.recordId
     * [3]  -> Auction.title
     * [4]  -> Auction.description
     * [5]  -> Auction.blockNumberOfDeadline
     * [6]  -> Auction.distributionCut
     * [7]  -> Auction.distributionAddress
     * [8]  -> Auction.startingPrice
     * [9] -> Auction.reservePrice
     * [10] -> Auction.currentBid
     * [11] -> Auction.bids.length
     * []  -> Auction.status (Not included right now)
     */
    function getAuction(uint idx) returns (address, address, string, string, string, uint, uint, address, uint256, uint256, uint256, uint) {
	Auction a = auctions[idx];
	return (a.seller,
		a.contractAddress,
		a.recordId,
		a.title,
		a.description,
		a.blockNumberOfDeadline,
		a.distributionCut,
		a.distributionAddress,
		a.startingPrice,
		a.reservePrice,
		a.currentBid,
		a.bids.length
        );
    }

    function getStatus(uint idx) returns (uint) {
	Auction a = auctions[idx];
	return uint(a.status);
    }

    function getAuctionsCountForUser(address addr) returns (uint) {
        return auctionsRunByUser[addr].length;
    }

    function getAuctionIdForUserAndIdx(address addr, uint idx) returns (uint) {
        return auctionsRunByUser[addr][idx];
    }

    // Checks if this contract address is the owner of the item for the auction
    function activateAuction(uint auctionId) onlySeller(auctionId) returns (bool){
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        a.status = AuctionStatus.Active;
        return true;
    }

    function cancelAuction(uint auctionId) onlySeller(auctionId) returns (bool) {
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        Asset asset = Asset(a.contractAddress);
        asset.setOwner(a.recordId, a.seller);

        a.status = AuctionStatus.Inactive;
    }

    /* BIDS */
    function getBidCountForAuction(uint auctionId) returns (uint) {
	Auction a = auctions[auctionId];
	return a.bids.length;
    }

    function getBidForAuctionByIdx(uint auctionId, uint idx) returns (address bidder, uint256 amount, uint timestamp) {
	Auction a = auctions[auctionId];
	if(idx > a.bids.length - 1) {
	    throw;
	}

	Bid b = a.bids[idx];
	return (b.bidder, b.amount, b.timestamp);
    }

    function placeBid(uint auctionId) onlyLive(auctionId) returns (bool success) {
	uint256 amount = msg.value;
	Auction a = auctions[auctionId];

	if (a.currentBid >= amount) {
	    // Want to return the bid amount and return false
	    if(!msg.sender.send(amount)) {
		LogFailure("Could not return the invalid bid amount to the bidder");
	    }
	    return false;
	}

	uint bidIdx = a.bids.length++;
	Bid b = a.bids[bidIdx];
	b.bidder = msg.sender;
	b.amount = amount;
	b.timestamp = now;
	a.currentBid = amount;

	auctionsBidOnByUser[b.bidder].push(auctionId);

	// Return ETH to previous bidder
	if (bidIdx > 0) {
	    Bid previousBid = a.bids[bidIdx - 1];
	    if (!previousBid.bidder.send(previousBid.amount)) {
		LogFailure("Could not return the outbid amount to the previous bidder");
	    }
	}
    }

    function endAuction(uint auctionId) returns (bool success) {
	// Check if the auction is passed the end date
	Auction a = auctions[auctionId];
	if (block.number < a.blockNumberOfDeadline) {
	    LogFailure("Can not end an auction that hasn't hit the deadline yet");
	    return false;
	}

	// No bids, make the auction inactive
	if (a.bids.length == 0) {
	    a.status = AuctionStatus.Inactive;
	    return true;
	}

	// If the auction hit its reserve price
	Bid topBid = a.bids[a.bids.length - 1];
	Asset asset = Asset(a.contractAddress);

	if (a.currentBid >= a.reservePrice) {
	    uint distributionShare = a.currentBid * a.distributionCut / 100;  // Calculate the distribution cut
	    uint sellerShare = a.currentBid - distributionShare;

	    asset.setOwner(a.recordId, topBid.bidder);  // Set the items new owner

	    if (!a.distributionAddress.send(distributionShare)) { LogFailure("Couldn't send the marketing distribution"); }
	    if (!a.seller.send(sellerShare)) { LogFailure("Couldn't send the seller his cut"); }
	} else {
	    // Return the item to the owner and the money to the top bidder
	    asset.setOwner(a.recordId, a.seller);
	    if (!topBid.bidder.send(a.currentBid)) { LogFailure("Couldn't send the top bidder his money back on a failed to meet reserve scenario."); }
	}

	a.status = AuctionStatus.Inactive;
	return true;
    }

    function() {
	// Don't allow ether to be sent blindly to this contract
	throw;
    }
}


Add implemented contract

Add implemented contract

pragma solidity ^0.4.15;

import "./AbstractEthDemocracy.sol";

contract EthDemocracy is AbstractEthDemocracy {

    /**
     * Get the number of registered voters
     */
    function getVotersLength() constant returns (uint) {
        return voters.length;
    }

    /**
     * Get the election ID for a given name
     */
    function getElectionId(string _electionName) constant returns (uint) {
        for (uint i=0; i<elections.length; i++) {
            if (sha3(_electionName) == sha3(elections[i].name)) {
                return i;
            }
        }
        revert();
    }

    /**
     * Get the name of an election
     */
    function getElectionName(uint _electionId) constant returns (string) {
        require(_electionId < elections.length);
        return elections[_electionId].name;
    }

    /**
     * Test if an address is a registered voter
     */
    function isVoter(address _voter) constant returns (bool) {
        for (uint i=0; i<voters.length; i++) {
            if (_voter == voters[i]) {
                return true;
            }
        }
        return false;
    }

    /**
     * Get the name of a vote option for a given election ID and option ID
     */
    function getVoteOption(uint _electionId, uint _optionId) constant returns (string) {
        require (_electionId < elections.length);
        require (_optionId < elections[_electionId].options.length);

        return elections[_electionId].options[_optionId];
    }

    /**
     * Get the ID of a vote option for a given election and an option's name
     */
    function getVoteOptionId(uint _electionId, string _option) constant returns (uint) {
        require(_electionId < elections.length);
        var hash = sha3(_option);
        for (uint i=0; i<elections[_electionId].options.length; i++) {
            if (hash == sha3(elections[_electionId].options[i])) {
                return i;
            }
        }
        revert();
        //revert('Not a valid option');
    }

    /**
     * Get number of choices for a given election
     */
    function getVoteOptions(uint _electionId) constant returns (uint) {
        require(_electionId < elections.length);
        return elections[_electionId].options.length;
    }

    /**
     * Get the number of votes that an address can still cast for a given election
     */
    function getVotes(uint _electionId, address _voter) constant returns (uint) {
        require(_electionId < elections.length);
        return elections[_electionId].balance[_voter];
    }

    /**
     * Get the number of votes for a particular choice in a particular election
     */
    function getResults(uint _electionId, string _option) constant returns (uint) {
        require(_electionId < elections.length);
        return elections[_electionId].votes[_option];
    }

    /**
     * Add an address to the registered voters list
     */
    function addVoter(address _voter) returns (bool) {
        if (isVoter(_voter)) { return false; }

        voters.push(_voter);
        VoterAdded(_voter);
        return true;
    }

    /**
     * Clear the list of registered voters
     */
    function deleteVoters() returns (bool) {
        voters.length = 0;
        VotersDeleted('All voters have been deleted');
        return true;
    }

    /**
     * Create a new election and distribute one vote to each registered voter. After calling this, the
     * choices still have to be set via `addVoteOption()`
     */
    function createElection(string _name) returns (bool success, uint electionId) {
        string[] memory emptyOptions;
        electionId = elections.length;

        elections.push(Election(electionId, _name, emptyOptions));
        for (uint i=0; i<voters.length; i++) {
            elections[elections.length-1].balance[voters[i]] = 1;
        }
        ElectionCreated(elections.length - 1);
        success = true;
    }

    /**
     * Add a single choice to an election. W/o calling this at least twice, the election is meaningless.
     */
    function addVoteOption(uint _electionId, string _option) returns (bool) {
        require(_electionId < elections.length);
        bytes32 sha3Option = sha3(_option);

        for(uint i=0; i<elections[_electionId].options.length; i++) {
            if (sha3(elections[_electionId].options[i]) == sha3Option) {
                return false;
            }
        }
        elections[_electionId].options.push(_option);
        VoteOptionAdded(_electionId, _option);
        return true;
    }

    /**
     * Vote with all available tokens for a choice
     */
    function castVote(uint _electionId, uint _optionId) returns (bool) {
        require (_electionId < elections.length);
        require (_optionId < elections[_electionId].options.length);
        require (getVotes(_electionId, msg.sender) > 0);

        uint voteWeight = elections[_electionId].balance[msg.sender];
        string memory choice = elections[_electionId].options[_optionId];
        elections[_electionId].balance[msg.sender] = 0;
        elections[_electionId].votes[choice] += voteWeight;
        VoteCast(msg.sender, _electionId, choice);

        return true;
    }

    /**
     * Transfer your votes to another address. The address must be a registered voter
     */
    function transferVotes(uint _electionId, address _to) returns (bool) {
        require(_electionId < elections.length);
        require(isVoter(_to));

        var amount = getVotes(_electionId, msg.sender);

        elections[_electionId].balance[msg.sender] -= amount;
        elections[_electionId].balance[_to] += amount;
        VoteTransferred(msg.sender, _to, amount);
        return true;
    }

}

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


add test sources

add test sources

pragma solidity >=0.4.0 <0.7.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}

error: pathspec 'packages/truffle-workflow-compile/test/sources/SimpleStorage.sol' did not match any file(s) known to git


access factory

access factory

contract Factory {

    event created(address addr);

    address[] parties;

    mapping(address => address) walletAccess;

    function getParties() constant returns (address[]){
        return parties;
    }

    function createParty() returns (address addr){
        var party = new Party();
        parties.push(party);
        created(party);
        return party;
    }

    function createPasswordChallenge(bytes20 response, bytes32 salt) returns (address addr){
        var challenge = new PasswordChallenge(response, salt);
        created(challenge);
        return challenge;
    }

    function getAccess() constant returns(address access){
        var wallet = msg.sender;
        return walletAccess[wallet];
    }

    function createAccess() returns(address addr){
        var wallet = msg.sender;
        var access = new Access();
        created(access);
        walletAccess[wallet] = access;
        return access;
    }

}

contract Factory {

    event created(address addr);

    address[] parties;

    function getParties() constant returns (address[]){
        return parties;
    }

    function createParty() returns (address addr){
        var party = new Party();
        parties.push(party);
        created(party);
        return party;
    }

    function createPasswordChallenge(bytes20 response, bytes32 salt) returns (address addr){
        var challenge = new PasswordChallenge(response, salt);
        created(challenge);
        return challenge;
    }

}


Add events for UnanimousConsent

Add events for UnanimousConsent

/**
 * This contract performs an "eval" on arbitrary contracts but only with the
 * consent of all participants named.
 */
contract UnanimousConsent {

	event ActionAdded(bytes32 indexed _hash, address _target, bytes4 _methodSignature, bytes32[] _calldata);
	event Evaluated(bytes32[] _actionHashes);
	event Consented(bytes32[] _hashes);
	event ParticipantsChanged(address[] _participants);
	event ActionsCleaned(bytes32[] _actionHashes);
	event ConsentsCleaned(bytes32[] _hashes, address[] _participants);

	enum ConsentState {
		NONE,
		CONSENTED,
		EXECUTED
	}

	struct Action {
		address target;
		bytes4 methodSignature;
		bytes32[] calldata;
	}

	// Records the current state of consent for a given hash and address
	mapping (bytes32 =>
			mapping (address => ConsentState)) consentStates;

	// Contains all of the sent execution actions
	mapping (bytes32 => Action) actions;

	// Holds all of the participants in the current UnanimousConsent contract
	address[] participants;

	modifier onlySelf {
		if (msg.sender == address(this)) {
			_
		} else {
			throw;
		}
	}

	/**
	 * Creates a new UnanimousConsent contract.
	 *
	 * _participants: The initial participants in the contract
	 */
	function UnanimousConsent(address[] _participants) {
		participants = _participants;
	}

	/**
	 * Adds an `Action` to potentially be executed.
	 *
	 * _target: The target of the execution call
	 * _calldata: The calldata associated with the call
	 */
	function addAction(address _target, bytes4 _methodSignature, bytes32[] _calldata) external {
		Action memory action = Action(_target, _methodSignature, _calldata);
		bytes32 hash = sha3(_target, _methodSignature, _calldata);
		actions[hash] = action;
		ActionAdded(hash, _target, _methodSignature, _calldata);
	}

	/**
	 * Evaluates arbitrary functions of contracts, but only with universal
	 * consent. Note that any `eval` sub-calls should `throw` in the event that
	 * there is a contract execution failure (such as if a precondition isn't
	 * met or if a verification of some sort fails) to prevent this call from
	 * finishing.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function eval(bytes32[] _actionHashes) {
		uint i;
		bytes32 hash = sha3(_actionHashes);

		for (i = participants.length; i > 0; i--) {
			if (consentStates[hash][participants[i-1]] == ConsentState.CONSENTED) {
				consentStates[hash][participants[i-1]] = ConsentState.EXECUTED;
			} else {
				throw;
			}
		}

		for (i = 0; i < _actionHashes.length; i++) {
			Action memory action = actions[_actionHashes[i]];
			if (!(action.target > 0 && action.target.delegatecall(action.methodSignature, action.calldata))) {
				throw;
			}
		}
		Evaluated(_actionHashes);
	}

	/**
	 * Provides consent for the hash of an execution call for the sender of the
	 * message. Throws if unsucessful.
	 *
	 * _hashes: The hashes of the execution call
	 */
	function consent(bytes32[] _hashes) {
		for (uint i = _hashes.length; i > 0; i--) {
			if (consentStates[_hashes[i-1]][msg.sender] == ConsentState.NONE) {
				consentStates[_hashes[i-1]][msg.sender] = ConsentState.CONSENTED;
			} else {
				throw;
			}
		}
		Consented(_hashes);
	}

	/**
	 * Changes the participants in the current contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _participants: The new participants in the contract
	 */
	function changeParticipants(address[] _participants) external onlySelf {
		participants = _participants;
		ParticipantsChanged(_participants);
	}

	/**
	 * Removes a group of `Action` that have been submitted. Intended to be
	 * called by this contract's `eval`.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function cleanActions(bytes32[] _actionHashes) external onlySelf {
		for (uint i = _actionHashes.length; i > 0; i--) {
			delete actions[_actionHashes[i-1]];
		}
		ActionsCleaned(_actionHashes);
	}

	/**
	 * Cleans up previously approved consents. Intended to only be called by
	 * this contract's `eval`.
	 *
	 * _hashes: The list of hashes to clean
	 * _participants: The list of address whose hashes should be cleaned
	 */
	function cleanConsents(bytes32[] _hashes, address[] _participants) external onlySelf {
		for (uint i = _hashes.length; i > 0; i--) {
			for (uint j = _participants.length; j > 0; j--) {
				delete consentStates[_hashes[i-1]][_participants[j-1]];
			}
		}
		ConsentsCleaned(_hashes, _participants);
	}

	/**
	 * Kills the current contract. Intended to only be called by this contract's
	 * eval.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlySelf {
		selfdestruct(_recipient);
	}
}

/**
 * This contract performs an "eval" on arbitrary contracts but only with the
 * consent of all participants named.
 */
contract UnanimousConsent {

	enum ConsentState {
		NONE,
		CONSENTED,
		EXECUTED
	}

	struct Action {
		address target;
		bytes4 methodSignature;
		bytes32[] calldata;
	}

	// Records the current state of consent for a given hash and address
	mapping (bytes32 =>
			mapping (address => ConsentState)) consentStates;

	// Contains all of the sent execution actions
	mapping (bytes32 => Action) actions;

	// Holds all of the participants in the current UnanimousConsent contract
	address[] participants;

	modifier onlySelf {
		if (msg.sender == address(this)) {
			_
		} else {
			throw;
		}
	}

	/**
	 * Creates a new UnanimousConsent contract.
	 *
	 * _participants: The initial participants in the contract
	 */
	function UnanimousConsent(address[] _participants) {
		participants = _participants;
	}

	/**
	 * Adds an `Action` to potentially be executed.
	 *
	 * _target: The target of the execution call
	 * _calldata: The calldata associated with the call
	 */
	function addAction(address _target, bytes4 _methodSignature, bytes32[] _calldata) external {
		Action memory action = Action(_target, _methodSignature, _calldata);
		actions[sha3(_target, _methodSignature, _calldata)] = action;
	}

	/**
	 * Evaluates arbitrary functions of contracts, but only with universal
	 * consent. Note that any `eval` sub-calls should `throw` in the event that
	 * there is a contract execution failure (such as if a precondition isn't
	 * met or if a verification of some sort fails) to prevent this call from
	 * finishing.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function eval(bytes32[] _actionHashes) {
		uint i;
		bytes32 hash = sha3(_actionHashes);

		for (i = participants.length; i > 0; i--) {
			if (consentStates[hash][participants[i-1]] == ConsentState.CONSENTED) {
				consentStates[hash][participants[i-1]] = ConsentState.EXECUTED;
			} else {
				throw;
			}
		}

		for (i = 0; i < _actionHashes.length; i++) {
			Action memory action = actions[_actionHashes[i]];
			if (!(action.target > 0 && action.target.delegatecall(action.methodSignature, action.calldata))) {
				throw;
			}
		}
	}

	/**
	 * Provides consent for the hash of an execution call for the sender of the
	 * message. Throws if unsucessful.
	 *
	 * _hashes: The hashes of the execution call
	 */
	function consent(bytes32[] _hashes) {
		for (uint i = _hashes.length; i > 0; i--) {
			if (consentStates[_hashes[i-1]][msg.sender] == ConsentState.NONE) {
				consentStates[_hashes[i-1]][msg.sender] = ConsentState.CONSENTED;
			} else {
				throw;
			}
		}
	}

	/**
	 * Changes the participants in the current contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _participants: The new participants in the contract
	 */
	function changeParticipants(address[] _participants) external onlySelf {
		participants = _participants;
	}

	/**
	 * Removes a group of `Action` that have been submitted. Intended to be
	 * called by this contract's `eval`.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function cleanActions(bytes32[] _actionHashes) external onlySelf {
		for (uint i = _actionHashes.length; i > 0; i--) {
			delete actions[_actionHashes[i-1]];
		}
	}

	/**
	 * Cleans up previously approved consents. Intended to only be called by
	 * this contract's `eval`.
	 *
	 * _hashes: The list of hashes to clean
	 * _participants: The list of address whose hashes should be cleaned
	 */
	function cleanConsents(bytes32[] _hashes, address[] _participants) external onlySelf {
		for (uint i = _hashes.length; i > 0; i--) {
			for (uint j = _participants.length; j > 0; j--) {
				delete consentStates[_hashes[i-1]][_participants[j-1]];
			}
		}
	}

	/**
	 * Kills the current contract. Intended to only be called by this contract's
	 * eval.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlySelf {
		selfdestruct(_recipient);
	}
}


Rename variable master to implementation #2 (#2553)

(cherry picked from commit 103ff8e23d661972711245f814026b8812762f11)

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../proxy/Clones.sol";
import "../utils/Address.sol";

contract ClonesMock {
    using Address for address;
    using Clones for address;

    event NewInstance(address instance);

    function clone(address implementation, bytes calldata initdata) public payable {
        _initAndEmit(implementation.clone(), initdata);
    }

    function cloneDeterministic(address implementation, bytes32 salt, bytes calldata initdata) public payable {
        _initAndEmit(implementation.cloneDeterministic(salt), initdata);
    }

    function predictDeterministicAddress(address implementation, bytes32 salt) public view returns (address predicted) {
        return implementation.predictDeterministicAddress(salt);
    }

    function _initAndEmit(address instance, bytes memory initdata) private {
        if (initdata.length > 0) {
            instance.functionCallWithValue(initdata, msg.value);
        }
        emit NewInstance(instance);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../proxy/Clones.sol";
import "../utils/Address.sol";

contract ClonesMock {
    using Address for address;
    using Clones for address;

    event NewInstance(address instance);

    function clone(address master, bytes calldata initdata) public payable {
        _initAndEmit(master.clone(), initdata);
    }

    function cloneDeterministic(address master, bytes32 salt, bytes calldata initdata) public payable {
        _initAndEmit(master.cloneDeterministic(salt), initdata);
    }

    function predictDeterministicAddress(address master, bytes32 salt) public view returns (address predicted) {
        return master.predictDeterministicAddress(salt);
    }

    function _initAndEmit(address instance, bytes memory initdata) private {
        if (initdata.length > 0) {
            instance.functionCallWithValue(initdata, msg.value);
        }
        emit NewInstance(instance);
    }
}


updated docstrings on nettingchannelcontract

pragma solidity ^0.4.0;

import "./NettingChannelLibrary.sol";

contract NettingChannelContract {
    using NettingChannelLibrary for NettingChannelLibrary.Data;
    NettingChannelLibrary.Data public data;

    event ChannelNewBalance(address token_address, address participant, uint balance, uint block_number);
    event ChannelClosed(address closing_address, uint block_number);
    event TransferUpdated(address node_address, uint block_number);
    event ChannelSettled(uint block_number);
    event ChannelSecretRevealed(bytes32 secret);

    modifier settleTimeoutNotTooLow(uint t) {
        if (t < 6) throw;
        _;
    }

    function NettingChannelContract(
        address token_address,
        address participant1,
        address participant2,
        uint timeout)
        settleTimeoutNotTooLow(timeout)
    {
        if (participant1 == participant2) {
            throw;
        }

        data.participants[0].node_address = participant1;
        data.participants[1].node_address = participant2;

        data.token = Token(token_address);
        data.settle_timeout = timeout;
    }

    /// @notice Caller makes a deposit into their channel balance.
    /// @param amount The amount caller wants to deposit.
    /// @return True if deposit is successful.
    function deposit(uint256 amount) returns (bool) {
        bool success;
        uint256 balance;

        (success, balance) = data.deposit(msg.sender, this, amount);

        if (success == true) {
            ChannelNewBalance(data.token, msg.sender, balance, data.opened);
        }

        return success;
    }

    /// @notice Get the address of the channel partner.
    /// @param one_address The address of partner 1.
    /// @return The address of partner 2.
    function partner(address one_address) constant returns (address) {
        return data.partner(one_address);
    }

    /// @notice Get the address and balance of both partners in a channel.
    /// @return The address and balance pairs.
    function addressAndBalance()
        constant
        returns (
        address participant1,
        uint balance1,
        address participant2,
        uint balance2)
    {
        return data.addressAndBalance();
    }

    /// @notice Get the amount one partner has sent to the other partner.
    /// @param participant The address of one partner.
    /// @return The amount one partner has sent to the other.
    function transferredAmount(address participant) constant returns (uint) {
        return data.transferredAmount(participant);
    }

    /// @notice Close the channel. Can only be called by a participant in the channel.
    /// @param theirs_encoded The state of the partner's transfers.
    /// @param ours_encoded The state of the caller's transfers.
    function close(bytes theirs_encoded, bytes ours_encoded) {
        data.close(msg.sender, theirs_encoded, ours_encoded);
        ChannelClosed(msg.sender, data.closed);
    }

    /// @notice Dispute the state after closing, called by a counterparty (the
    ///         participant who did not close the channel).
    /// @param theirs_encoded The transfer the counterparty believes is the valid
    ///                       state of the first participant.
    function updateTransfer(bytes theirs_encoded) {
        data.updateTransfer(msg.sender, theirs_encoded);
        TransferUpdated(msg.sender, block.number);
    }

    /// @notice Unlock a locked transfer.
    function unlock(bytes locked_encoded, bytes merkle_proof, bytes32 secret) {
        data.unlock(msg.sender, locked_encoded, merkle_proof, secret);
        ChannelSecretRevealed(secret);
    }

    /// @notice Settle the transfers and balances of the channel and pay out to
    ///         each participant. Must be called by a participating address.
    function settle() {
        data.settle(msg.sender);
        ChannelSettled(data.settled);
    }

    /// @notice Returns the number of blocks until the settlement timeout.
    function settleTimeout() constant returns (uint) {
        return data.settle_timeout;
    }

    /// @notice Returns the address of the token.
    function tokenAddress() constant returns (address) {
        return data.token;
    }

    /// @notice Returns the block number for when the channel was opened.
    function opened() constant returns (uint) {
        return data.opened;
    }

    /// @notice Returns the block number for when the channel was closed.
    function closed() constant returns (uint) {
        return data.closed;
    }

    /// @notice Returns the block number for when the channel was settled.
    function settled() constant returns (uint) {
        return data.settled;
    }

    /// @notice Returns the address of the closing participant.
    function closingAddress() constant returns (address) {
        return data.closing_address;
    }

    /// @notice All other attempted functions are thrown. (Wasted gas.)
    function () { throw; }
}

pragma solidity ^0.4.0;

import "./NettingChannelLibrary.sol";

contract NettingChannelContract {
    using NettingChannelLibrary for NettingChannelLibrary.Data;
    NettingChannelLibrary.Data public data;

    event ChannelNewBalance(address asset_address, address participant, uint balance, uint block_number);
    event ChannelClosed(address closing_address, uint block_number);
    event TransferUpdated(address node_address, uint block_number);
    event ChannelSettled(uint block_number);
    event ChannelSecretRevealed(bytes32 secret);

    modifier settleTimeoutNotTooLow(uint t) {
        if (t < 6) throw;
        _;
    }

    function NettingChannelContract(
        address asset_address,
        address participant1,
        address participant2,
        uint timeout)
        settleTimeoutNotTooLow(timeout)
    {
        if (participant1 == participant2) {
            throw;
        }

        data.participants[0].node_address = participant1;
        data.participants[1].node_address = participant2;

        data.token = Token(asset_address);
        data.settle_timeout = timeout;
    }

    /// @notice Caller makes a deposit into their channel balance.
    /// @param amount The amount caller wants to deposit.
    /// @return True if deposit is successful.
    function deposit(uint256 amount) returns (bool) {
        bool success;
        uint256 balance;

        (success, balance) = data.deposit(msg.sender, this, amount);

        if (success == true) {
            ChannelNewBalance(data.token, msg.sender, balance, data.opened);
        }

        return success;
    }

    /// @notice Get the address of the channel partner.
    /// @param one_address The address of partner 1.
    /// @return The address of partner 2.
    function partner(address one_address) constant returns (address) {
        return data.partner(one_address);
    }

    /// @notice Get the address and balance of both partners in a channel.
    /// @return The address and balance pairs.
    function addressAndBalance()
        constant
        returns (
        address participant1,
        uint balance1,
        address participant2,
        uint balance2)
    {
        return data.addressAndBalance();
    }

    /// @notice Get the amount one partner has sent to the other partner.
    /// @param participant The address of one partner.
    /// @return The amount one partner has sent to the other.
    function transferredAmount(address participant) constant returns (uint) {
        return data.transferredAmount(participant);
    }

    /// @notice Close the channel. Can only be called by a participant in the channel.
    /// @param theirs_encoded The state of the partner's transfers.
    /// @param ours_encoded The state of the caller's transfers.
    function close(bytes theirs_encoded, bytes ours_encoded) {
        data.close(msg.sender, theirs_encoded, ours_encoded);
        ChannelClosed(msg.sender, data.closed);
    }

    /// @notice Dispute the state after closing, called by a counterparty (the
    ///         participant who did not close the channel).
    /// @param theirs_encoded The transfer the counterparty believes is the valid
    ///                       state of the first participant.
    function updateTransfer(bytes theirs_encoded) {
        data.updateTransfer(msg.sender, theirs_encoded);
        TransferUpdated(msg.sender, block.number);
    }

    /// @notice Unlock a locked transfer.
    function unlock(bytes locked_encoded, bytes merkle_proof, bytes32 secret) {
        data.unlock(msg.sender, locked_encoded, merkle_proof, secret);
        ChannelSecretRevealed(secret);
    }

    /// @notice Settle the transfers and balances of the channel and pay out to
    ///         each participant. Must be called by a participating address.
    function settle() {
        data.settle(msg.sender);
        ChannelSettled(data.settled);
    }

    /// @notice Returns the number of blocks until the settlement timeout.
    function settleTimeout() constant returns (uint) {
        return data.settle_timeout;
    }

    /// @notice Returns the address of the asset/token.
    function assetAddress() constant returns (address) {
        return data.token;
    }

    /// @notice Returns the block number for when the channel was opened.
    function opened() constant returns (uint) {
        return data.opened;
    }

    /// @notice Returns the block number for when the channel was closed.
    function closed() constant returns (uint) {
        return data.closed;
    }

    /// @notice Returns the block number for when the channel was settled.
    function settled() constant returns (uint) {
        return data.settled;
    }

    /// @notice Returns the address of the closing participant.
    function closingAddress() constant returns (address) {
        return data.closing_address;
    }

    /// @notice All other attempted functions are thrown. (Wasted gas.)
    function () { throw; }
}


Bump required compiler version for Address (#1898)

(cherry picked from commit 4e527a20a5f2ef75f63bfae9eb323c8c2b75ec0d)

pragma solidity ^0.5.5;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * This test is non-exhaustive, and there may be false-negatives: during the
     * execution of a contract's constructor, its address will be reported as
     * not containing a contract.
     *
     * IMPORTANT: It is unsafe to assume that an address for which this
     * function returns false is an externally-owned account (EOA) and not a
     * contract.
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies in extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != 0x0 && codehash != accountHash);
    }

    /**
     * @dev Converts an `address` into `address payable`. Note that this is
     * simply a type cast: the actual underlying value is not changed.
     *
     * NOTE: This is a feature of the next version of OpenZeppelin Contracts.
     * @dev Get it via `npm install @openzeppelin/contracts@next`.
     */
    function toPayable(address account) internal pure returns (address payable) {
        return address(uint160(account));
    }
}

pragma solidity ^0.5.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * This test is non-exhaustive, and there may be false-negatives: during the
     * execution of a contract's constructor, its address will be reported as
     * not containing a contract.
     *
     * IMPORTANT: It is unsafe to assume that an address for which this
     * function returns false is an externally-owned account (EOA) and not a
     * contract.
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies in extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != 0x0 && codehash != accountHash);
    }

    /**
     * @dev Converts an `address` into `address payable`. Note that this is
     * simply a type cast: the actual underlying value is not changed.
     *
     * NOTE: This is a feature of the next version of OpenZeppelin Contracts.
     * @dev Get it via `npm install @openzeppelin/contracts@next`.
     */
    function toPayable(address account) internal pure returns (address payable) {
        return address(uint160(account));
    }
}


Dgp.sol compiled

Dgp.sol compiled

pragma solidity ^0.4.11;

contract Dgp {

    struct Client {
        uint256 startBlock;
        uint256 lastRedemptionBlock;
        uint256 checkingBalance;
        uint256 allocatedEndowments;
        uint256 endowmentTotal;
    }
    address public admin;
    uint256 public accountBalance;
    uint256 public allocated;
    uint256 public constant redemptionFrequency = 7; //7 days
    uint256 public constant redemptionAmt = 7000; //DUST (in cents)

    mapping (address => uint256) public vendorBalances;
    mapping (address => Client) public clients;
	mapping (uint256 => uint256) blockTimes;

    // events
    event Donation(uint256 _value);
    event CheckingDeposit(address indexed _to, uint256 _value);
    event Endowment(address indexed _to, uint256 _value);
    event RemoveClient(address indexed _removed, uint256 _value);
    event Purchase(address indexed _client, address indexed _vendor, uint256 _value);
    event Refund(address indexed _vendor, address _client, uint256 _value);
    event Redemption(address indexed _vendor, uint256 _value);

    //access control
	modifier onlyAdmin {
		if (msg.sender != admin)  throw;
		_;
	}
	modifier onlyClient {
		if (clients[msg.sender].startBlock == 0)  throw;
		_;
	}
	modifier onlyVendorWithBalance {
		if (vendorBalances[msg.sender] == 0)  throw;
		_;
	}

        // constructor
    function Dgp()
    {
      admin = msg.sender;
    }
    function registerDonation(uint256 _donationAmt) onlyAdmin() {
        accountBalance += _donationAmt;
        Donation(_donationAmt);
    }

    function registerClient(address _clientAddress, uint256 _checkingBalance,
    uint256 _endowmentTotal, uint256 _startBlock) onlyAdmin() {
        //never allocate more than account balance
        if (_checkingBalance + _endowmentTotal + allocated> accountBalance) throw;
        //TODO use safeAdd?
        allocated += _checkingBalance + _endowmentTotal;
        clients[_clientAddress].checkingBalance = _checkingBalance;
        clients[_clientAddress].endowmentTotal = _endowmentTotal;
        clients[_clientAddress].startBlock = _startBlock;
        clients[_clientAddress].lastRedemptionBlock = 0;
        if (_checkingBalance > 0) CheckingDeposit(_clientAddress, _checkingBalance);
        if (_endowmentTotal > 0) Endowment(_clientAddress, _endowmentTotal);

    }
    function depositChecking(address _clientAddress, uint256 _amount) onlyAdmin() external {
        if (allocated + _amount > accountBalance) throw;
        allocated += _amount;
        clients[_clientAddress].checkingBalance += _amount;
        CheckingDeposit(_clientAddress, _amount);
    }
    function endow(address _clientAddress, uint256 _amount) onlyAdmin() external {
        if (allocated + _amount > accountBalance) throw;
        allocated += _amount;
        clients[_clientAddress].endowmentTotal += _amount;
        Endowment(_clientAddress, _amount);
    }
    function removeClient(address _clientAddress) onlyAdmin() external {
        uint256 clientFunds = clients[_clientAddress].checkingBalance +
         clients[_clientAddress].endowmentTotal - clients[_clientAddress].allocatedEndowments;

        allocated -= clientFunds;

        RemoveClient(_clientAddress, clientFunds);
        delete clients[_clientAddress];
    }
    function getVested(address _clientAddress) constant returns(uint256 vested) {
        //wait 60 blocks since last endowment transfer for security (900 second miner fudge factor)
        if (block.number - clients[_clientAddress].lastRedemptionBlock < 60) return 0;
        uint256 startTime = blockTimes[clients[_clientAddress].startBlock];
        if (startTime == 0) return 0;
        uint256 endowmentDuration = (block.timestamp - startTime) * 1 days;
        uint256 earnedEndowments = endowmentDuration / redemptionFrequency;
        return earnedEndowments - clients[_clientAddress].allocatedEndowments;

        //int256 activeDays = clients[_clientAddress].startBlock - msg.blockNumber

    }
    function getCheckingBalance(address _clientAddress) constant external returns(uint256 checkingBalance) {
        checkingBalance = getVested(_clientAddress) + clients[_clientAddress].checkingBalance;
    }
    function getSavingsBalance(address _clientAddress) constant external returns(uint256 savingsBalance) {
        savingsBalance = clients[_clientAddress].allocatedEndowments -
        getVested(_clientAddress) - clients[_clientAddress].checkingBalance;
    }

    function makePurchase(address _vendorAddress, uint256 amount) onlyClient() external  {
        uint256 vested = getVested(msg.sender);
        if (vested + clients[msg.sender].checkingBalance < amount) throw;
        clients[msg.sender].allocatedEndowments += vested;
        clients[msg.sender].checkingBalance += clients[msg.sender].allocatedEndowments -amount;
        vendorBalances[_vendorAddress] += amount;
        Purchase(msg.sender, _vendorAddress, amount);
    }
    function refundClient(address _clientAddress, uint256 amount) onlyVendorWithBalance() external {
        if (vendorBalances[msg.sender] < amount) throw;
        clients[_clientAddress].checkingBalance += amount;
        Refund(msg.sender,_clientAddress,amount);
    }
    function makePurchaseForClient(address _vendorAddress, address _clientAddress, uint256 amount)
       onlyAdmin() external {
        uint256 vested = getVested(_clientAddress);
        if (vested + clients[_clientAddress].checkingBalance < amount) throw;
        clients[_clientAddress].allocatedEndowments += vested;
        clients[_clientAddress].checkingBalance += clients[_clientAddress].allocatedEndowments -amount;
        vendorBalances[_vendorAddress] += amount;
        Purchase(_clientAddress, _vendorAddress, amount);

    }

    function redeemPurchases() onlyVendorWithBalance() external {

        uint256 balance = vendorBalances[msg.sender];
        vendorBalances[msg.sender] = 0;
        Redemption(msg.sender,balance);

    }
    function redeemPurchasesForVendor(address _vendorAddress) onlyAdmin() external {

        uint256 balance = vendorBalances[_vendorAddress];
        vendorBalances[_vendorAddress] = 0;
        Redemption(_vendorAddress,balance);
    }

}

pragma solidity ^0.4.11;

contract Dgp {

    struct Client {
        uint256 startBlock;
        uint256 lastRedemptionBlock;
        uint256 checkingBalance;
        uint256 allocatedEndowments;
        uint256 endowmentTotal;
    }
    address public admin;
    uint256 public accountBalance;
    uint256 public allocated;
    uint256 public constant redemptionFrequency = 7; //7 days
    uint256 public constant redemptionAmt = 7000; //DUST (in cents)

    mapping (address => uint256) public vendorBalances;
    mapping (address => Client) public clients;
	mapping (uint256 => uint256) blockTimes;

    // events
    event Donation(uint256 _value);
    event CheckingDeposit(address indexed _to, uint256 _value);
    event Endowment(address indexed _to, uint256 _value);
    event RemoveClient(address indexed _removed, uint256 _value);
    event Purchase(address indexed _client, address indexed _vendor, uint256 _value);
    event Refund(address indexed _from, address indexed _to, uint256 _value);
    event Redemption(address indexed _to, uint256 _value);

    //access control
	modifier onlyAdmin {
		if (msg.sender != admin)  throw;
		_;
	}
	modifier onlyClient {
		if (clients[msg.sender].startBlock == 0)  throw;
		_;
	}
	modifier onlyVendorWithBalance {
		if (vendorBalances[msg.sender] == 0)  throw;
		_;
	}

        // constructor
    function Dgp()
    {
      admin = msg.sender;
    }
    function registerDonation(uint256 _donationAmt) onlyAdmin() {
        accountBalance += _donationAmt;
        Donation(_donationAmt);
    }

    function registerClient(address _clientAddress, uint256 _checkingBalance,
    uint256 _endowmentTotal, uint256 _startBlock) onlyAdmin() {
        //never allocate more than account balance
        if (_checkingBalance + _endowmentTotal + allocated> accountBalance) throw;
        //TODO use safeAdd?
        allocated += _checkingBalance + _endowmentTotal;
        clients[_clientAddress].checkingBalance = _checkingBalance;
        clients[_clientAddress].endowmentTotal = _endowmentTotal;
        clients[_clientAddress].startBlock = _startBlock;
        clients[_clientAddress].lastRedemptionBlock = 0;
        if (_checkingBalance > 0) CheckingDeposit(_clientAddress, _checkingBalance);
        if (_endowmentTotal > 0) Endowment(_clientAddress, _endowmentTotal);

    }
    function depositChecking(address _clientAddress, uint256 _amount) onlyAdmin() external {
        if (allocated + _amount > accountBalance) throw;
        allocated += _amount;
        clients[_clientAddress].checkingBalance += _amount;
        CheckingDeposit(_clientAddress, _amount);
    }
    function endow(address _clientAddress, uint256 _amount) onlyAdmin() external {
        if (allocated + _amount > accountBalance) throw;
        allocated += _amount;
        clients[_clientAddress].endowmentTotal += _amount;
        Endowment(_clientAddress, _amount);
    }
    function removeClient(address _clientAddress) onlyAdmin() external {
        uint256 clientFunds = clients[_clientAddress].checkingBalance +
         clients[_clientAddress].endowmentTotal - clients[_clientAddress].allocatedEndowments;

        allocated -= clientFunds;

        RemoveClient(_clientAddress, clientFunds);
        delete clients[_clientAddress];
    }
    function getVested(address _clientAddress) constant returns(uint256 vested) {
        //wait 60 blocks since last endowment transfer for security (900 second miner fudge factor)
        if (block.number - clients[_clientAddress].lastRedemptionBlock < 60) return 0;
        uint256 startTime = blockTimes[clients[_clientAddress].startBlock];
        if (startTime == 0) return 0;
        uint256 endowmentDuration = (block.timestamp - startTime) * 1 days;
        uint256 earnedEndowments = endowmentDuration / redemptionFrequency;
        return earnedEndowments - clients[_clientAddress].allocatedEndowments;

        //int256 activeDays = clients[_clientAddress].startBlock - msg.blockNumber

    }
    function getCheckingBalance(address _clientAddress) constant external returns(uint256 checkingBalance) {
        checkingBalance = getVested(_clientAddress) + clients[_clientAddress].checkingBalance;
    }
    function getSavingsBalance(address _clientAddress) constant external returns(uint256 savingsBalance) {
        savingsBalance = clients[_clientAddress].allocatedEndowments -
        getVested(_clientAddress) - clients[_clientAddress].checkingBalance;
    }

    function makePurchase(address _vendorAddress, uint256 amount) onlyClient() external  {
        uint256 vested = getVested(msg.sender);
        if (vested + clients[msg.sender].checkingBalance < amount) throw;
        clients[msg.sender].allocatedEndowments += vested;
        clients[msg.sender].checkingBalance += clients[msg.sender].allocatedEndowments -amount;
        vendorBalances[_vendorAddress] += amount;
        Purchase(msg.sender, _vendorAddress, amount);
    }
    function refundClient(address _clientAddress, uint256 amount) onlyVendorWithBalance() external {

    }
    function makePurchaseForClient(address _vendorAddress, address _clientAddress, uint256 amount)
       onlyAdmin() external {

    }

    function redeemPurchases() onlyVendorWithBalance() external {

    }
    function redeemPurchasesForVendor() onlyAdmin() external {

    }

}


minor cleanup

minor cleanup

pragma solidity ^0.4.10;
import './Owned.sol';
import './ERC20Token.sol';
import './ERC20TokenInterface.sol';
import './BancorEventsInterface.sol';

/*
    Smart Token v0.1
*/
contract SmartToken is Owned, ERC20Token {
    string public version = '0.1';
    uint8 public numDecimalUnits = 0;   // for display purposes only
    address public events = 0x0;        // bancor events contract address
    address public changer = 0x0;       // changer contract address
    bool public transfersEnabled = true;

    // events, can be used to listen to the contract directly, as opposed to through the events contract
    event ChangerUpdate(address _prevChanger, address _newChanger);

    /*
        _name               token name
        _symbol             token short symbol, 1-6 characters
        _numDecimalUnits    for display purposes only
        _formula            address of a bancor formula contract
        _events             optional, address of a bancor events contract
    */
    function SmartToken(string _name, string _symbol, uint8 _numDecimalUnits, address _events)
        ERC20Token(_name, _symbol)
    {
        require(bytes(_name).length != 0 && bytes(_symbol).length >= 1 && bytes(_symbol).length <= 6); // validate input

        numDecimalUnits = _numDecimalUnits;
        events = _events;
        if (events == 0x0)
            return;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.newToken();
    }

    // allows execution only when transfers aren't disabled
    modifier transfersAllowed {
        assert(transfersEnabled);
        _;
    }

    // allows execution by the owner if there's no changer defined or by the changer contract if a changer is defined
    modifier managerOnly {
        assert((changer == 0x0 && msg.sender == owner) ||
               (changer != 0x0 && msg.sender == changer)); // validate state & permissions
        _;
    }

    function setOwner(address _newOwner)
        public
        ownerOnly
        validAddress(_newOwner)
    {
        address prevOwner = owner;
        super.setOwner(_newOwner);
        if (events == 0x0)
            return;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.tokenOwnerUpdate(prevOwner, owner);
    }

    /*
        sets the number of display decimal units
        can only be called by the token owner

        _numDecimalUnits    new number of decimal units
    */
    function setNumDecimalUnits(uint8 _numDecimalUnits) public ownerOnly {
        numDecimalUnits = _numDecimalUnits;
    }

    /*
        disables/enables transfers
        can only be called by the token owner (if no changer is defined) or the changer contract (if a changer is defined)

        _disable    true to disable transfers, false to enable them
    */
    function disableTransfers(bool _disable) public managerOnly {
        transfersEnabled = !_disable;
    }

    /*
        increases the token supply and sends the new tokens to an account
        can only be called by the token owner (if no changer is defined) or the changer contract (if a changer is defined)

        _to         account to receive the new amount
        _amount     amount to increase the supply by
    */
    function issue(address _to, uint256 _amount)
        public
        managerOnly
        validAddress(_to)
        returns (bool success)
    {
         // validate input
        require(_to != address(this) && _amount != 0);
         // supply overflow protection
        assert(totalSupply + _amount >= totalSupply);
        // target account balance overflow protection
        assert(balanceOf[_to] + _amount >= balanceOf[_to]);

        totalSupply += _amount;
        balanceOf[_to] += _amount;
        dispatchTransfer(this, _to, _amount);
        return true;
    }

    /*
        removes tokens from an account and decreases the token supply
        can only be called by the token owner (if no changer is defined) or the changer contract (if a changer is defined)

        _from       account to remove the new amount from
        _amount     amount to decrease the supply by
    */
    function destroy(address _from, uint256 _amount)
        public
        managerOnly
        validAddress(_from)
        returns (bool success)
    {
        require(_from != address(this) && _amount != 0 && _amount <= balanceOf[_from]); // validate input

        totalSupply -= _amount;
        balanceOf[_from] -= _amount;
        dispatchTransfer(_from, this, _amount);
        return true;
    }

    /*
        sets a changer contract address
        can only be called by the token owner (if no changer is defined) or the changer contract (if a changer is defined)
        the changer can be set to null to transfer ownership from the changer to the owner

        _changer    new changer contract address (can also be set to 0x0 to remove the current changer)
    */
    function setChanger(address _changer) public managerOnly returns (bool success) {
        require(_changer != changer);
        address prevChanger = changer;
        changer = _changer;
        dispatchChangerUpdate(prevChanger, changer);
        return true;
    }

    // ERC20 standard method overrides with some extra functionality

    // send coins
    function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
        assert(super.transfer(_to, _value));

        // transferring to the contract address destroys tokens
        if (_to == address(this)) {
            balanceOf[_to] -= _value;
            totalSupply -= _value;
        }

        if (events == 0x0)
            return;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.tokenTransfer(msg.sender, _to, _value);
        return true;
    }

    // an account/contract attempts to get the coins
    function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
        assert(super.transferFrom(_from, _to, _value));

        // transferring to the contract address destroys tokens
        if (_to == address(this)) {
            balanceOf[_to] -= _value;
            totalSupply -= _value;
        }

        if (events == 0x0)
            return;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.tokenTransfer(_from, _to, _value);
        return true;
    }

    // allow another account/contract to spend some tokens on your behalf
    function approve(address _spender, uint256 _value) public returns (bool success) {
        assert(super.approve(_spender, _value));
        if (events == 0x0)
            return true;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.tokenApproval(msg.sender, _spender, _value);
        return true;
    }

    // utility

    function dispatchChangerUpdate(address _prevChanger, address _newChanger) private {
        ChangerUpdate(_prevChanger, _newChanger);
        if (events == 0x0)
            return;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.tokenChangerUpdate(_prevChanger, _newChanger);
    }

    function dispatchTransfer(address _from, address _to, uint256 _value) private {
        Transfer(_from, _to, _value);
        if (events == 0x0)
            return;

        BancorEventsInterface eventsContract = BancorEventsInterface(events);
        eventsContract.tokenTransfer(_from, _to, _value);
    }

    // fallback
    function() {
        assert(false);
    }
}


Updated ballot to empty initialisation

Updated ballot to empty initialisation

pragma solidity ^0.4.6;
// We have to specify what version of compiler this code will compile with

contract Ballot {

    struct Voter {
        uint weight;
        bool voted;
    }

    bytes32[] public candidateList;
    mapping(address => Voter) public votersList;
    mapping (bytes32 => uint8) public votesForCandidates;

  function Ballot() {
  }

  function addCandidate(bytes32 candidate) {
      candidateList.push(candidate);
  }

  function addVoter(address voter) {
      votersList[voter] = Voter({weight: 1, voted: false});
  }

  function totalVotesFor(bytes32 candidate) returns (uint8) {
    if (validCandidate(candidate) == false) throw;
    return votesForCandidates[candidate];
  }

  function vote(bytes32 candidate) {
    if (votersList[msg.sender].weight != 1 || votersList[msg.sender].voted) return;
    if (validCandidate(candidate) == false) throw;
    votesForCandidates[candidate] += 1;
    votersList[msg.sender].voted = true;
  }

  function validCandidate(bytes32 candidate) returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }

  function getWinner() returns (bytes32) {
      uint maxVotes = 0;
      bytes32 winner = "";

      for (uint i = 0; i < candidateList.length; i++) {
          if (votesForCandidates[candidateList[i]] > maxVotes) {
              maxVotes = votesForCandidates[candidateList[i]];
              winner = candidateList[i];
          }
      }

      return winner;
  }
}

pragma solidity ^0.4.6;
// We have to specify what version of compiler this code will compile with

contract Ballot {

    struct Voter {
        uint weight;
        bool voted;
    }

    bytes32[] public candidateList;
    mapping(address => Voter) public votersList;
    mapping (bytes32 => uint8) public votesForCandidates;

  function Ballot(bytes32[] candidateNames, address[] voterAddresses) {
      candidateList = candidateNames;

    for (uint j = 0; j < voterAddresses.length; j++) {
        votersList[voterAddresses[j]] = Voter({weight: 1, voted: false});
    }
  }

  function totalVotesFor(bytes32 candidate) returns (uint8) {
    if (validCandidate(candidate) == false) throw;
    return votesForCandidates[candidate];
  }

  function vote(bytes32 candidate) {
    if (votersList[msg.sender].weight != 1 || votersList[msg.sender].voted) return;
    if (validCandidate(candidate) == false) throw;
    votesForCandidates[candidate] += 1;
    votersList[msg.sender].voted = true;
  }

  function validCandidate(bytes32 candidate) returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }

  function getWinner() returns (bytes32) {
      uint maxVotes = 0;
      bytes32 winner = "";

      for (uint i = 0; i < candidateList.length; i++) {
          if (votesForCandidates[candidateList[i]] > maxVotes) {
              maxVotes = votesForCandidates[candidateList[i]];
              winner = candidateList[i];
          }
      }

      return winner;
  }
}


solc > 0.4.25

solc > 0.4.25

pragma solidity >0.4.24;

library SHA1 {
    event Debug(bytes32 x);

    function sha1(bytes memory data) internal pure returns(bytes20 ret) {
        assembly {
            // Get a safe scratch location
            let scratch := mload(0x40)

            // Get the data length, and point data at the first byte
            let len := mload(data)
            data := add(data, 32)

            // Find the length after padding
            let totallen := add(and(add(len, 1), 0xFFFFFFFFFFFFFFC0), 64)
            switch lt(sub(totallen, len), 9)
            case 1 { totallen := add(totallen, 64) }

            let h := 0x6745230100EFCDAB890098BADCFE001032547600C3D2E1F0

            function readword(ptr, off, count) -> result {
                result := 0
                if lt(off, count) {
                    result := mload(add(ptr, off))
                    count := sub(count, off)
                    if lt(count, 32) {
                        let mask := not(sub(exp(256, sub(32, count)), 1))
                        result := and(result, mask)
                    }
                }
            }

            for { let i := 0 } lt(i, totallen) { i := add(i, 64) } {
                mstore(scratch, readword(data, i, len))
                mstore(add(scratch, 32), readword(data, add(i, 32), len))

                // If we loaded the last byte, store the terminator byte
                switch lt(sub(len, i), 64)
                case 1 { mstore8(add(scratch, sub(len, i)), 0x80) }

                // If this is the last block, store the length
                switch eq(i, sub(totallen, 64))
                case 1 { mstore(add(scratch, 32), or(mload(add(scratch, 32)), mul(len, 8))) }

                // Expand the 16 32-bit words into 80
                for { let j := 64 } lt(j, 128) { j := add(j, 12) } {
                    let temp := xor(xor(mload(add(scratch, sub(j, 12))), mload(add(scratch, sub(j, 32)))), xor(mload(add(scratch, sub(j, 56))), mload(add(scratch, sub(j, 64)))))
                    temp := or(and(mul(temp, 2), 0xFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFE), and(div(temp, 0x80000000), 0x0000000100000001000000010000000100000001000000010000000100000001))
                    mstore(add(scratch, j), temp)
                }
                for { let j := 128 } lt(j, 320) { j := add(j, 24) } {
                    let temp := xor(xor(mload(add(scratch, sub(j, 24))), mload(add(scratch, sub(j, 64)))), xor(mload(add(scratch, sub(j, 112))), mload(add(scratch, sub(j, 128)))))
                    temp := or(and(mul(temp, 4), 0xFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFC), and(div(temp, 0x40000000), 0x0000000300000003000000030000000300000003000000030000000300000003))
                    mstore(add(scratch, j), temp)
                }

                let x := h
                let f := 0
                let k := 0
                for { let j := 0 } lt(j, 80) { j := add(j, 1) } {
                    switch div(j, 20)
                    case 0 {
                        // f = d xor (b and (c xor d))
                        f := xor(div(x, 0x100000000000000000000), div(x, 0x10000000000))
                        f := and(div(x, 0x1000000000000000000000000000000), f)
                        f := xor(div(x, 0x10000000000), f)
                        k := 0x5A827999
                    }
                    case 1{
                        // f = b xor c xor d
                        f := xor(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000))
                        f := xor(div(x, 0x10000000000), f)
                        k := 0x6ED9EBA1
                    }
                    case 2 {
                        // f = (b and c) or (d and (b or c))
                        f := or(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000))
                        f := and(div(x, 0x10000000000), f)
                        f := or(and(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000)), f)
                        k := 0x8F1BBCDC
                    }
                    case 3 {
                        // f = b xor c xor d
                        f := xor(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000))
                        f := xor(div(x, 0x10000000000), f)
                        k := 0xCA62C1D6
                    }
                    // temp = (a leftrotate 5) + f + e + k + w[i]
                    let temp := and(div(x, 0x80000000000000000000000000000000000000000000000), 0x1F)
                    temp := or(and(div(x, 0x800000000000000000000000000000000000000), 0xFFFFFFE0), temp)
                    temp := add(f, temp)
                    temp := add(and(x, 0xFFFFFFFF), temp)
                    temp := add(k, temp)
                    temp := add(div(mload(add(scratch, mul(j, 4))), 0x100000000000000000000000000000000000000000000000000000000), temp)
                    x := or(div(x, 0x10000000000), mul(temp, 0x10000000000000000000000000000000000000000))
                    x := or(and(x, 0xFFFFFFFF00FFFFFFFF000000000000FFFFFFFF00FFFFFFFF), mul(or(and(div(x, 0x4000000000000), 0xC0000000), and(div(x, 0x400000000000000000000), 0x3FFFFFFF)), 0x100000000000000000000))
                }

                h := and(add(h, x), 0xFFFFFFFF00FFFFFFFF00FFFFFFFF00FFFFFFFF00FFFFFFFF)
            }
            ret := mul(or(or(or(or(and(div(h, 0x100000000), 0xFFFFFFFF00000000000000000000000000000000), and(div(h, 0x1000000), 0xFFFFFFFF000000000000000000000000)), and(div(h, 0x10000), 0xFFFFFFFF0000000000000000)), and(div(h, 0x100), 0xFFFFFFFF00000000)), and(h, 0xFFFFFFFF)), 0x1000000000000000000000000)
        }
    }
}

pragma solidity >=0.5.0;

library SHA1 {
    event Debug(bytes32 x);

    function sha1(bytes memory data) internal pure returns(bytes20 ret) {
        assembly {
            // Get a safe scratch location
            let scratch := mload(0x40)

            // Get the data length, and point data at the first byte
            let len := mload(data)
            data := add(data, 32)

            // Find the length after padding
            let totallen := add(and(add(len, 1), 0xFFFFFFFFFFFFFFC0), 64)
            switch lt(sub(totallen, len), 9)
            case 1 { totallen := add(totallen, 64) }

            let h := 0x6745230100EFCDAB890098BADCFE001032547600C3D2E1F0

            function readword(ptr, off, count) -> result {
                result := 0
                if lt(off, count) {
                    result := mload(add(ptr, off))
                    count := sub(count, off)
                    if lt(count, 32) {
                        let mask := not(sub(exp(256, sub(32, count)), 1))
                        result := and(result, mask)
                    }
                }
            }

            for { let i := 0 } lt(i, totallen) { i := add(i, 64) } {
                mstore(scratch, readword(data, i, len))
                mstore(add(scratch, 32), readword(data, add(i, 32), len))

                // If we loaded the last byte, store the terminator byte
                switch lt(sub(len, i), 64)
                case 1 { mstore8(add(scratch, sub(len, i)), 0x80) }

                // If this is the last block, store the length
                switch eq(i, sub(totallen, 64))
                case 1 { mstore(add(scratch, 32), or(mload(add(scratch, 32)), mul(len, 8))) }

                // Expand the 16 32-bit words into 80
                for { let j := 64 } lt(j, 128) { j := add(j, 12) } {
                    let temp := xor(xor(mload(add(scratch, sub(j, 12))), mload(add(scratch, sub(j, 32)))), xor(mload(add(scratch, sub(j, 56))), mload(add(scratch, sub(j, 64)))))
                    temp := or(and(mul(temp, 2), 0xFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFE), and(div(temp, 0x80000000), 0x0000000100000001000000010000000100000001000000010000000100000001))
                    mstore(add(scratch, j), temp)
                }
                for { let j := 128 } lt(j, 320) { j := add(j, 24) } {
                    let temp := xor(xor(mload(add(scratch, sub(j, 24))), mload(add(scratch, sub(j, 64)))), xor(mload(add(scratch, sub(j, 112))), mload(add(scratch, sub(j, 128)))))
                    temp := or(and(mul(temp, 4), 0xFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFCFFFFFFFC), and(div(temp, 0x40000000), 0x0000000300000003000000030000000300000003000000030000000300000003))
                    mstore(add(scratch, j), temp)
                }

                let x := h
                let f := 0
                let k := 0
                for { let j := 0 } lt(j, 80) { j := add(j, 1) } {
                    switch div(j, 20)
                    case 0 {
                        // f = d xor (b and (c xor d))
                        f := xor(div(x, 0x100000000000000000000), div(x, 0x10000000000))
                        f := and(div(x, 0x1000000000000000000000000000000), f)
                        f := xor(div(x, 0x10000000000), f)
                        k := 0x5A827999
                    }
                    case 1{
                        // f = b xor c xor d
                        f := xor(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000))
                        f := xor(div(x, 0x10000000000), f)
                        k := 0x6ED9EBA1
                    }
                    case 2 {
                        // f = (b and c) or (d and (b or c))
                        f := or(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000))
                        f := and(div(x, 0x10000000000), f)
                        f := or(and(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000)), f)
                        k := 0x8F1BBCDC
                    }
                    case 3 {
                        // f = b xor c xor d
                        f := xor(div(x, 0x1000000000000000000000000000000), div(x, 0x100000000000000000000))
                        f := xor(div(x, 0x10000000000), f)
                        k := 0xCA62C1D6
                    }
                    // temp = (a leftrotate 5) + f + e + k + w[i]
                    let temp := and(div(x, 0x80000000000000000000000000000000000000000000000), 0x1F)
                    temp := or(and(div(x, 0x800000000000000000000000000000000000000), 0xFFFFFFE0), temp)
                    temp := add(f, temp)
                    temp := add(and(x, 0xFFFFFFFF), temp)
                    temp := add(k, temp)
                    temp := add(div(mload(add(scratch, mul(j, 4))), 0x100000000000000000000000000000000000000000000000000000000), temp)
                    x := or(div(x, 0x10000000000), mul(temp, 0x10000000000000000000000000000000000000000))
                    x := or(and(x, 0xFFFFFFFF00FFFFFFFF000000000000FFFFFFFF00FFFFFFFF), mul(or(and(div(x, 0x4000000000000), 0xC0000000), and(div(x, 0x400000000000000000000), 0x3FFFFFFF)), 0x100000000000000000000))
                }

                h := and(add(h, x), 0xFFFFFFFF00FFFFFFFF00FFFFFFFF00FFFFFFFF00FFFFFFFF)
            }
            ret := mul(or(or(or(or(and(div(h, 0x100000000), 0xFFFFFFFF00000000000000000000000000000000), and(div(h, 0x1000000), 0xFFFFFFFF000000000000000000000000)), and(div(h, 0x10000), 0xFFFFFFFF0000000000000000)), and(div(h, 0x100), 0xFFFFFFFF00000000)), and(h, 0xFFFFFFFF)), 0x1000000000000000000000000)
        }
    }
}


update TestCallExecution contract

update TestCallExecution contract

contract SchedulerAPI {
    function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock) public returns (address);
    //function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint suggestedGas) public returns (address);
    //function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint suggestedGas, uint8 gracePeriod) public returns (address);
    //function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint suggestedGas, uint8 gracePeriod, uint basePayment) public returns (address);
    //function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint suggestedGas, uint8 gracePeriod, uint basePayment, uint baseFee) public returns (address);
}

contract TestDataRegistry {
        uint8 public wasSuccessful = 0;

        function reset() public {
            wasSuccessful = 0;
        }

        function registerBool(address to, bool v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerUInt(address to, uint v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerInt(address to, int v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerBytes32(address to, bytes32 v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerBytes(address to, bytes v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v.length, v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerAddress(address to, address v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerMany(address to, uint a, int b, uint c, bytes20 d, address e, bytes f) public {
            bool result = to.call(bytes4(sha3("registerData()")), a, b, c, d, e, f.length, f);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerData(address to, int arg1, bytes32 arg2, address arg3) public {
            // 0xb0f07e44 == bytes4(sha3("registerData()"))
            bool result = to.call(0xb0f07e44, arg1, arg2, arg3);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }
}

contract TestCallExecution is TestDataRegistry {
        uint8 public wasSuccessful;

        function doExecution(address to) {
            bool result = to.call(bytes4(sha3("execute()")));
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function doLoops(uint iterations) {
            for (uint i = 0; i < iterations; i++) {
                address(this).send(1);
            }
        }

        bool public v_bool;

        function scheduleSetBool(address to, uint targetBlock, bool v) public {
            SchedulerAPI arst = SchedulerAPI(to);
            address call_address = arst.scheduleCall.value(msg.value)(address(this), bytes4(sha3("setBool()")), targetBlock);
            call_address.call(bytes4(sha3("registerData()")), v);
        }

        function setBool() public {
            v_bool = true;
        }

        uint public v_uint;

        function scheduleSetUInt(address to, uint targetBlock, uint v) public {
            SchedulerAPI arst = SchedulerAPI(to);
            address call_address = arst.scheduleCall.value(msg.value)(address(this), bytes4(sha3("setUInt(uint256)")), targetBlock);
            call_address.call(bytes4(sha3("registerData()")), v);
        }

        function setUInt(uint v) public {
            v_uint = v;
        }

        int public v_int;

        function setInt(int v) public {
            v_int = v;
        }

        address public v_address;

        function setAddress(address v) public {
            v_address = v;
        }

        bytes32 public v_bytes32;

        function setBytes32(bytes32 v) public {
            v_bytes32 = v;
        }

        bytes public v_bytes;

        function setBytes(bytes v) public {
            Bytes(v);
            Bytes(msg.data);
            v_bytes = v;
        }

        uint public vm_a;
        int public vm_b;
        uint public vm_c;
        bytes20 public vm_d;
        address public vm_e;
        bytes public vm_f;

        event Bytes(bytes f);

        function setMany(uint a, int b, uint c, bytes20 d, address e, bytes f) public {
            Bytes(f);
            Bytes(msg.data);
            vm_a = a;
            vm_b = b;
            vm_c = c;
            vm_d = d;
            vm_e = e;
            vm_f = f;
        }
}

contract TestErrors {
        bool public value;

        function doFail() public {
                throw;
                value = true;
        }

        function doInfinite() public {
                while (true) {
                        tx.origin.send(1);
                }
                value = true;
        }
}

contract TestDataRegistry {
        uint8 public wasSuccessful = 0;

        function reset() public {
            wasSuccessful = 0;
        }

        function registerUInt(address to, uint v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerInt(address to, int v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerBytes32(address to, bytes32 v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerBytes(address to, bytes v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v.length, v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerAddress(address to, address v) public {
            bool result = to.call(bytes4(sha3("registerData()")), v);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerMany(address to, uint a, int b, uint c, bytes20 d, address e, bytes f) public {
            bool result = to.call(bytes4(sha3("registerData()")), a, b, c, d, e, f.length, f);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function registerData(address to, int arg1, bytes32 arg2, address arg3) public {
            // 0xb0f07e44 == bytes4(sha3("registerData()"))
            bool result = to.call(0xb0f07e44, arg1, arg2, arg3);
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }
}

contract TestCallExecution {
        uint8 public wasSuccessful;

        function doExecution(address to) {
            bool result = to.call(bytes4(sha3("execute()")));
            if (result) {
                wasSuccessful = 1;
            }
            else {
                wasSuccessful = 2;
            }
        }

        function doLoops(uint iterations) {
            for (uint i = 0; i < iterations; i++) {
                address(this).send(1);
            }
        }

        bool public v_bool;

        function setBool() public {
            v_bool = true;
        }

        uint public v_uint;

        function setUInt(uint v) public {
            v_uint = v;
        }

        int public v_int;

        function setInt(int v) public {
            v_int = v;
        }

        address public v_address;

        function setAddress(address v) public {
            v_address = v;
        }

        bytes32 public v_bytes32;

        function setBytes32(bytes32 v) public {
            v_bytes32 = v;
        }

        bytes public v_bytes;

        function setBytes(bytes v) public {
            Bytes(v);
            Bytes(msg.data);
            v_bytes = v;
        }

        uint public vm_a;
        int public vm_b;
        uint public vm_c;
        bytes20 public vm_d;
        address public vm_e;
        bytes public vm_f;

        event Bytes(bytes f);

        function setMany(uint a, int b, uint c, bytes20 d, address e, bytes f) public {
            Bytes(f);
            Bytes(msg.data);
            vm_a = a;
            vm_b = b;
            vm_c = c;
            vm_d = d;
            vm_e = e;
            vm_f = f;
        }
}

contract TestErrors {
        bool public value;

        function doFail() public {
                throw;
                value = true;
        }

        function doInfinite() public {
                while (true) {
                        tx.origin.send(1);
                }
                value = true;
        }
}