Recursive dissolution?

Recursive dissolution?

/// Partnership
/// Requires all pre-defined partners agreement on transactions and operations.
contract Partnership
{
	event Funded();
	event Deposit(address _from, uint _value);
	event ConfirmationRequired(bytes32 _operation, address _initiator, address _to, uint _value, bytes _data);
	event TransactionSent(bytes32 _transaction, address _finalSigner, address _to, uint _value, bytes _data);

	/// Price in wei of each equal share of the partnership
	uint public sharePrice;

	/// Flag indicating whether or not all partners have paid for their share
	bool public funded;

	/// Array of partner addresses
	address [] public partners;

	/// Collection of partner records
	mapping(address => Partner) public partnerRecords;

	/// Count of partners
	uint public partnerCount;

	/// Count of partners who have paid for their share
	uint public paidPartnerCount;

	/// Collection of pending transactions (ie send X ETH to Y with Z data)
	mapping(bytes32 => Transaction) public transactions;

	struct Partner {
		/// Flag indicating that this record has been initialized
		bool isPartner;
		/// Flag indicating that the partner has paid for their share
		bool paid;
		/// Total amount loaned to the partnership by the partner
		uint loanBalance;
		/// Amount released for withdrawal by the partner
		uint withdrawableAmount;
	}

	struct Transaction {
		/// Flag indicating that this record has been initialized
		bool valid;
		/// Proposed recipient for the transaction (0 indicates a new contract will be created)
		address to;
		/// Proposed amount to send (0 indicates no wei)
		uint value;
		/// Optional array of data to send with the transaction
		bytes data;
		/// Optional description of proposed transaction
		string description;
		/// Account that created the transaction
		address creator;
		/// Total number of partners that have confirmed/voted
		uint voteCount;
		/// Collection of partners that have confirmed/voted
		mapping(address => uint) votes;
		/// Flag indicating that all partners have confirmed
		bool passed;
		/// Flag indicatint that the transaction has been sent
		bool sent;
	}

	modifier onlyFunded {
		if (!funded)
	       		throw;
		_
	}

	modifier onlyPartner {
		if (!isPartner(msg.sender))
			throw;
		_
	}

	modifier onlyDao {
		if (msg.sender != address(this))
			throw;
		_
	}

	function Partnership(address[] _partners, uint _sharePrice) {
		funded = false;
		sharePrice = _sharePrice;
		partners = _partners;
		for (uint i = 0; i < _partners.length; i++) {
			partnerRecords[_partners[i]].isPartner = true;
		}
		partnerCount = _partners.length;
	}

	/// This executes when funds are sent to the contract
	function() {
		if (msg.value > 0) {
			if (funded) {
				if (isPartner(msg.sender)) {
					partnerRecords[msg.sender].loanBalance += msg.value;
				}
			}
			else {
				if (isPartner(msg.sender)) {
					if (partnerRecords[msg.sender].paid) {
						throw;
					}
					else {
						if (msg.value == sharePrice) {
							partnerRecords[msg.sender].paid = true;
							paidPartnerCount += 1;
							if (paidPartnerCount == partnerCount) {
								funded = true;
								Funded();
							}
						}
						else {
							throw;
						}
					}
				}
				else {
					throw;
				}
			}
			Deposit(msg.sender, msg.value);
		}
	}

	/// Adds a proposed transaction to be confirmed by other partners
	function proposeTransaction(address _to, uint _value, bytes _data, string _description) onlyFunded onlyPartner external returns (bytes32) {

		// generate hash for easy specification in confirm and execute
		bytes32 id = sha3(msg.data, block.number);

		// grab the presumably blank transaction
		var transaction = transactions[id];

		transaction.valid = true;
		transaction.to = _to;
		transaction.value = _value;
		transaction.data = _data;
		transaction.description = _description;
		transaction.creator = msg.sender;
		transaction.voteCount = 1;
		transaction.votes[msg.sender] = 1;
		transaction.passed = false;
		transaction.sent = false;

		ConfirmationRequired(id, msg.sender, _description);

		return id;
	}

	/// Confirms an existing proposed transaction
	function confirmTransaction(bytes32 _id) onlyFunded onlyPartner external {

		var transaction = transactions[_id];

		// ensure this is a transaction we've set up
		if (!transaction.valid)
			throw;

		// ignore second confirmation
		if (transaction.votes[msg.sender] == 1)
			throw;

		// register the vote
		transaction.voteCount += 1;
		transaction.votes[msg.sender] = 1;

		if (transaction.voteCount == partnerCount) {
			transaction.passed = true;
			TransactionPassed(_id, msg.sender, transaction.to, transaction.value, transaction.data);
		}
	}

	/// Executes a passed transaction
	function executeTransaction(bytes32 _id) onlyFunded onlyPartner external {

		var transaction = transactions[_id];

		// ignore transactions that have not passed yet
		if (!transaction.passed)
			throw;

		// ignore transactions that have already been sent
		if (transaction.sent)
			throw;

		// register the sent transaction
		transaction.sent = true;

		// send the transaction
		if (transactions[_id].to.call.value(transactions[_id].value)(transactions[_id].data)) {

			TransactionSent(_id, msg.sender, transaction.to, transaction.value, transaction.data);

			// clear the transaction structure to free memory
			delete transactions[_id];
		}
		else {
			// roll back if the call failed
			transaction.sent = false;
		}
	}

	/// Distribute ETH to a partner
	function distribute(address _partner, uint _amount) onlyDao external {

		// ignore invalid partners
		if (!isPartner(_partner))
			throw;

		partnerRecords[_partner].withdrawableAmount += _amount;
	}

	/// Distribute ETH evenly amongst all partners
	function distributeEvenly(uint _amount) onlyDao external {

		var payout = _amount / partnerCount;

		for (uint i = 0; i < partnerCount; i++) {
			partnerRecords[partners[i]].withdrawableAmount += payout;
	}

	/// Mark down partner's loan and make it available for withdrawal
	function repayLoan(address _partner, uint _amount) onlyDao external {

		// ignore invalid partners
		if (!partnerRecords[_partner].isPartner)
			throw;

		// ignore invalid amounts
		if (_amount > partnerRecords[_partner].loanBalance)
			throw;

		partnerRecords[_partner].loanBalance -= amount;
		partnerRecords[_partner].withdrawableAmount += amount;
	}

	/// Allow partner to withdraw funds marked as withdrawable
	function withdraw(uint _amount) onlyFunded onlyPartner external {

		// ignore requests for more than the amount allowed
		if (_amount > partnerRecords[msg.sender].withdrawableAmount)
			throw;

		// ignore requests for more than the available balance
		if (_amount > this.balance)
			throw;

		// mark the withdrawal as successful
		partnerRecords[msg.sender].withdrawableAmount -= _amount;

		// send the wei
		if (msg.sender.send(_amount)) {
			Withdrawal(msg.sender, _amount);
		}
		else {
			// roll back if the send failed
			partnerRecords[msg.sender].withdrawableAmount += _amount;
		}
	}

	/// Dissolve DAO and send the remaining ETH to a beneficiary
	function dissolve(address _beneficiary) onlyDao external {

		// ignore unset beneficiary, or recursive dissolution?
		if ((_beneficiary == 0) || (_beneficiary == this))
			throw;

		suicide(_beneficiary);
	}

	function isPartner(address _address) internal returns (bool) {
		return partnerRecords[_address].isPartner;
	}

}

/// Partnership
/// Requires all pre-defined partners agreement on transactions and operations.
contract Partnership
{
	event Funded();
	event Deposit(address _from, uint _value);
	event ConfirmationRequired(bytes32 _operation, address _initiator, address _to, uint _value, bytes _data);
	event TransactionSent(bytes32 _transaction, address _finalSigner, address _to, uint _value, bytes _data);

	/// Price in wei of each equal share of the partnership
	uint public sharePrice;

	/// Flag indicating whether or not all partners have paid for their share
	bool public funded;

	/// Array of partner addresses
	address [] public partners;

	/// Collection of partner records
	mapping(address => Partner) public partnerRecords;

	/// Count of partners
	uint public partnerCount;

	/// Count of partners who have paid for their share
	uint public paidPartnerCount;

	/// Collection of pending transactions (ie send X ETH to Y with Z data)
	mapping(bytes32 => Transaction) public transactions;

	struct Partner {
		/// Flag indicating that this record has been initialized
		bool isPartner;
		/// Flag indicating that the partner has paid for their share
		bool paid;
		/// Total amount loaned to the partnership by the partner
		uint loanBalance;
		/// Amount released for withdrawal by the partner
		uint withdrawableAmount;
	}

	struct Transaction {
		/// Flag indicating that this record has been initialized
		bool valid;
		/// Proposed recipient for the transaction (0 indicates a new contract will be created)
		address to;
		/// Proposed amount to send (0 indicates no wei)
		uint value;
		/// Optional array of data to send with the transaction
		bytes data;
		/// Optional description of proposed transaction
		string description;
		/// Account that created the transaction
		address creator;
		/// Total number of partners that have confirmed/voted
		uint voteCount;
		/// Collection of partners that have confirmed/voted
		mapping(address => uint) votes;
		/// Flag indicating that all partners have confirmed
		bool passed;
		/// Flag indicatint that the transaction has been sent
		bool sent;
	}

	modifier onlyFunded {
		if (!funded)
	       		throw;
		_
	}

	modifier onlyPartner {
		if (!isPartner(msg.sender))
			throw;
		_
	}

	modifier onlyDao {
		if (msg.sender != address(this))
			throw;
		_
	}

	function Partnership(address[] _partners, uint _sharePrice) {
		funded = false;
		sharePrice = _sharePrice;
		partners = _partners;
		for (uint i = 0; i < _partners.length; i++) {
			partnerRecords[_partners[i]].isPartner = true;
		}
		partnerCount = _partners.length;
	}

	/// This executes when funds are sent to the contract
	function() {
		if (msg.value > 0) {
			if (funded) {
				if (isPartner(msg.sender)) {
					partnerRecords[msg.sender].loanBalance += msg.value;
				}
			}
			else {
				if (isPartner(msg.sender)) {
					if (partnerRecords[msg.sender].paid) {
						throw;
					}
					else {
						if (msg.value == sharePrice) {
							partnerRecords[msg.sender].paid = true;
							paidPartnerCount += 1;
							if (paidPartnerCount == partnerCount) {
								funded = true;
								Funded();
							}
						}
						else {
							throw;
						}
					}
				}
				else {
					throw;
				}
			}
			Deposit(msg.sender, msg.value);
		}
	}

	/// Adds a proposed transaction to be confirmed by other partners
	function proposeTransaction(address _to, uint _value, bytes _data, string _description) onlyFunded onlyPartner external returns (bytes32) {

		// generate hash for easy specification in confirm and execute
		bytes32 id = sha3(msg.data, block.number);

		// grab the presumably blank transaction
		var transaction = transactions[id];

		transaction.valid = true;
		transaction.to = _to;
		transaction.value = _value;
		transaction.data = _data;
		transaction.description = _description;
		transaction.creator = msg.sender;
		transaction.voteCount = 1;
		transaction.votes[msg.sender] = 1;
		transaction.passed = false;
		transaction.sent = false;

		ConfirmationRequired(id, msg.sender, _description);

		return id;
	}

	/// Confirms an existing proposed transaction
	function confirmTransaction(bytes32 _id) onlyFunded onlyPartner external {

		var transaction = transactions[_id];

		// ensure this is a transaction we've set up
		if (!transaction.valid)
			throw;

		// ignore second confirmation
		if (transaction.votes[msg.sender] == 1)
			throw;

		// register the vote
		transaction.voteCount += 1;
		transaction.votes[msg.sender] = 1;

		if (transaction.voteCount == partnerCount) {
			transaction.passed = true;
			TransactionPassed(_id, msg.sender, transaction.to, transaction.value, transaction.data);
		}
	}

	/// Executes a passed transaction
	function executeTransaction(bytes32 _id) onlyFunded onlyPartner external {

		var transaction = transactions[_id];

		// ignore transactions that have not passed yet
		if (!transaction.passed)
			throw;

		// ignore transactions that have already been sent
		if (transaction.sent)
			throw;

		// register the sent transaction
		transaction.sent = true;

		// send the transaction
		if (transactions[_id].to.call.value(transactions[_id].value)(transactions[_id].data)) {

			TransactionSent(_id, msg.sender, transaction.to, transaction.value, transaction.data);

			// clear the transaction structure to free memory
			delete transactions[_id];
		}
		else {
			// roll back if the call failed
			transaction.sent = false;
		}
	}

	/// Distribute ETH to a partner
	function distribute(address _partner, uint _amount) onlyDao external {

		// ignore invalid partners
		if (!isPartner(_partner))
			throw;

		partnerRecords[_partner].withdrawableAmount += _amount;
	}

	/// Distribute ETH evenly amongst all partners
	function distributeEvenly(uint _amount) onlyDao external {

		var payout = _amount / partnerCount;

		for (uint i = 0; i < partnerCount; i++) {
			partnerRecords[partners[i]].withdrawableAmount += payout;
	}

	/// Mark down partner's loan and make it available for withdrawal
	function repayLoan(address _partner, uint _amount) onlyDao external {

		// ignore invalid partners
		if (!partnerRecords[_partner].isPartner)
			throw;

		// ignore invalid amounts
		if (_amount > partnerRecords[_partner].loanBalance)
			throw;

		partnerRecords[_partner].loanBalance -= amount;
		partnerRecords[_partner].withdrawableAmount += amount;
	}

	/// Allow partner to withdraw funds marked as withdrawable
	function withdraw(uint _amount) onlyFunded onlyPartner external {

		// ignore requests for more than the amount allowed
		if (_amount > partnerRecords[msg.sender].withdrawableAmount)
			throw;

		// ignore requests for more than the available balance
		if (_amount > this.balance)
			throw;

		// mark the withdrawal as successful
		partnerRecords[msg.sender].withdrawableAmount -= _amount;

		// send the wei
		if (msg.sender.send(_amount)) {
			Withdrawal(msg.sender, _amount);
		}
		else {
			// roll back if the send failed
			partnerRecords[msg.sender].withdrawableAmount += _amount;
		}
	}

	/// Dissolve DAO and send the remaining ETH to a beneficiary
	function dissolve(address _beneficiary) onlyDao external {

		// ignore unset beneficiary
		if (_beneficiary == 0)
			throw;

		suicide(_beneficiary);
	}

	function isPartner(address _address) internal returns (bool) {
		return partnerRecords[_address].isPartner;
	}

}


StandingOrderDapp-7 Use safemath library

pragma solidity ^0.4.4;

import 'zeppelin/ownership/Ownable.sol';
import 'zeppelin/SafeMath.sol';

contract StandingOrder is Ownable, SafeMath {

    address public payee;        // The payee gets the money
    uint public startTime;       // Time the order was created
    uint public paymentInterval; // How often can payee claim paymentAmount
    uint public paymentAmount;   // How much can payee claim per period
    uint public claimedFunds;    // How much funds have been claimed already
    string public ownerLabel;    // Label managed by contract owner
    string public payeeLabel;    // Label managed by payee

    function StandingOrder(address _owner, address _payee, uint _paymentInterval, uint _paymentAmount, string _label) payable {
        // Sanity check parameters
        if (_paymentInterval < 1)
        throw;
        if (_paymentAmount < 1)
        throw;

        // override default behaviour of Ownable base contract
        // Explicitly set owner to _owner, as msg.sender is the StandingOrderFactory contract
        owner = _owner;

        payee = _payee;
        paymentInterval = _paymentInterval;
        paymentAmount = _paymentAmount;
        ownerLabel = _label;
        payeeLabel = _label;
        startTime = now;
    }

    modifier onlyPayee() {
        if (msg.sender != payee) {
            throw;
        }
        _;
    }

    /* Allow adding funds to existing order */
    function() payable {
        // TODO: Log entry
    }

    /* How much funds are owned by Payee but not yet withdrawn */
    function getUnclaimedFunds() constant returns (uint) {
        // sanity check
        if (now < startTime) {
            // bad miner trying to mess with block time?
            return 0;
        }

        // Calculate theoretical amount that payee should own right now
        uint age = safeSub(now, startTime);
        if (age == 0) {
            // order has just been created
            return 0;
        }
        uint completeIntervals = safeDiv(age, paymentInterval); // implicitly rounding down
        uint totalAmount = safeMul(completeIntervals, paymentAmount);

        // subtract already withdrawn funds
        uint entitledAmount = safeSub(totalAmount, claimedFunds);

        /* entitledAmount might be more than available balance. In this case
         * available balance is the limit */
        uint availableAmount = min256(entitledAmount, this.balance);

        return availableAmount;
    }

    /* How much funds are still owned by owner (not yet reserved for payee) */
    function getOwnerFunds() constant returns (uint) {
        return safeSub(this.balance, getUnclaimedFunds());
    }

    /* Collect payment */
    function collectFunds() {
        // only payee can collect funds
        if (msg.sender != payee) {
            throw;
        }

        uint amount = getUnclaimedFunds();

        if (amount <= 0) {
            // nothing to collect :-(
            throw;
        }

        // keep track of collected funds
        claimedFunds = safeAdd(claimedFunds, amount);

        if (payee.send(amount) == false)
            throw;
    }

    /* Returns remaining funds to owner.
     * Note that this does not return unclaimed funds - They
     * can only be claimed by payee!
     * The Standingorder is not yet cancelled, at any time owner can
     * fund it again!
     */
    function WithdrawOwnerFunds() onlyOwner {
        uint ownerFunds = getOwnerFunds();
        if (ownerFunds <= 0)
        throw;

        if (owner.send(ownerFunds) == false)
            throw;
        // TODO: Log event
    }

    /* Completely cancel this standingOrder */
    function Cancel() onlyOwner {
        // only possible when no funds are left in the contract
        if (this.balance > 0) {
            throw;
        }

        selfdestruct(owner);
    }

    function SetOwnerLabel(string _label) onlyOwner {
        ownerLabel = _label;
    }

    function SetPayeeLabel(string _label) onlyPayee {
        payeeLabel = _label;
    }
}

contract StandingOrderFactory {

    // keep track who issued standing orders
    mapping (address => StandingOrder[]) public standingOrdersByOwner;
    // keep track of payees of standing orders
    mapping (address => StandingOrder[]) public standingOrdersByPayee;

    // Events
    event LogOrderCreated(
        address orderAddress,
        address indexed owner,
        address indexed payee
    );

    // Create a new standing order.
    function createStandingOrder(address payee, uint rate, uint interval, string label) returns (StandingOrder) {
        StandingOrder so = new StandingOrder(msg.sender, payee, interval, rate, label);
        standingOrdersByOwner[msg.sender].push(so);
        standingOrdersByPayee[payee].push(so);
        LogOrderCreated(so, msg.sender, payee);
        return so;
    }

    function getNumOrdersByOwner() constant returns (uint) {
        return standingOrdersByOwner[msg.sender].length;
    }

    function getOwnOrderByIndex(uint index) constant returns (StandingOrder) {
        return standingOrdersByOwner[msg.sender][index];
    }

    function getNumOrdersByPayee() constant returns (uint) {
        return standingOrdersByPayee[msg.sender].length;
    }

    function getPaidOrderByIndex(uint index) constant returns (StandingOrder) {
        return standingOrdersByPayee[msg.sender][index];
    }
}

pragma solidity ^0.4.4;

import 'zeppelin/ownership/Ownable.sol';

contract StandingOrder is Ownable {

    address public payee;        // The payee gets the money
    uint public startTime;       // Time the order was created
    uint public paymentInterval; // How often can payee claim paymentAmount
    uint public paymentAmount;   // How much can payee claim per period
    uint public claimedFunds;    // How much funds have been claimed already
    string public ownerLabel;    // Label managed by contract owner
    string public payeeLabel;    // Label managed by payee

    function StandingOrder(address _owner, address _payee, uint _paymentInterval, uint _paymentAmount, string _label) payable {
        // Sanity check parameters
        if (_paymentInterval < 1)
            throw;
        if (_paymentAmount < 1)
            throw;

        // override default behaviour of Ownable base contract
        // Explicitly set owner to _owner, as msg.sender is the StandingOrderFactory contract
        owner = _owner;

        payee = _payee;
        paymentInterval = _paymentInterval;
        paymentAmount = _paymentAmount;
        ownerLabel = _label;
        payeeLabel = _label;
        startTime = now;
    }

    modifier onlyPayee() {
        if (msg.sender != payee) {
            throw;
        }
        _;
    }

    /* Allow adding funds to existing order */
    function() payable {
        // TODO: Log entry
    }

    /* How much funds are owned by Payee but not yet withdrawn */
    function getUnclaimedFunds() constant returns (uint) {
        // sanity check
        if (now < startTime) {
            // bad miner trying to mess with block time?
            return 0;
        }

        // Calculate theoretical amount that payee should own right now
        uint age = now - startTime;
        if (age == 0) {
            // order has just been created
            return 0;
        }

        uint completeIntervals = age / paymentInterval;
        // implicitly rounding down
        uint totalAmount = completeIntervals * paymentAmount;

        // subtract already withdrawn funds
        uint entitledAmount = totalAmount - claimedFunds;

        /* entitledAmount might be more than available balance. In this case
         * available balance is the limit */
        uint availableAmount = min(entitledAmount, this.balance);

        return availableAmount;
    }

    /* How much funds are still owned by owner (not yet reserved for payee) */
    function getOwnerFunds() constant returns (uint) {
        return this.balance - getUnclaimedFunds();
    }

    /* Collect payment */
    function collectFunds() {
        // only payee can collect funds
        if (msg.sender != payee) {
            throw;
        }

        uint amount = getUnclaimedFunds();

        if (amount <= 0) {
            // nothing to collect :-(
            throw;
        }

        claimedFunds += amount;
        if (payee.send(amount) == false)
        throw;
    }

    /* Returns remaining funds to owner.
     * Note that this does not return unclaimed funds - They
     * can only be claimed by payee!
     * The Standingorder is not yet cancelled, at any time owner can
     * fund it again!
     */
    function WithdrawOwnerFunds() onlyOwner {
        uint ownerFunds = getOwnerFunds();
        if (ownerFunds <= 0)
        throw;

        if (owner.send(ownerFunds) == false)
        throw;
        // TODO: Log event
    }

    /* Completely cancel this standingOrder */
    function Cancel() onlyOwner {

        // only possible when no funds are left in the contract
        if (this.balance > 0) {
            throw;
        }

        selfdestruct(owner);
    }

    function SetOwnerLabel(string _label) onlyOwner {
        ownerLabel = _label;
    }

    function SetPayeeLabel(string _label) onlyPayee {
        payeeLabel = _label;
    }

    function min(uint a, uint b) returns (uint) {
        if (a < b) return a;
        else return b;
    }
}

contract StandingOrderFactory {

    // keep track who issued standing orders
    mapping (address => StandingOrder[]) public standingOrdersByOwner;
    // keep track of payees of standing orders
    mapping (address => StandingOrder[]) public standingOrdersByPayee;

    // Events
    event LogOrderCreated(
    address orderAddress,
    address indexed owner,
    address indexed payee
    );

    // Create a new standing order.
    function createStandingOrder(address payee, uint rate, uint interval, string label) returns (StandingOrder) {
        StandingOrder so = new StandingOrder(msg.sender, payee, interval, rate, label);
        standingOrdersByOwner[msg.sender].push(so);
        standingOrdersByPayee[payee].push(so);
        LogOrderCreated(so, msg.sender, payee);
        return so;
    }

    function getNumOrdersByOwner() constant returns (uint) {
        return standingOrdersByOwner[msg.sender].length;
    }

    function getOwnOrderByIndex(uint index) constant returns (StandingOrder) {
        return standingOrdersByOwner[msg.sender][index];
    }

    function getNumOrdersByPayee() constant returns (uint) {
        return standingOrdersByPayee[msg.sender].length;
    }

    function getPaidOrderByIndex(uint index) constant returns (StandingOrder) {
        return standingOrdersByPayee[msg.sender][index];
    }
}


minor changes and events

minor changes and events

pragma solidity ^0.4.9;

contract Workflow {

// Data types:

    // enums are zero indexed - FYI.
    enum RelationType {
        Include, Exclude, Response, Condition, Milestone
    }

    struct ExternalRelation {
        uint32 id;
        address ext;
        RelationType relationType;
    }

    struct Activity {
        // State
        bytes32 name;
        bool included;
        bool executed;
        bool pending;

        // Outgoing relations:
        uint32[] include;
        uint32[] exclude;
        uint32[] response;

        // Incoming relations:
        uint32[] condition;
        uint32[] milestone;

        // Access rights:
        address[] whitelist;

        // External relations:
        ExternalRelation[] extRel; // could be made into several lists if large
    }

// Workflow data and creation:

    event Execution(address sender, uint32 id, bool successful);
    event ExternalStateEdit(address sender, uint32 id, RelationType typ, bool successful);
    event ActivityAdded(address sender, uint32 id);
    event RelationAdded(address sender, uint32 fromId, uint32 toId, RelationType typ);
    Activity[] activities;
    address owner;
    bytes32 name;

    /// names: array of activity names, where names[i] is the name of activity with id i
    /// included: array of activity included state, where included[i] is the included state of activity with id i
    /// executed: array of activity executed state, where executed[i] is the executed state of activity with id i
    /// pending: array of activity pending state, where pending[i] is the pending state of activity with id i
    /// include: array of include relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity
    /// exclude: array of exclude relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity
    /// response: array of response relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity
    /// condition: array of condition relations. The array is expected to have a structure such that i % 2 = 0 is the TO activity and i + 1 is the FROM activity
    /// milestone: array of milestone relations. The array is expected to have a structure such that i % 2 = 0 is the TO activity and i + 1 is the FROM activity
    /// localId: array of ids where the following external relation data should be put. Expected to be ordered such that localId[i] is id of the activity where externalId[i], workflowAddress[i] and relationType[i] is relevant.
    /// externalId: array of ids of activities on other workflow contracts. Ordered such that externalId[i] is activity i on workflowAddress[i]
    /// workflowAddress: array of addresses to other workflow contracts.
    /// relationType: array of external relation type enums.
    function Workflow (
        bytes32 wfName,
        bytes32[] names,
        bool[] included,
        bool[] executed,
        bool[] pending,
        uint32[] include,
        uint32[] exclude,
        uint32[] response,
        uint32[] spawn,
        uint32[] condition,
        uint32[] milestone,
        // External relation data:
        uint32[] localId,
        uint32[] externalId,
        address[] workflowAddress,
        uint32[] relationType
    ) {
        name = wfName;
        owner = msg.sender;

        activities.length = names.length;

        for (var i = 0; i < names.length; i++) {
            activities[i].name      = names[i];
            activities[i].included  = included[i];
            activities[i].executed  = executed[i];
            activities[i].pending   = pending[i];
        }

        // We expect all relation arrays are formed such that i % 2 = 0 is where the data is to be stored, and i+1 is the data that is to be stored there
        for (i = 0; i < include.length; i++)
            activities[include[i++]].include.push(include[i]);
        for (i = 0; i < exclude.length; i++)
            activities[exclude[i++]].exclude.push(exclude[i]);
        for (i = 0; i < response.length; i++)
            activities[response[i++]].response.push(response[i]);
        for (i = 0; i < condition.length; i++)
            activities[condition[i++]].condition.push(condition[i]);
        for (i = 0; i < milestone.length; i++)
            activities[milestone[i++]].milestone.push(milestone[i]);

        // External relation creation
        for (i = 0; i < localId.length; i++)
            activities[localId[i]].extRel.push(ExternalRelation(externalId[i], workflowAddress[i], RelationType(relationType[i])));
    }

// Internal functions:

    function logFail(uint32 id) private {
        Execution(msg.sender, id, false);
    }

    function authorize(uint32 actId) private {
        if(activities[actId].whitelist.length > 0) {
            for (var i = 0; i < activities[actId].whitelist.length; i++)
                if(activities[actId].whitelist[i] == msg.sender)
                    break;

            if(i == activities[actId].whitelist.length){
                throw;
            }
        }
    }

// External functions:

    function execute(uint32 id) {
        // Check that activity is in executable state
        Activity memory a = activities[id];

        authorize(id);

        if(!a.included){
            logFail(id);
            return;
        }

        for (var i = 0; i < a.condition.length; i++)
            if(!activities[a.condition[i]].executed && activities[a.condition[i]].included) {
                logFail(id);
                return;
            }

        for (i = 0; i < a.milestone.length; i++)
            if(activities[a.milestone[i]].pending && activities[a.milestone[i]].included) {
                logFail(id);
                return;
            }

        // External checks
        for (i = 0; i < a.extRel.length; i++) {
            if(a.extRel[i].relationType == RelationType.Condition || a.extRel[i].relationType == RelationType.Milestone){
                // Maybe check if wf address is valid?
                Workflow wf = Workflow(a.extRel[i].ext);
                if(!wf.relationFulfilled(a.extRel[i].id, a.extRel[i].relationType)) {
                    logFail(id);
                    return;
                }
            }
        }

        // Effects on other activities
        for (i = 0; i < a.include.length; i++)
            activities[a.include[i]].included = true;
        for (i = 0; i < a.exclude.length; i++)
            activities[a.exclude[i]].included = false;
        for (i = 0; i < a.response.length; i++)
            activities[a.response[i]].pending = true;

        // External state changes
        for (i = 0; i < a.extRel.length; i++){
            if( a.extRel[i].relationType == RelationType.Include ||
                a.extRel[i].relationType == RelationType.Exclude ||
                a.extRel[i].relationType == RelationType.Response) {
                    wf = Workflow(a.extRel[i].ext);
                    wf.externalStateChange(a.extRel[i].id, a.extRel[i].relationType);
            }
        }

        // Effect on executing activity - reentrancy issues!?
        a.executed = true;
        a.pending = false;
        Execution(msg.sender, id, true);

    }

    // Add a new authorized pub key to specified activity
    function addToWhitelist(uint32 id, address actor){
        if(msg.sender != owner)
            throw;

        activities[id].whitelist.push(actor);
    }

    // Add a new external relation on activity id
    function addExternalRelation (uint32 actId, address workflow, RelationType relTyp) {
        authorize(actId);

        activities[actId].extRel.push(ExternalRelation(actId, workflow, relTyp));
    }

    function addActivities (
        bytes32[] names,
        bool[] included,
        bool[] executed,
        bool[] pending,
        uint32[] relations, // even ids are fromIds, odd are toIds
        uint32[] internalRelations, // even ids are fromIds, odd are toIds
        RelationType[] relTyps, // expected to have size relations.length /2
        RelationType[] intRelTyps // expected to have size internalRelations.length /2
    ) returns (uint32[]) {
        uint32[] memory ids = new uint32[](names.length);

        for(var i = 0; i < names.length; i++) {
            uint32 id = uint32(activities.length++);
            activities[id].name = name;
            activities[id].included = included[i];
            activities[id].executed = executed[i];
            activities[id].pending = pending[i];
            ids[i] = id;

            ActivityAdded(msg.sender, id);
        }

        for(i = 0; i < relations.length; i++)
            addRelation(relations[i++], relations[i], relTyps[(i-1) / 2]);
        for(i = 0; i < internalRelations.length; i++)
            addRelation(ids[internalRelations[i++]], ids[internalRelations[i]], intRelTyps[(i-1) / 2]);

        return ids;
    }

    function addRelation (uint32 fromId, uint32 toId, RelationType relTyp) {
        if(fromId >= activities.length || toId >= activities.length)
            throw;

        if(relTyp == RelationType.Include) activities[fromId].include.push(toId);
        else if(relTyp == RelationType.Exclude) activities[fromId].exclude.push(toId);
        else if(relTyp == RelationType.Response) activities[fromId].response.push(toId);
        else if(relTyp == RelationType.Condition) activities[toId].condition.push(fromId);
        else if(relTyp == RelationType.Milestone) activities[toId].milestone.push(fromId);

        RelationAdded(msg.sender, fromId, toId, relTyp);
    }

    function addActivity(
        bytes32 name,
        bool included,
        bool executed,
        bool pending,
        uint32[] include,
        uint32[] exclude,
        uint32[] response,
        uint32[] condition,
        uint32[] milestone,
        address[] whitelist
    ) returns (uint32) {
        uint32 id = uint32(activities.length++);
        activities[id].name = name;
        activities[id].included = included;
        activities[id].executed = executed;
        activities[id].pending = pending;
        activities[id].include = include;
        activities[id].exclude = exclude;
        activities[id].response = response;
        activities[id].condition = condition;
        activities[id].milestone = milestone;
        activities[id].whitelist = whitelist;
        ActivityAdded(msg.sender, id);
        return id;
    }

    // Selfdestruct
    function sudoku() {
        if(msg.sender != owner)
            throw;

        selfdestruct(owner);
    }

// Functions for external activity state interaction, to enable interworkflow communication:

    // External state change call
    function externalStateChange (uint32 actId, RelationType relTyp) {

        // Authorization: Assuming that calling contract address is in activity whitelist
        authorize(actId);

        // Change local state
        if(relTyp == RelationType.Include) activities[actId].included = true;
        if(relTyp == RelationType.Exclude) activities[actId].included = false;
        if(relTyp == RelationType.Response) activities[actId].pending = true;
        ExternalStateEdit(msg.sender, actId, relTyp, true);

    }

    // returns true if calling activity is executable according to specified relation type
    function relationFulfilled (uint32 actId, RelationType relTyp) returns (bool) {

        // Condition logic
        if(relTyp == RelationType.Condition)
            return !activities[actId].included || activities[actId].executed;

        // Milestone logic
        else if(relTyp == RelationType.Milestone)
            return !activities[actId].included || !activities[actId].pending;

        // Default case given non-valid relation
        return false;
    }

}

pragma solidity ^0.4.9;

contract Workflow {

// Data types:

    // enums are zero indexed - FYI.
    enum RelationType {
        Include, Exclude, Response, Condition, Milestone
    }

    struct ExternalRelation {
        uint32 id;
        address ext;
        RelationType relationType;
    }

    struct Activity {
        // State
        bytes32 name;
        bool included;
        bool executed;
        bool pending;

        // Outgoing relations:
        uint32[] include;
        uint32[] exclude;
        uint32[] response;

        // Incoming relations:
        uint32[] condition;
        uint32[] milestone;

        // Access rights:
        address[] whitelist;

        // External relations:
        ExternalRelation[] extRel; // could be made into several lists if large
    }

// Workflow data and creation:

    event Execution(address sender, uint32 id, bool successful);
    event ExternalStateEdit(address sender, uint32 id, RelationType typ, bool successful);
    event ActivityAdded(address sender, uint32 id);
    Activity[] activities;
    address owner;
    bytes32 name;

    /// names: array of activity names, where names[i] is the name of activity with id i
    /// included: array of activity included state, where included[i] is the included state of activity with id i
    /// executed: array of activity executed state, where executed[i] is the executed state of activity with id i
    /// pending: array of activity pending state, where pending[i] is the pending state of activity with id i
    /// include: array of include relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity
    /// exclude: array of exclude relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity
    /// response: array of response relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity
    /// spawn: array of spawn relations. The array is expected to have a structure such that i % 2 = 0 is the FROM activity and i + 1 is the TO activity, which is expected to have isSpawn=true
    /// condition: array of condition relations. The array is expected to have a structure such that i % 2 = 0 is the TO activity and i + 1 is the FROM activity
    /// milestone: array of milestone relations. The array is expected to have a structure such that i % 2 = 0 is the TO activity and i + 1 is the FROM activity
    /// localId: array of ids where the following external relation data should be put. Expected to be ordered such that localId[i] is id of the activity where externalId[i], workflowAddress[i] and relationType[i] is relevant.
    /// externalId: array of ids of activities on other workflow contracts. Ordered such that externalId[i] is activity i on workflowAddress[i]
    /// workflowAddress: array of addresses to other workflow contracts.
    /// relationType: array of external relation type enums.
    function Workflow (
        bytes32 wfName,
        bytes32[] names,
        bool[] included,
        bool[] executed,
        bool[] pending,
        uint32[] include,
        uint32[] exclude,
        uint32[] response,
        uint32[] spawn,
        uint32[] condition,
        uint32[] milestone,
        // External relation data:
        uint32[] localId,
        uint32[] externalId,
        address[] workflowAddress,
        uint32[] relationType
    ) {
        name = wfName;
        owner = msg.sender;

        activities.length = names.length;

        for (var i = 0; i < names.length; i++) {
            activities[i].name      = names[i];
            activities[i].included  = included[i];
            activities[i].executed  = executed[i];
            activities[i].pending   = pending[i];
        }

        // We expect all relation arrays are formed such that i % 2 = 0 is where the data is to be stored, and i+1 is the data that is to be stored there
        for (i = 0; i < include.length; i++)
            activities[include[i++]].include.push(include[i]);
        for (i = 0; i < exclude.length; i++)
            activities[exclude[i++]].exclude.push(exclude[i]);
        for (i = 0; i < response.length; i++)
            activities[response[i++]].response.push(response[i]);
        for (i = 0; i < condition.length; i++)
            activities[condition[i++]].condition.push(condition[i]);
        for (i = 0; i < milestone.length; i++)
            activities[milestone[i++]].milestone.push(milestone[i]);

        // External relation creation
        for (i = 0; i < localId.length; i++)
            activities[localId[i]].extRel.push(ExternalRelation(externalId[i], workflowAddress[i], RelationType(relationType[i])));
    }

// Internal functions:

    function logFail(uint32 id) private {
        Execution(msg.sender, id, false);
    }

    function authorize(uint32 actId) private {
        if(activities[actId].whitelist.length > 0) {
            for (var i = 0; i < activities[actId].whitelist.length; i++)
                if(activities[actId].whitelist[i] == msg.sender)
                    break;

            if(i == activities[actId].whitelist.length){
                throw;
            }
        }
    }

// External functions:

    function execute(uint32 id) {
        // Check that activity is in executable state
        Activity memory a = activities[id];

        authorize(id);

        if(!a.included){
            logFail(id);
            return;
        }

        for (var i = 0; i < a.condition.length; i++)
            if(!activities[a.condition[i]].executed && activities[a.condition[i]].included) {
                logFail(id);
                return;
            }

        for (i = 0; i < a.milestone.length; i++)
            if(activities[a.milestone[i]].pending && activities[a.milestone[i]].included) {
                logFail(id);
                return;
            }

        // External checks
        for (i = 0; i < a.extRel.length; i++) {
            if(a.extRel[i].relationType == RelationType.Condition || a.extRel[i].relationType == RelationType.Milestone){
                // Maybe check if wf address is valid?
                Workflow wf = Workflow(a.extRel[i].ext);
                if(!wf.relationFulfilled(a.extRel[i].id, a.extRel[i].relationType)) {
                    logFail(id);
                    return;
                }
            }
        }

        // Effects on other activities
        for (i = 0; i < a.include.length; i++)
            activities[a.include[i]].included = true;
        for (i = 0; i < a.exclude.length; i++)
            activities[a.exclude[i]].included = false;
        for (i = 0; i < a.response.length; i++)
            activities[a.response[i]].pending = true;

        // External state changes
        for (i = 0; i < a.extRel.length; i++){
            if( a.extRel[i].relationType == RelationType.Include ||
                a.extRel[i].relationType == RelationType.Exclude ||
                a.extRel[i].relationType == RelationType.Response) {
                    wf = Workflow(a.extRel[i].ext);
                    wf.externalStateChange(a.extRel[i].id, a.extRel[i].relationType);
            }
        }

        // Effect on executing activity - reentrancy issues!?
        a.executed = true;
        a.pending = false;
        Execution(msg.sender, id, true);

    }

    // Add a new authorized pub key to specified activity
    function addToWhitelist(uint32 id, address actor){
        if(msg.sender != owner)
            throw;

        activities[id].whitelist.push(actor);
    }

    // Add a new external relation on activity id
    function addExternalRelation (uint32 actId, address workflow, RelationType relTyp) {
        authorize(actId);

        activities[actId].extRel.push(ExternalRelation(actId, workflow, relTyp));
    }

    function addActivities (
        bytes32[] names,
        bool[] included,
        bool[] executed,
        bool[] pending,
        uint32[] relations, // even ids are fromIds, odd are toIds
        uint32[] internalRelations, // even ids are fromIds, odd are toIds
        RelationType[] relTyps, // expected to have size relations.length /2
        RelationType[] intRelTyps // expected to have size internalRelations.length /2
    ) returns (uint32[]) {
        uint32[] memory ids = new uint32[](names.length);

        for(var i = 0; i < names.length; i++) {
            uint32 id = uint32(activities.length++);
            activities[id].name = name;
            activities[id].included = included[i];
            activities[id].executed = executed[i];
            activities[id].pending = pending[i];
            ids[i] = id;
        }

        for(i = 0; i < relations.length; i++)
            addRelation(relations[i++], relations[i], relTyps[(i-1) / 2]);
        for(i = 0; i < internalRelations.length; i++)
            addRelation(ids[internalRelations[i++]], ids[internalRelations[i]], intRelTyps[(i-1) / 2]);

        return ids;
    }

    function addRelation (uint32 fromId, uint32 toId, RelationType relTyp) {
        if(fromId >= activities.length || toId >= activities.length)
            throw;

        if(relTyp == RelationType.Include) activities[fromId].include.push(toId);
        else if(relTyp == RelationType.Exclude) activities[fromId].exclude.push(toId);
        else if(relTyp == RelationType.Response) activities[fromId].response.push(toId);
        else if(relTyp == RelationType.Condition) activities[toId].condition.push(fromId);
        else if(relTyp == RelationType.Milestone) activities[toId].milestone.push(fromId);
    }
    function addActivity(
        bytes32 name,
        bool included,
        bool executed,
        bool pending,
        uint32[] include,
        uint32[] exclude,
        uint32[] response,
        uint32[] condition,
        uint32[] milestone,
        address[] whitelist
    ) returns (uint32) {
        uint32 id = uint32(activities.length++);
        activities[id].name = name;
        activities[id].included = included;
        activities[id].executed = executed;
        activities[id].pending = pending;
        activities[id].include = include;
        activities[id].exclude = exclude;
        activities[id].response = response;
        activities[id].condition = condition;
        activities[id].milestone = milestone;
        activities[id].whitelist = whitelist;
        return id;
    }

    // Selfdestruct
    function sudoku() {
        if(msg.sender != owner)
            throw;

        selfdestruct(owner);
    }

// Functions for external activity state interaction, to enable interworkflow communication:

    // External state change call
    function externalStateChange (uint32 actId, RelationType relTyp) {

        // Authorization: Assuming that calling contract address is in activity whitelist
        authorize(actId);

        // Change local state
        if(relTyp == RelationType.Include) activities[actId].included = true;
        if(relTyp == RelationType.Exclude) activities[actId].included = false;
        if(relTyp == RelationType.Response) activities[actId].pending = true;
        ExternalStateEdit(msg.sender, actId, relTyp, true);

    }

    // returns true if calling activity is executable according to specified relation type
    function relationFulfilled (uint32 actId, RelationType relTyp) returns (bool) {

        // Condition logic
        if(relTyp == RelationType.Condition)
            return !activities[actId].included || activities[actId].executed;

        // Milestone logic
        else if(relTyp == RelationType.Milestone)
            return !activities[actId].included || !activities[actId].pending;

        // Default case given non-valid relation
        return false;
    }

}


Proportionally divide ether in withdraw contract

pragma solidity ^0.4.11;

contract Token {
	uint256 public totalSupply;

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

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

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

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

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

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

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

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

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

contract Withdraw {
	Token public token;

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

	function () payable {}

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

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

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

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

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

pragma solidity ^0.4.11;

contract Token {
	uint256 public totalSupply;

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

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

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

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

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

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

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

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

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

contract Withdraw {
	Token public token;

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

	function () payable {}

	function withdraw() {
		require(token.sealed());
		require(token.balanceOf(msg.sender) > 0);
		uint amount = token.balanceOf(msg.sender);
		if (!token.transferFrom(msg.sender, this, amount) || !msg.sender.send(amount)) {
			throw;
		}
	}
}

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

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

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

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


AssertInt.sol

AssertInt.sol

pragma solidity >= 0.4.15 < 0.6.0;

library AssertInt {

    uint8 constant ZERO = uint8(byte('0'));
    uint8 constant A = uint8(byte('a'));

    byte constant MINUS = byte('-');

    /*
        Event: TestEvent

        Fired when an assertion is made.

        Params:
            result (bool) - Whether or not the assertion holds.
            message (string) - A message to display if the assertion does not hold.
    */
    event TestEvent(bool indexed result, string message);

    // ************************************** int **************************************

    /*
        Function: equal(int)

        Assert that two (256 bit) signed integers are equal.

        : A == B

        Params:
            A (int) - The first int.
            B (int) - The second int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function equal(int a, int b, string memory message) public returns (bool result) {
        result = (a == b);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(a, "Tested"), _tag(b, "Against"), message));
    }

    /*
        Function: notEqual(int)

        Assert that two (256 bit) signed integers are not equal.

        : A != B

        Params:
            A (int) - The first int.
            B (int) - The second int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function notEqual(int a, int b, string memory message) public returns (bool result) {
        result = (a != b);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(a, "Tested"), _tag(b, "Against"), message));
    }

    /*
        Function: isAbove(int)

        Assert that the int 'A' is greater than the int 'B'.

        : A > B

        Params:
            A (int) - The first int.
            B (int) - The second int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function isAbove(int a, int b, string memory message) public returns (bool result) {
        result = (a > b);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(a, "Tested"), _tag(b, "Against"), message));
    }

    /*
        Function: isAtLeast(int)

        Assert that the int 'A' is greater than or equal to the int 'B'.

        : A >= B

        Params:
            A (int) - The first int.
            B (int) - The second int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function isAtLeast(int a, int b, string memory message) public returns (bool result) {
        result = (a >= b);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(a, "Tested"), _tag(b, "Against"), message));
    }

    /*
        Function: isBelow(int)

        Assert that the int 'A' is lesser than the int 'B'.

        : A < B

        Params:
            A (int) - The first int.
            B (int) - The second int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function isBelow(int a, int b, string memory message) public returns (bool result) {
        result = (a < b);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(a, "Tested"), _tag(b, "Against"), message));
    }

    /*
        Function: isAtMost(int)

        Assert that the int 'A' is lesser than or equal to the int 'B'.

        : A <= B

        Params:
            A (int) - The first int.
            B (int) - The second int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function isAtMost(int a, int b, string memory message) public returns (bool result) {
        result = (a <= b);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(a, "Tested"), _tag(b, "Against"), message));
    }

    /*
        Function: isZero(int)

        Assert that a (256 bit) signed integer is 0.

        : number == 0

        Params:
            number (int) - The int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function isZero(int number, string memory message) public returns (bool result) {
        result = (number == 0);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(number, "Tested"), message));
    }

    /*
        Function: isNotZero(int)

        Assert that a (256 bit) signed integer is not 0.

        : number != 0

        Params:
            number (int) - The int.
            message (string) - A message that is sent if the assertion fails.

        Returns:
            result (bool) - The result.
    */
    function isNotZero(int number, string memory message) public returns (bool result) {
        result = (number != 0);
        if (result)
            _report(result, message);
        else
            _report(result, _appendTagged(_tag(number, "Tested"), message));
    }

    /******************************** internal ********************************/

        /*
            Function: _report

            Internal function for triggering <TestEvent>.

            Params:
                result (bool) - The test result (true or false).
                message (string) - The message that is sent if the assertion fails.
        */
    function _report(bool result, string memory message) internal {
        if(result)
            emit TestEvent(true, "");
        else
            emit TestEvent(false, message);
    }

    /*
        Function: _itoa

        Convert a signed integer to a string. Negative numbers gets a '-' in front, e.g. "-54".

        Params:
            n (int) - The integer.
            radix (uint8) - A number between 2 and 16 (inclusive). Characters used are 0-9,a-f

        Returns:
            result (string) - The resulting string.
    */
    function _itoa(int n, uint8 radix) internal pure returns (string memory) {
        if (n == 0 || radix < 2 || radix > 16)
            return '0';
        bytes memory bts = new bytes(256);
        uint i;
        bool neg = false;
        if (n < 0) {
            n = -n;
            neg = true;
        }
        while (n > 0) {
            bts[i++] = _utoa(uint8(n % radix)); // Turn it to ascii.
            n /= radix;
        }
        // Reverse
        uint size = i;
        uint j = 0;
        bytes memory rev;
        if (neg) {
            size++;
            j = 1;
            rev = new bytes(size);
            rev[0] = MINUS;
        }
        else
            rev = new bytes(size);

        for (; j < size; j++)
            rev[j] = bts[size - j - 1];
        return string(rev);
    }

    /*
        Function: _utoa(uint8)

        Convert an unsigned 8-bit integer to its ASCII byte representation. Numbers 0-9 are converted to '0'-'9',
        numbers 10-16 to 'a'-'f'. Numbers larger then 16 return the null byte.

        Params:
            u (uint8) - The unsigned 8-bit integer.

        Returns:
            result (string) - The ASCII byte.
    */
    function _utoa(uint8 u) internal pure returns (byte) {
        if (u < 10)
            return byte(u + ZERO);
        else if (u < 16)
            return byte(u - 10 + A);
        else
            return 0;
    }

    /*
    function htoa(address addr) constant returns (string) {
        bytes memory bts = new bytes(40);
        bytes20 addrBts = bytes20(addr);
        for (uint i = 0; i < 20; i++) {
            bts[2*i] = addrBts[i] % 16;
            bts[2*i + 1] = (addrBts[i] / 16) % 16;
        }
        return string(bts);
    }
    */

    /*
        Function: _tag(string)

        Add a tag to a string. The 'value' and 'tag' strings are returned on the form "tag: value".

        Params:
            value (string) - The value.
            tag (string) - The tag.

        Returns:
            result (string) - "tag: value"
    */
    function _tag(string memory value, string memory tag) internal pure returns (string memory) {

        bytes memory valueB = bytes(value);
        bytes memory tagB = bytes(tag);

        uint vl = valueB.length;
        uint tl = tagB.length;

        bytes memory newB = new bytes(vl + tl + 2);

        uint i;
        uint j;

        for (i = 0; i < tl; i++)
            newB[j++] = tagB[i];
        newB[j++] = ':';
        newB[j++] = ' ';
        for (i = 0; i < vl; i++)
            newB[j++] = valueB[i];

        return string(newB);
    }

    /*
        Function: _tag(int)

        Add a tag to an int.

        Params:
            value (int) - The value.
            tag (string) - The tag.

        Returns:
            result (string) - "tag: _itoa(value)"
    */
    function _tag(int value, string memory tag) internal pure returns (string memory) {
        string memory nstr = _itoa(value, 10);
        return _tag(nstr, tag);
    }

    /*
        Function: _appendTagged(string)

        Append a tagged value to a string.

        Params:
            tagged (string) - The tagged value.
            str (string) - The string.

        Returns:
            result (string) - "str (tagged)"
    */
    function _appendTagged(string memory tagged, string memory str) internal pure returns (string memory) {

        bytes memory taggedB = bytes(tagged);
        bytes memory strB = bytes(str);

        uint sl = strB.length;
        uint tl = taggedB.length;

        bytes memory newB = new bytes(sl + tl + 3);

        uint i;
        uint j;

        for (i = 0; i < sl; i++)
            newB[j++] = strB[i];
        newB[j++] = ' ';
        newB[j++] = '(';
        for (i = 0; i < tl; i++)
            newB[j++] = taggedB[i];
        newB[j++] = ')';

        return string(newB);
    }

    /*
        Function: _appendTagged(string, string)

        Append two tagged values to a string.

        Params:
            tagged0 (string) - The first tagged value.
            tagged1 (string) - The second tagged value.
            str (string) - The string.

        Returns:
            result (string) - "str (tagged0, tagged1)"
    */
    function _appendTagged(string memory tagged0, string memory tagged1, string memory str) internal pure returns (string memory) {

        bytes memory tagged0B = bytes(tagged0);
        bytes memory tagged1B = bytes(tagged1);
        bytes memory strB = bytes(str);

        uint sl = strB.length;
        uint t0l = tagged0B.length;
        uint t1l = tagged1B.length;

        bytes memory newB = new bytes(sl + t0l + t1l + 5);

        uint i;
        uint j;

        for (i = 0; i < sl; i++)
            newB[j++] = strB[i];
        newB[j++] = ' ';
        newB[j++] = '(';
        for (i = 0; i < t0l; i++)
            newB[j++] = tagged0B[i];
        newB[j++] = ',';
        newB[j++] = ' ';
        for (i = 0; i < t1l; i++)
            newB[j++] = tagged1B[i];
        newB[j++] = ')';

        return string(newB);
    }
}

error: pathspec 'packages/truffle-core/lib/testing/AssertInt.sol' did not match any file(s) known to git


add owner example

add owner example

pragma solidity ^0.4.2;

contract EtherBank {

    /* Ether  */
    mapping (address => uint) public etherBalanceOf;
    // address public owner;

    /* Constructor */
    function EtherBank(){
        // owner = msg.sender;
    }

     /* ------- Utilities:  */
    function weiToEther(uint _wei) internal returns (uint){
         return _wei / 1000000000000000000;
    }

    function etherToWei(uint _ether) internal returns (uint){
         return _ether * 1000000000000000000;
    }

     /* ------------- working with Ether in contract */

    //
    event DepositEther(address sender, uint value);
    function depositEther() payable {

        uint weiToDeposit = msg.value;

        uint etherToDeposit = weiToEther(weiToDeposit);

        etherBalanceOf[msg.sender] += etherToDeposit;

        DepositEther(msg.sender, etherToDeposit);

     } // end of depositEther()

    event Withdrawal(address addressee, uint value, string message);
    //
    function withdraw(uint _ethSumToWithdraw) returns(string){

            var message = "result";

            if (_ethSumToWithdraw >= etherBalanceOf[msg.sender] ){
                 message = "withdrawal: insufficient funds";
                 Withdrawal(msg.sender, _ethSumToWithdraw, message);
                 return message;
             }

             // (!!!) see:
             // https://blog.ethereum.org/2016/06/10/smart-contract-security/
             //

             etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] - _ethSumToWithdraw;
             //
             if (
                 !msg.sender.send(etherToWei(_ethSumToWithdraw))
                 ){

                 etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] + _ethSumToWithdraw;
                 message = "withdrawal: failed";
                 Withdrawal(msg.sender, _ethSumToWithdraw, message);
                 return message;

             } else {

                 message = "withdrawal: success";
                 Withdrawal(msg.sender, _ethSumToWithdraw, message);
                 return message;

             }
    } // end of withdraw()

    // function ownerWithdraw(uint _sum){
    //     if (msg.sender == owner){
    //         msg.sender.send(etherToWei(_sum));
    //     }
    // }

} // end of EtherBank

pragma solidity ^0.4.2;

contract EtherBank {

    /* Ether  */
     mapping (address => uint) public etherBalanceOf;

     /* Constructor */
     function EtherBank(){}

     /* ------- Utilities:  */
     function weiToEther(uint _wei) internal returns (uint){
         return _wei / 1000000000000000000;
     }

     function etherToWei(uint _ether) internal returns (uint){
         return _ether * 1000000000000000000;
     }

     /* ------------- working with Ether in contract */

    //
    event DepositEther(address sender, uint value);
    function depositEther() payable {

        uint weiToDeposit = msg.value;

        uint etherToDeposit = weiToEther(weiToDeposit);

        etherBalanceOf[msg.sender] += etherToDeposit;

        DepositEther(msg.sender, etherToDeposit);

     } // end of depositEther()

    event Withdrawal(address addressee, uint value, string message);
    //
    function withdraw(uint _ethSumToWithdraw) returns(string){

            var message = "result";

            if (_ethSumToWithdraw >= etherBalanceOf[msg.sender] ){
                 message = "withdrawal: insufficient funds";
                 Withdrawal(msg.sender, _ethSumToWithdraw, message);
                 return message;
             }
             // (!!!) see:
             // https://blog.ethereum.org/2016/06/10/smart-contract-security/
             //

             etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] - _ethSumToWithdraw;
             //
             if (!msg.sender.send(etherToWei(_ethSumToWithdraw))){

                 etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] + _ethSumToWithdraw;
                 message = "withdrawal: failed";
                 Withdrawal(msg.sender, _ethSumToWithdraw, message);
                 return message;

             } else {

                 message = "withdrawal: success";
                 Withdrawal(msg.sender, _ethSumToWithdraw, message);
                 return message;

             }
    } // end of withdraw()

} // end of EtherBank