Updated cup

Updated cup

pragma solidity ^0.4.4;

// ERC20 token interface is implemented only partially.
// Token transfer is prohibited due to spec (see PRESALE-SPEC.md),
// hence some functions are left undefined:
//  - transfer, transferFrom,
//  - approve, allowance.

contract PresaleToken {

    /// @dev Constructor
    /// @param _tokenManager Token manager address.
    function PresaleToken(address _tokenManager) {
        tokenManager = _tokenManager;
    }

    /*/
     *  Constants
    /*/

    string public name = "SONM Presale Token";
    string public symbol = "SPT";
    uint   public decimals = 18;

    uint public PRICE = 200; // 200 SPT per Ether

    //  price
    // Cup is 10 000 ETH
    // ETH price ~50$ for 28.03.2017
    // Cup in $ is ~ 500 000$

    uint public TOKEN_SUPPLY_LIMIT = 6060000 * (1 ether / 1 wei);

    /*/
     *  Token state
    /*/

    enum Phase {
        Created,
        Running,
        Paused,
        Migrating,
        Migrated
    }

    Phase public currentPhase = Phase.Created;
    uint public totalSupply = 0; // amount of tokens already sold

    // Token manager has exclusive priveleges to call administrative
    // functions on this contract.
    address public tokenManager;
    // Crowdsale manager has exclusive priveleges to burn presale tokens.
    address public crowdsaleManager;

    mapping (address => uint256) private balance;

    modifier onlyTokenManager()     { if(msg.sender != tokenManager) throw; _; }
    modifier onlyCrowdsaleManager() { if(msg.sender != crowdsaleManager) throw; _; }

    /*/
     *  Events
    /*/

    event LogBuy(address indexed owner, uint value);
    event LogBurn(address indexed owner, uint value);
    event LogPhaseSwitch(Phase newPhase);

    /*/
     *  Public functions
    /*/

    function() payable {
        buyTokens(msg.sender);
    }

    /// @dev Lets buy you some tokens.
    function buyTokens(address _buyer) public payable {
        // Available only if presale is running.
        if(currentPhase != Phase.Running) throw;

        if(msg.value == 0) throw;
        uint newTokens = msg.value * PRICE;
        if (totalSupply + newTokens > TOKEN_SUPPLY_LIMIT) throw;
        balance[_buyer] += newTokens;
        totalSupply += newTokens;
        LogBuy(_buyer, newTokens);
    }

    /// @dev Returns number of tokens owned by given address.
    /// @param _owner Address of token owner.
    function burnTokens(address _owner) public
        onlyCrowdsaleManager
    {
        // Available only during migration phase
        if(currentPhase != Phase.Migrating) throw;

        uint tokens = balance[_owner];
        if(tokens == 0) throw;
        balance[_owner] = 0;
        totalSupply -= tokens;
        LogBurn(_owner, tokens);

        // Automatically switch phase when migration is done.
        if(totalSupply == 0) {
            currentPhase = Phase.Migrated;
            LogPhaseSwitch(Phase.Migrated);
        }
    }

    /// @dev Returns number of tokens owned by given address.
    /// @param _owner Address of token owner.
    function balanceOf(address _owner) constant returns (uint256) {
        return balance[_owner];
    }

    /*/
     *  Administrative functions
    /*/

    function setPresalePhase(Phase _nextPhase) public
        onlyTokenManager
    {
        bool canSwitchPhase
            =  (currentPhase == Phase.Created && _nextPhase == Phase.Running)
            || (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
                // switch to migration phase only if crowdsale manager is set
            || ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
                && _nextPhase == Phase.Migrating
                && crowdsaleManager != 0x0)
            || (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
                // switch to migrated only if everyting is migrated
            || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
                && totalSupply == 0);

        if(!canSwitchPhase) throw;
        currentPhase = _nextPhase;
        LogPhaseSwitch(_nextPhase);
    }

    function withdrawEther() public
        onlyTokenManager
    {
        // Available at any phase.
        if(this.balance > 0) {
            if(!tokenManager.send(this.balance)) throw;
        }
    }

    function setCrowdsaleManager(address _mgr) public
        onlyTokenManager
    {
        // You can't change crowdsale contract when migration is in progress.
        if(currentPhase == Phase.Migrating) throw;
        crowdsaleManager = _mgr;
    }
}

pragma solidity ^0.4.4;

// ERC20 token interface is implemented only partially.
// Token transfer is prohibited due to spec (see PRESALE-SPEC.md),
// hence some functions are left undefined:
//  - transfer, transferFrom,
//  - approve, allowance.

contract PresaleToken {

    /// @dev Constructor
    /// @param _tokenManager Token manager address.
    function PresaleToken(address _tokenManager) {
        tokenManager = _tokenManager;
    }

    /*/
     *  Constants
    /*/

    string public name = "SONM Presale Token";
    string public symbol = "SPT";
    uint   public decimals = 18;

    uint public PRICE = 200; // 200 SPT per Ether

    //  price
    uint public TOKEN_SUPPLY_LIMIT = 4000000 * (1 ether / 1 wei);

    /*/
     *  Token state
    /*/

    enum Phase {
        Created,
        Running,
        Paused,
        Migrating,
        Migrated
    }

    Phase public currentPhase = Phase.Created;
    uint public totalSupply = 0; // amount of tokens already sold

    // Token manager has exclusive priveleges to call administrative
    // functions on this contract.
    address public tokenManager;
    // Crowdsale manager has exclusive priveleges to burn presale tokens.
    address public crowdsaleManager;

    mapping (address => uint256) private balance;

    modifier onlyTokenManager()     { if(msg.sender != tokenManager) throw; _; }
    modifier onlyCrowdsaleManager() { if(msg.sender != crowdsaleManager) throw; _; }

    /*/
     *  Events
    /*/

    event LogBuy(address indexed owner, uint value);
    event LogBurn(address indexed owner, uint value);
    event LogPhaseSwitch(Phase newPhase);

    /*/
     *  Public functions
    /*/

    function() payable {
        buyTokens(msg.sender);
    }

    /// @dev Lets buy you some tokens.
    function buyTokens(address _buyer) public payable {
        // Available only if presale is running.
        if(currentPhase != Phase.Running) throw;

        if(msg.value == 0) throw;
        uint newTokens = msg.value * PRICE;
        if (totalSupply + newTokens > TOKEN_SUPPLY_LIMIT) throw;
        balance[_buyer] += newTokens;
        totalSupply += newTokens;
        LogBuy(_buyer, newTokens);
    }

    /// @dev Returns number of tokens owned by given address.
    /// @param _owner Address of token owner.
    function burnTokens(address _owner) public
        onlyCrowdsaleManager
    {
        // Available only during migration phase
        if(currentPhase != Phase.Migrating) throw;

        uint tokens = balance[_owner];
        if(tokens == 0) throw;
        balance[_owner] = 0;
        totalSupply -= tokens;
        LogBurn(_owner, tokens);

        // Automatically switch phase when migration is done.
        if(totalSupply == 0) {
            currentPhase = Phase.Migrated;
            LogPhaseSwitch(Phase.Migrated);
        }
    }

    /// @dev Returns number of tokens owned by given address.
    /// @param _owner Address of token owner.
    function balanceOf(address _owner) constant returns (uint256) {
        return balance[_owner];
    }

    /*/
     *  Administrative functions
    /*/

    function setPresalePhase(Phase _nextPhase) public
        onlyTokenManager
    {
        bool canSwitchPhase
            =  (currentPhase == Phase.Created && _nextPhase == Phase.Running)
            || (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
                // switch to migration phase only if crowdsale manager is set
            || ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
                && _nextPhase == Phase.Migrating
                && crowdsaleManager != 0x0)
            || (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
                // switch to migrated only if everyting is migrated
            || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
                && totalSupply == 0);

        if(!canSwitchPhase) throw;
        currentPhase = _nextPhase;
        LogPhaseSwitch(_nextPhase);
    }

    function withdrawEther() public
        onlyTokenManager
    {
        // Available at any phase.
        if(this.balance > 0) {
            if(!tokenManager.send(this.balance)) throw;
        }
    }

    function setCrowdsaleManager(address _mgr) public
        onlyTokenManager
    {
        // You can't change crowdsale contract when migration is in progress.
        if(currentPhase == Phase.Migrating) throw;
        crowdsaleManager = _mgr;
    }
}


add thesaurus.sol

add thesaurus.sol

contract thesaurus {

	struct metadata {

	}
}

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


Comment Adjudicator

Comment Adjudicator

/**
 * This contract ensures that the latest signed state between some parties is
 * revealed. This solves the data availability contest problem.
 */
contract Adjudicator {

	// The maximum integer value that can be stored in an uint256 (uint)
	uint public constant UINT_MAX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

	// Whether the state has been frozen or not
	bool public frozen = false;

	// The current nonce of the state
	uint nonce = 0;

	// The timestamp of the last state sent
	uint lastTimestamp = 0;

	// The address of the owner of this contract
	address owner;

	// The timeout period before this contract can be frozen
	uint timeout;

	// The last hash of the latest state
	bytes32 public stateHash;

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

	modifier notFrozen {
		if (frozen) {
			throw;
		} else {
			_
		}
	}

	/**
	 * Creates a new Adjudicator contract.
	 *
	 * _owner: The owner of this contract
	 * _timeout: The timeout period before this contract can be frozen
	 */
	function Adjudicator(address _owner, uint _timeout) {
		owner = _owner;
		timeout = _timeout;
	}

	/**
	 * Submits a potential hash of state into this contract.
	 *
	 * _newNonce: The nonce of the new state
	 * _stateHash: The hash of the latest state
	 *
	 * returns: `true` if sucessful, otherwise `false`
	 */
	function submit(uint _newNonce, bytes32 _stateHash)
		external
		onlyOwner
		notFrozen
		returns (bool)
	{
		if (_newNonce > nonce) {
			nonce = _newNonce;
			stateHash = _stateHash;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Unfreezes the contract only if the the contract is frozen.
	 *
	 * returns: `true` if successful, otherwise `false`
	 */
	function unfreeze() external onlyOwner returns (bool) {
		if (frozen && nonce != UINT_MAX) {
			lastTimestamp = 0;
			frozen = false;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Freezes the contract if the nonce is final or if the timeout period has
	 * been reached.
	 *
	 * returns: `true` if successful, otherwise `false`
	 */
	function finalize() external notFrozen returns (bool) {
		if (nonce == UINT_MAX || (lastTimestamp != 0 && now > lastTimestamp + timeout)) {
			frozen = true;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Kills the current contract.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlyOwner {
		selfdestruct(_recipient);
	}
}

contract Adjudicator {

	uint public constant UINT_MAX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

	bool public frozen = false;
	uint nonce = 0;
	uint lastTimestamp = 0;
	address owner;
	uint timeout;
	bytes32 public stateHash;

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

	modifier notFrozen {
		if (frozen) {
			throw;
		} else {
			_
		}
	}

	function Adjudicator(address _owner, uint _timeout) {
		owner = _owner;
		timeout = _timeout;
	}

	function submit(uint _newNonce, bytes32 _stateHash)
		external
		onlyOwner
		notFrozen
		returns (bool)
	{
		if (_newNonce > nonce) {
			nonce = _newNonce;
			stateHash = _stateHash;
			return true;
		} else {
			return false;
		}
	}

	function unfreeze() external onlyOwner returns (bool) {
		if (frozen && nonce != UINT_MAX) {
			lastTimestamp = 0;
			frozen = false;
			return true;
		} else {
			return false;
		}
	}

	function finalize() external notFrozen returns (bool) {
		if (nonce == UINT_MAX || (lastTimestamp != 0 && now > lastTimestamp + timeout)) {
			frozen = true;
			return true;
		} else {
			return false;
		}
	}

	function kill(address _recipient) external onlyOwner {
		selfdestruct(_recipient);
	}
}


Store the block number in the last 6 bytes of the id.

/**
 * @title BlobStore
 * @author Jonathan Brown <jbrown@bluedroplet.com>
 */
contract BlobStore {

    event logBlob(bytes32 indexed hash, bytes blob) anonymous;

    /**
     * @dev Stores a blob in the transaction log.
     * @param blob Blob that should be stored.
     * @return id 26 bytes hash of blob, 6 bytes block number.
     */
    function storeBlob(bytes blob) external returns (bytes32 id) {
        // Calculate the hash and zero out the last six bytes.
        // Casting to bytes32 before the ~ saves 8 gas.
        id = sha3(blob) & ~bytes32((2 ** 48) - 1);
        // Store the blob in a log in the current block.
        logBlob(id, blob);
        // Populate the last six bytes with the current block number.
        id |= bytes32(block.number);
    }

    function() {
        throw;      // Do not maintain an ether balance.
    }

}

/**
 * @title BlobStore
 * @author Jonathan Brown <jbrown@bluedroplet.com>
 */
contract BlobStore {

    event logBlob(bytes32 indexed hash, bytes blob) anonymous;

    /**
     * @dev Stores a blob in the transaction log.
     * @param blob Blob that should be stored.
     * @return hash Hash of blob.
     */
    function storeBlob(bytes blob) external returns (bytes32 hash) {
        // Calculate the hash.
        hash = sha3(blob);
        // Store the blob in a log in the current block.
        logBlob(hash, blob);
    }

    function() {
        throw;      // Do not maintain an ether balance.
    }

}


Minor comment added

Minor comment added

import 'plutons';
import 'plutusdex';

/**
 Contract of user of Plutus.
*/
contract PlutusUser {
	//control addr
	address owner;
	// link to token
	address plutonAddr;
	//PlutusDex address
	address plutusDexAddr;
	//Virtual debit card ID
	bytes32 userVdcIban;
	address plutusApprovedCentralAddr;

	modifier ownerCheck { if (msg.sender == owner) _ }
	modifier plutusCentralAddrCheck { if (msg.sender == plutusApprovedCentralAddr) _ }
	modifier plutusDexCheck { if (msg.sender == plutusDexAddr) _ }

	function PlutusUser(bytes32 _userVdcIban) {
		owner = msg.sender;
		userVdcIban = _userVdcIban;
		//Rewrite when plutons and PlutusDex smart contracts will be created
		plutusApprovedCentralAddr = 0xa;
		plutonAddr = 0xa;
		plutusDexAddr = 0xa;
	}

    function sendTokenFromDex(address _to, uint _amount) plutusDexCheck returns(bool result) {
        plutons pluton;
        pluton = plutons(plutonAddr);
        result = pluton.sendCoinFrom(owner, _amount, _to);
        return result;
    }

	function offerBtcFromApp(address _trader,  uint _btcOffered) plutusCentralAddrCheck returns(bool result) {
		PlutusDex plutusDex;
        plutusDex = PlutusDex(plutusDexAddr);
		result = plutusDex.offerBtc( _trader, _btcOffered, userVdcIban);
		return result;
	}
}

import 'plutons';
import 'plutusdex';

contract PlutusUser {
	//control addr
	address owner;
	// link to token
	address plutonAddr;
	//PlutusDex address
	address plutusDexAddr;
	//Virtual debit card ID
	bytes32 userVdcIban;
	address plutusApprovedCentralAddr;

	modifier ownerCheck { if (msg.sender == owner) _ }
	modifier plutusCentralAddrCheck { if (msg.sender == plutusApprovedCentralAddr) _ }
	modifier plutusDexCheck { if (msg.sender == plutusDexAddr) _ }

	function PlutusUser(bytes32 _userVdcIban) {
		owner = msg.sender;
		userVdcIban = _userVdcIban;
		//Rewrite when plutons and PlutusDex smart contracts will be created
		plutusApprovedCentralAddr = 0xa;
		plutonAddr = 0xa;
		plutusDexAddr = 0xa;
	}

    function sendTokenFromDex(address _to, uint _amount) plutusDexCheck returns(bool result) {
        plutons pluton;
        pluton = plutons(plutonAddr);
        result = pluton.sendCoinFrom(owner, _amount, _to);
        return result;
    }

	function offerBtcFromApp(address _trader,  uint _btcOffered) plutusCentralAddrCheck returns(bool result) {
		PlutusDex plutusDex;
        plutusDex = PlutusDex(plutusDexAddr);
		result = plutusDex.offerBtc( _trader, _btcOffered, userVdcIban);
		return result;
	}
}


changed leftover send to forwarding all funds to transaction request

pragma solidity ^0.4.21;

import "contracts/Interface/RequestFactoryInterface.sol";
import "contracts/Interface/SchedulerInterface.sol";

import "contracts/Library/PaymentLib.sol";
import "contracts/Library/RequestLib.sol";
import "contracts/Library/RequestScheduleLib.sol";

/**
 * @title BaseScheduler
 * @dev The foundational contract which provides the API for scheduling future transactions on the Alarm Client.
 */
contract BaseScheduler is SchedulerInterface {
    // The RequestFactory which produces requests for this scheduler.
    address public factoryAddress;

    // The TemporalUnit (Block or Timestamp) for this scheduler.
    RequestScheduleLib.TemporalUnit public temporalUnit;

    // The address which will be sent the fee payments.
    address public feeRecipient;

    /*
     * @dev Fallback function to be able to receive ether. This can occur
     *  legitimately when scheduling fails due to a validation error.
     */
    function() public payable {}

    /// Event that bubbles up the address of new requests made with this scheduler.
    event NewRequest(address request);

    /**
     * @dev Schedules a new TransactionRequest using the 'full' parameters.
     * @param _toAddress The address destination of the transaction.
     * @param _callData The bytecode that will be included with the transaction.
     * @param _uintArgs [0] The callGas of the transaction.
     * @param _uintArgs [1] The value of ether to be sent with the transaction.
     * @param _uintArgs [2] The size of the execution window of the transaction.
     * @param _uintArgs [3] The (block or timestamp) of when the execution window starts.
     * @param _uintArgs [4] The gasPrice which will be used to execute this transaction.
     * @param _uintArgs [5] The fee attached to this transaction.
     * @param _uintArgs [6] The bounty attached to this transaction.
     * @param _uintArgs [7] The deposit required to claim this transaction.
     * @return The address of the new TransactionRequest.
     */
    function schedule (
        address   _toAddress,
        bytes     _callData,
        uint[8]   _uintArgs
    )
        public payable returns (address newRequest)
    {
        RequestFactoryInterface factory = RequestFactoryInterface(factoryAddress);

        uint endowment = PaymentLib.computeEndowment(
            _uintArgs[6], //bounty
            _uintArgs[5], //fee
            _uintArgs[0], //callGas
            _uintArgs[1], //callValue
            _uintArgs[4], //gasPrice
            RequestLib.EXECUTION_GAS_OVERHEAD()
        );

        require(msg.value > endowment);

        if (temporalUnit == RequestScheduleLib.TemporalUnit.Blocks) {
            newRequest = factory.createValidatedRequest.value(msg.value)(
                [
                    msg.sender,                 // meta.owner
                    feeRecipient,               // paymentData.feeRecipient
                    _toAddress                  // txnData.toAddress
                ],
                [
                    _uintArgs[5],               // paymentData.fee
                    _uintArgs[6],               // paymentData.bounty
                    255,                        // scheduler.claimWindowSize
                    10,                         // scheduler.freezePeriod
                    16,                         // scheduler.reservedWindowSize
                    uint(temporalUnit),         // scheduler.temporalUnit (1: block, 2: timestamp)
                    _uintArgs[2],               // scheduler.windowSize
                    _uintArgs[3],               // scheduler.windowStart
                    _uintArgs[0],               // txnData.callGas
                    _uintArgs[1],               // txnData.callValue
                    _uintArgs[4],               // txnData.gasPrice
                    _uintArgs[7]                // claimData.requiredDeposit
                ],
                _callData
            );
        } else if (temporalUnit == RequestScheduleLib.TemporalUnit.Timestamp) {
            newRequest = factory.createValidatedRequest.value(msg.value)(
                [
                    msg.sender,                 // meta.owner
                    feeRecipient,               // paymentData.feeRecipient
                    _toAddress                  // txnData.toAddress
                ],
                [
                    _uintArgs[5],               // paymentData.fee
                    _uintArgs[6],               // paymentData.bounty
                    60 minutes,                 // scheduler.claimWindowSize
                    3 minutes,                  // scheduler.freezePeriod
                    5 minutes,                  // scheduler.reservedWindowSize
                    uint(temporalUnit),         // scheduler.temporalUnit (1: block, 2: timestamp)
                    _uintArgs[2],               // scheduler.windowSize
                    _uintArgs[3],               // scheduler.windowStart
                    _uintArgs[0],               // txnData.callGas
                    _uintArgs[1],               // txnData.callValue
                    _uintArgs[4],               // txnData.gasPrice
                    _uintArgs[7]                // claimData.requiredDeposit
                ],
                _callData
            );
        } else {
            // unsupported temporal unit
            revert();
        }

        require(newRequest != 0x0);
        emit NewRequest(newRequest);
        return newRequest;
    }
}

pragma solidity ^0.4.21;

import "contracts/Interface/RequestFactoryInterface.sol";
import "contracts/Interface/SchedulerInterface.sol";

import "contracts/Library/PaymentLib.sol";
import "contracts/Library/RequestLib.sol";
import "contracts/Library/RequestScheduleLib.sol";

/**
 * @title BaseScheduler
 * @dev The foundational contract which provides the API for scheduling future transactions on the Alarm Client.
 */
contract BaseScheduler is SchedulerInterface {
    // The RequestFactory which produces requests for this scheduler.
    address public factoryAddress;

    // The TemporalUnit (Block or Timestamp) for this scheduler.
    RequestScheduleLib.TemporalUnit public temporalUnit;

    // The address which will be sent the fee payments.
    address public feeRecipient;

    /*
     * @dev Fallback function to be able to receive ether. This can occur
     *  legitimately when scheduling fails due to a validation error.
     */
    function() public payable {}

    /// Event that bubbles up the address of new requests made with this scheduler.
    event NewRequest(address request);

    /**
     * @dev Schedules a new TransactionRequest using the 'full' parameters.
     * @param _toAddress The address destination of the transaction.
     * @param _callData The bytecode that will be included with the transaction.
     * @param _uintArgs [0] The callGas of the transaction.
     * @param _uintArgs [1] The value of ether to be sent with the transaction.
     * @param _uintArgs [2] The size of the execution window of the transaction.
     * @param _uintArgs [3] The (block or timestamp) of when the execution window starts.
     * @param _uintArgs [4] The gasPrice which will be used to execute this transaction.
     * @param _uintArgs [5] The fee attached to this transaction.
     * @param _uintArgs [6] The bounty attached to this transaction.
     * @param _uintArgs [7] The deposit required to claim this transaction.
     * @return The address of the new TransactionRequest.
     */
    function schedule (
        address   _toAddress,
        bytes     _callData,
        uint[8]   _uintArgs
    )
        public payable returns (address newRequest)
    {
        RequestFactoryInterface factory = RequestFactoryInterface(factoryAddress);

        uint endowment = PaymentLib.computeEndowment(
            _uintArgs[6], //bounty
            _uintArgs[5], //fee
            _uintArgs[0], //callGas
            _uintArgs[1], //callValue
            _uintArgs[4], //gasPrice
            RequestLib.EXECUTION_GAS_OVERHEAD()
        );

        if (temporalUnit == RequestScheduleLib.TemporalUnit.Blocks) {
            newRequest = factory.createValidatedRequest.value(endowment)(
                [
                    msg.sender,                 // meta.owner
                    feeRecipient,               // paymentData.feeRecipient
                    _toAddress                  // txnData.toAddress
                ],
                [
                    _uintArgs[5],               // paymentData.fee
                    _uintArgs[6],               // paymentData.bounty
                    255,                        // scheduler.claimWindowSize
                    10,                         // scheduler.freezePeriod
                    16,                         // scheduler.reservedWindowSize
                    uint(temporalUnit),         // scheduler.temporalUnit (1: block, 2: timestamp)
                    _uintArgs[2],               // scheduler.windowSize
                    _uintArgs[3],               // scheduler.windowStart
                    _uintArgs[0],               // txnData.callGas
                    _uintArgs[1],               // txnData.callValue
                    _uintArgs[4],               // txnData.gasPrice
                    _uintArgs[7]                // claimData.requiredDeposit
                ],
                _callData
            );
        } else if (temporalUnit == RequestScheduleLib.TemporalUnit.Timestamp) {
            newRequest = factory.createValidatedRequest.value(endowment)(
                [
                    msg.sender,                 // meta.owner
                    feeRecipient,               // paymentData.feeRecipient
                    _toAddress                  // txnData.toAddress
                ],
                [
                    _uintArgs[5],               // paymentData.fee
                    _uintArgs[6],               // paymentData.bounty
                    60 minutes,                 // scheduler.claimWindowSize
                    3 minutes,                  // scheduler.freezePeriod
                    5 minutes,                  // scheduler.reservedWindowSize
                    uint(temporalUnit),         // scheduler.temporalUnit (1: block, 2: timestamp)
                    _uintArgs[2],               // scheduler.windowSize
                    _uintArgs[3],               // scheduler.windowStart
                    _uintArgs[0],               // txnData.callGas
                    _uintArgs[1],               // txnData.callValue
                    _uintArgs[4],               // txnData.gasPrice
                    _uintArgs[7]                // claimData.requiredDeposit
                ],
                _callData
            );
        } else {
            // unsupported temporal unit
            revert();
        }

        uint leftover = address(this).balance;
        if (leftover > 0) {
            msg.sender.transfer(leftover);
        }

        require(newRequest != 0x0);
        emit NewRequest(newRequest);
        return newRequest;
    }
}


Change made on BasicToken.sol OpenZeppelin Code. Make it more standard to ERC20 token

pragma solidity ^0.4.13;

import './ERC20Basic.sol';
import '../math/SafeMath.sol';

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
*
 * created by OpenZeppelin
 * https://github.com/OpenZeppelin/zeppelin-solidity
 * changed by IAM <DEV> (Elky Bachtiar)
 * https://iamdeveloper.io
 * Changes made base on ERC20 Token Stadard and Solidity version 0.4.13
 * https://theethereum.wiki/w/index.php/ERC20_Token_Standard
 */
contract BasicToken is ERC20Basic {
  using SafeMath for uint256;

  mapping(address => uint256) balances;

  /**
  * @dev transfer token for a specified address
  * @param _to The address to transfer to.
  * @param _value The amount to be transferred.
  */
  function transfer(address _to, uint256 _value) returns (bool success) {
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

  /**
  * @dev Gets the balance of the specified address.
  * @param _owner The address to query the the balance of.
  * @return An uint256 representing the amount owned by the passed address.
  */
  function balanceOf(address _owner) constant returns (uint256 balance) {
    return balances[_owner];
  }

}

pragma solidity ^0.4.11;

import './ERC20Basic.sol';
import '../math/SafeMath.sol';

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
 */
contract BasicToken is ERC20Basic {
  using SafeMath for uint256;

  mapping(address => uint256) balances;

  /**
  * @dev transfer token for a specified address
  * @param _to The address to transfer to.
  * @param _value The amount to be transferred.
  */
  function transfer(address _to, uint256 _value) returns (bool) {
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

  /**
  * @dev Gets the balance of the specified address.
  * @param _owner The address to query the the balance of.
  * @return An uint256 representing the amount owned by the passed address.
  */
  function balanceOf(address _owner) constant returns (uint256 balance) {
    return balances[_owner];
  }

}


Move comment

Move comment

pragma solidity >=0.8.4;

import "./ENS.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../root/Controllable.sol";

abstract contract NameResolver {
    function setName(bytes32 node, string memory name) public virtual;
}

bytes32 constant lookup = 0x3031323334353637383961626364656600000000000000000000000000000000;

bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;

// namehash('addr.reverse')

contract ReverseRegistrar is Ownable, Controllable {
    ENS public ens;
    NameResolver public defaultResolver;

    event ReverseClaimed(address indexed addr, bytes32 indexed node);

    /**
     * @dev Constructor
     * @param ensAddr The address of the ENS registry.
     * @param resolverAddr The address of the default reverse resolver.
     */
    constructor(ENS ensAddr, NameResolver resolverAddr) {
        ens = ensAddr;
        defaultResolver = resolverAddr;

        // Assign ownership of the reverse record to our deployer
        ReverseRegistrar oldRegistrar = ReverseRegistrar(
            ens.owner(ADDR_REVERSE_NODE)
        );
        if (address(oldRegistrar) != address(0x0)) {
            oldRegistrar.claim(msg.sender);
        }
    }

    modifier authorised(address addr) {
        require(
            addr == msg.sender ||
                controllers[msg.sender] ||
                ens.isApprovedForAll(addr, msg.sender) ||
                ownsContract(addr),
            "Caller is not a controller or authorised by address or the address itself"
        );
        _;
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @return The ENS node hash of the reverse record.
     */
    function claim(address owner) public returns (bytes32) {
        return _claimWithResolver(msg.sender, owner, address(0x0));
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param addr The reverse record to set
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @return The ENS node hash of the reverse record.
     */
    function claimForAddr(address addr, address owner)
        public
        authorised(addr)
        returns (bytes32)
    {
        return _claimWithResolver(addr, owner, address(0x0));
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @param resolver The address of the resolver to set; 0 to leave unchanged.
     * @return The ENS node hash of the reverse record.
     */
    function claimWithResolver(address owner, address resolver)
        public
        returns (bytes32)
    {
        return _claimWithResolver(msg.sender, owner, resolver);
    }

    /**
     * @dev Transfers ownership of the reverse ENS record specified with the
     *      address provided
     * @param addr The reverse record to set
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @param resolver The address of the resolver to set; 0 to leave unchanged.
     * @return The ENS node hash of the reverse record.
     */
    function claimWithResolverForAddr(
        address addr,
        address owner,
        address resolver
    ) public authorised(addr) returns (bytes32) {
        return _claimWithResolver(addr, owner, resolver);
    }

    /**
     * @dev Sets the `name()` record for the reverse ENS record associated with
     * the calling account. First updates the resolver to the default reverse
     * resolver if necessary.
     * @param name The name to set for this address.
     * @return The ENS node hash of the reverse record.
     */
    function setName(string memory name) public returns (bytes32) {
        bytes32 node = _claimWithResolver(
            msg.sender,
            address(this),
            address(defaultResolver)
        );
        defaultResolver.setName(node, name);
        return node;
    }

    /**
     * @dev Sets the `name()` record for the reverse ENS record associated with
     * the account provided. First updates the resolver to the default reverse
     * resolver if necessary.
     * Only callable by controllers and authorised users
     * @param addr The reverse record to set
     * @param owner The owner of the reverse node
     * @param name The name to set for this address.
     * @return The ENS node hash of the reverse record.
     */
    function setNameForAddr(
        address addr,
        address owner,
        string memory name
    ) public authorised(addr) returns (bytes32) {
        bytes32 node = _claimWithResolver(
            addr,
            address(this),
            address(defaultResolver)
        );
        defaultResolver.setName(node, name);
        ens.setSubnodeOwner(ADDR_REVERSE_NODE, sha3HexAddress(addr), owner);
        return node;
    }

    /**
     * @dev Returns the node hash for a given account's reverse records.
     * @param addr The address to hash
     * @return The ENS node hash.
     */
    function node(address addr) public pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr))
            );
    }

    /**
     * @dev An optimised function to compute the sha3 of the lower-case
     *      hexadecimal representation of an Ethereum address.
     * @param addr The address to hash
     * @return ret The SHA3 hash of the lower-case hexadecimal encoding of the
     *         input address.
     */
    function sha3HexAddress(address addr) private pure returns (bytes32 ret) {
        assembly {
            for {
                let i := 40
            } gt(i, 0) {

            } {
                i := sub(i, 1)
                mstore8(i, byte(and(addr, 0xf), lookup))
                addr := div(addr, 0x10)
                i := sub(i, 1)
                mstore8(i, byte(and(addr, 0xf), lookup))
                addr := div(addr, 0x10)
            }

            ret := keccak256(0, 40)
        }
    }

    /* Internal functions */

    function _claimWithResolver(
        address addr,
        address owner,
        address resolver
    ) internal returns (bytes32) {
        bytes32 label = sha3HexAddress(addr);
        bytes32 node = keccak256(abi.encodePacked(ADDR_REVERSE_NODE, label));
        address currentResolver = ens.resolver(node);
        bool shouldUpdateResolver = (resolver != address(0x0) &&
            resolver != currentResolver);
        address newResolver = shouldUpdateResolver ? resolver : currentResolver;

        ens.setSubnodeRecord(ADDR_REVERSE_NODE, label, owner, newResolver, 0);

        emit ReverseClaimed(addr, node);

        return node;
    }

    function ownsContract(address addr) internal view returns (bool) {
        try Ownable(addr).owner() returns (address owner) {
            return owner == msg.sender;
        } catch {
            return false;
        }
    }
}

pragma solidity >=0.8.4;

import "./ENS.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../root/Controllable.sol";

abstract contract NameResolver {
    function setName(bytes32 node, string memory name) public virtual;
}

bytes32 constant lookup = 0x3031323334353637383961626364656600000000000000000000000000000000;

bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;

contract ReverseRegistrar is Ownable, Controllable {
    // namehash('addr.reverse')

    ENS public ens;
    NameResolver public defaultResolver;

    event ReverseClaimed(address indexed addr, bytes32 indexed node);

    /**
     * @dev Constructor
     * @param ensAddr The address of the ENS registry.
     * @param resolverAddr The address of the default reverse resolver.
     */
    constructor(ENS ensAddr, NameResolver resolverAddr) {
        ens = ensAddr;
        defaultResolver = resolverAddr;

        // Assign ownership of the reverse record to our deployer
        ReverseRegistrar oldRegistrar = ReverseRegistrar(
            ens.owner(ADDR_REVERSE_NODE)
        );
        if (address(oldRegistrar) != address(0x0)) {
            oldRegistrar.claim(msg.sender);
        }
    }

    modifier authorised(address addr) {
        require(
            addr == msg.sender ||
                controllers[msg.sender] ||
                ens.isApprovedForAll(addr, msg.sender) ||
                ownsContract(addr),
            "Caller is not a controller or authorised by address or the address itself"
        );
        _;
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @return The ENS node hash of the reverse record.
     */
    function claim(address owner) public returns (bytes32) {
        return _claimWithResolver(msg.sender, owner, address(0x0));
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param addr The reverse record to set
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @return The ENS node hash of the reverse record.
     */
    function claimForAddr(address addr, address owner)
        public
        authorised(addr)
        returns (bytes32)
    {
        return _claimWithResolver(addr, owner, address(0x0));
    }

    /**
     * @dev Transfers ownership of the reverse ENS record associated with the
     *      calling account.
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @param resolver The address of the resolver to set; 0 to leave unchanged.
     * @return The ENS node hash of the reverse record.
     */
    function claimWithResolver(address owner, address resolver)
        public
        returns (bytes32)
    {
        return _claimWithResolver(msg.sender, owner, resolver);
    }

    /**
     * @dev Transfers ownership of the reverse ENS record specified with the
     *      address provided
     * @param addr The reverse record to set
     * @param owner The address to set as the owner of the reverse record in ENS.
     * @param resolver The address of the resolver to set; 0 to leave unchanged.
     * @return The ENS node hash of the reverse record.
     */
    function claimWithResolverForAddr(
        address addr,
        address owner,
        address resolver
    ) public authorised(addr) returns (bytes32) {
        return _claimWithResolver(addr, owner, resolver);
    }

    /**
     * @dev Sets the `name()` record for the reverse ENS record associated with
     * the calling account. First updates the resolver to the default reverse
     * resolver if necessary.
     * @param name The name to set for this address.
     * @return The ENS node hash of the reverse record.
     */
    function setName(string memory name) public returns (bytes32) {
        bytes32 node = _claimWithResolver(
            msg.sender,
            address(this),
            address(defaultResolver)
        );
        defaultResolver.setName(node, name);
        return node;
    }

    /**
     * @dev Sets the `name()` record for the reverse ENS record associated with
     * the account provided. First updates the resolver to the default reverse
     * resolver if necessary.
     * Only callable by controllers and authorised users
     * @param addr The reverse record to set
     * @param owner The owner of the reverse node
     * @param name The name to set for this address.
     * @return The ENS node hash of the reverse record.
     */
    function setNameForAddr(
        address addr,
        address owner,
        string memory name
    ) public authorised(addr) returns (bytes32) {
        bytes32 node = _claimWithResolver(
            addr,
            address(this),
            address(defaultResolver)
        );
        defaultResolver.setName(node, name);
        ens.setSubnodeOwner(ADDR_REVERSE_NODE, sha3HexAddress(addr), owner);
        return node;
    }

    /**
     * @dev Returns the node hash for a given account's reverse records.
     * @param addr The address to hash
     * @return The ENS node hash.
     */
    function node(address addr) public pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr))
            );
    }

    /**
     * @dev An optimised function to compute the sha3 of the lower-case
     *      hexadecimal representation of an Ethereum address.
     * @param addr The address to hash
     * @return ret The SHA3 hash of the lower-case hexadecimal encoding of the
     *         input address.
     */
    function sha3HexAddress(address addr) private pure returns (bytes32 ret) {
        assembly {
            for {
                let i := 40
            } gt(i, 0) {

            } {
                i := sub(i, 1)
                mstore8(i, byte(and(addr, 0xf), lookup))
                addr := div(addr, 0x10)
                i := sub(i, 1)
                mstore8(i, byte(and(addr, 0xf), lookup))
                addr := div(addr, 0x10)
            }

            ret := keccak256(0, 40)
        }
    }

    /* Internal functions */

    function _claimWithResolver(
        address addr,
        address owner,
        address resolver
    ) internal returns (bytes32) {
        bytes32 label = sha3HexAddress(addr);
        bytes32 node = keccak256(abi.encodePacked(ADDR_REVERSE_NODE, label));
        address currentResolver = ens.resolver(node);
        bool shouldUpdateResolver = (resolver != address(0x0) &&
            resolver != currentResolver);
        address newResolver = shouldUpdateResolver ? resolver : currentResolver;

        ens.setSubnodeRecord(ADDR_REVERSE_NODE, label, owner, newResolver, 0);

        emit ReverseClaimed(addr, node);

        return node;
    }

    function ownsContract(address addr) internal view returns (bool) {
        try Ownable(addr).owner() returns (address owner) {
            return owner == msg.sender;
        } catch {
            return false;
        }
    }
}


Should fix Medao.startAuction() throwing

pragma solidity ^0.4.11;

import "MiniMeToken.sol";

contract ERC20Token {
    function transfer(address _to, uint256 _value) returns (bool success);
    function balanceOf(address _owner) constant returns (uint256 balance);
}

contract Owned {
    address public owner;

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

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

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

/*
    Copyright 2017, Joseph Reed

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/// @title MeDao Contract
/// @author Joseph Reed
/// @dev A MeDao aims to let anyone issue time shares for themselves. The issuer
///      should talk to shareholders for advice on how to maximize value for
///      themselves and for shareholders. Up to 40 hours worth of time are
///      auctioned off each week. The Owner of the MeDao is expected to burn
///      a certain amount of tokens each week negotiated between the Owner
///      and the Shareholders and thus will be diffrent for every MeDao. For
///      more info go to <github link here>.

contract Tokenized is Owned {

    MiniMeToken public Token;
    address public withdraw_address;

    function setupToken (
        address withdrawAddress,
        MiniMeToken CloneableToken,
        string _tokenName,
        uint8 _decimals,
        string _symbol,
        uint _snapshotBlock,
        bool _transfersEnabled
    ) onlyOwner {
        withdraw_address = withdrawAddress;
        address token = CloneableToken.createCloneToken(
            _tokenName,
            _decimals,
            _symbol,
            _snapshotBlock,
            _transfersEnabled
        );

        Token = MiniMeToken(token);
    }

    function withdrawEther () onlyOwner {
        var balance = this.balance;
        withdraw_address.transfer(balance);

        WithdrawEther_event(withdraw_address,balance);
    }

    function withdrawERC20Token (address Token) onlyOwner {
        uint tokenBalance = ERC20Token(Token).balanceOf(this);
        ERC20Token(Token).transfer(withdraw_address,tokenBalance);

        WithdrawToken_event(withdraw_address,Token,tokenBalance);
    }

    function updateDepositAddress (address _newDepositAddress) onlyOwner {
        withdraw_address = _newDepositAddress;

        NewWithdrawAddress_event(withdraw_address);
    }

    function () payable {
        withdraw_address.transfer(msg.value);

        Payable_event(msg.sender,msg.value);
    }

    modifier onlyTokenHolders (uint _minimum_needed) {
        uint tokens = Token.balanceOf(msg.sender);
        if(tokens < _minimum_needed) throw;
        _;
    }

    event Payable_event(address sender, uint amount);
    event WithdrawEther_event(address withdrawAddress, uint amount);
    event WithdrawToken_event(address withdrawAddress, address token, uint amount);
    event NewWithdrawAddress_event(address withdraw_address);
}

contract OngoingAuction is Owned {

    uint public current_bids_open;
    uint public total_bids_made;
    mapping (uint => Bid) public bids;
    mapping (address => Bidder) public bidders;

    uint public top_teir;
    uint public bottom_teir;
    uint public total_teirs;
    mapping (uint => Teir) public teirs; //DLL

////////////////
// Auction Functions
////////////////

    function placeBid (uint touchingTeir) payable {
        if(msg.value == 0) throw;

        if(teirs[msg.value].line_length == 0) {
            if(teirs[touchingTeir].line_length == 0 && top_teir != 0) throw;

            addNewTeir_internal(touchingTeir);
        }

        addNewBid_internal();
    }

    function removeBid (uint bid_id) {
        if (msg.sender != bids[bid_id].owner) throw;

        removeBid_internal(bid_id);
        bids[bid_id].cancelled = true;

        if (!bids[bid_id].owner.send(bids[bid_id].value)) throw;
    }

    function startAuction (address deposit_address) onlyOwner returns (uint) {
        uint winning_bid_id = acceptHighestBid();
        uint bidValue = bids[winning_bid_id].value;

        deposit_address.transfer(bidValue);

        return winning_bid_id;
    }

    function getBids (address bidder) constant returns (uint[]) {
        uint total_bids = bidders[bidder].total_bids_made;
        uint[] memory all_bids = new uint[](total_bids);

        for(uint i = 0; i < total_bids; i++)
            all_bids[i] = bidders[bidder].bids[i+1];

        return all_bids;
    }

    function getTeirs () constant returns (uint[]) {
        uint[] memory all_teirs = new uint[](total_teirs);
        uint current_teir = teirs[top_teir].value;
        for (uint i = 0; i < total_teirs; i++) {
            all_teirs[i] = current_teir;
            current_teir = teirs[current_teir].teir_below;
        }

        return all_teirs;
    }

    function getBidOwner (uint bid_id) constant returns (address) {
        return bids[bid_id].owner;
    }

    function getBidValue (uint bid_id) constant returns (uint) {
        return bids[bid_id].value;
    }

////////////////
// Internal Functions
////////////////

    function acceptHighestBid () internal returns (uint) {
        if(top_teir == 0) throw;

        uint highest_bid_id = teirs[top_teir].front_of_line_id;
        bids[highest_bid_id].accepted = true;
        removeBid_internal(highest_bid_id);

        return highest_bid_id;
    }

    function addNewTeir_internal (uint touching) internal {
        uint value = msg.value;

        if (top_teir == 0) {
            teirs[value] = Teir(0,value,0,0,0,0);
            top_teir = value;
            bottom_teir = value;
        } else if (value > top_teir && touching == top_teir) {
            teirs[value] = Teir(0,value,top_teir,0,0,0);
            teirs[top_teir].teir_above = value;
            top_teir = value;
        } else if (value < bottom_teir && touching == bottom_teir) {
            teirs[value] = Teir(bottom_teir,value,0,0,0,0);
            teirs[bottom_teir].teir_below = value;
            bottom_teir = value;
        } else {
            uint above;
            uint below;
            if(value > touching) {
                above = teirs[touching].teir_above;
                below = touching;
                if(value > above) throw;
            } else if(value < touching) {
                above = touching;
                below = teirs[touching].teir_below;
                if(value < below) throw;
            }

            teirs[value] = Teir(above,value,below,0,0,0);
            teirs[above].teir_below = value;
            teirs[below].teir_above = value;
        }

        total_teirs++;
    }

    function removeTeir_internal (uint value) internal {
        uint teir_below = teirs[value].teir_below;
        uint teir_above = teirs[value].teir_above;

        if (value == top_teir && value == bottom_teir) {
            top_teir = 0;
            bottom_teir = 0;
        } else if (value == top_teir) {
            teirs[teir_below].teir_above = 0;
            top_teir = teir_below;
        } else if (value == bottom_teir) {
            teirs[teir_above].teir_below = 0;
            bottom_teir = teir_above;
        } else {
            teirs[teir_above].teir_below = teir_below;
            teirs[teir_below].teir_above = teir_above;
        }

        delete teirs[value];
        total_teirs--;
    }

    function addNewBid_internal () internal {
        current_bids_open++;
        total_bids_made++;
        uint new_bid_id = total_bids_made;

        teirs[msg.value].line[new_bid_id] = SpotInLine(back_of_line_id,new_bid_id,0);

        if (teirs[msg.value].line_length == 0)
            teirs[msg.value].front_of_line_id = new_bid_id;

        uint back_of_line_id = teirs[msg.value].back_of_line_id;
        if (back_of_line_id != 0)
            teirs[msg.value].line[back_of_line_id].prev = new_bid_id;

        teirs[msg.value].back_of_line_id = new_bid_id;
        teirs[msg.value].line_length++;

        bids[new_bid_id] = Bid(new_bid_id,msg.sender,msg.value,false,false);
        bidders[msg.sender].current_bids_open++;
        bidders[msg.sender].total_bids_made++;
        uint total_bids = bidders[msg.sender].total_bids_made;
        bidders[msg.sender].bids[total_bids] = new_bid_id;

        NewBid_event(msg.sender,new_bid_id,msg.value);
    }

    function removeBid_internal (uint bid_id) internal {
        Bid bid = bids[bid_id];
        if(teirs[bid.value].line_length == 0) throw;
        if(bid.accepted || bid.cancelled) throw;

        uint front_of_line_id = teirs[bid.value].front_of_line_id;
        uint back_of_line_id = teirs[bid.value].back_of_line_id;
        if (bid.id == front_of_line_id) {
            uint prev = teirs[bid.value].line[bid.id].prev;
            teirs[bid.value].front_of_line_id = prev;
            teirs[bid.value].line[prev].prev = 0;
        } else if (bid.id == back_of_line_id) {
            uint next = teirs[bid.value].line[bid.id].next;
            teirs[bid.value].back_of_line_id = next;
            teirs[bid.value].line[next].prev = 0;
        } else {
            uint front_id = teirs[bid.value].line[bid.id].next;
            uint back_id = teirs[bid.value].line[bid.id].prev;
            teirs[bid.value].line[front_id].prev = back_id;
            teirs[bid.value].line[back_id].next = front_id;
        }

        delete teirs[bid.value].line[bid_id];
        teirs[bid.value].line_length--;

        bidders[msg.sender].current_bids_open--;
        current_bids_open--;

        if(teirs[bid.value].line_length == 0)
            removeTeir_internal(bid.value);
    }

////////////////
// Structs and Events
////////////////

    struct SpotInLine {
        uint next;
        uint bid_id;
        uint prev;
    }

    struct Bidder {
        uint current_bids_open;
        uint total_bids_made;
        mapping (uint => uint) bids;
    }

    struct Bid {
        uint id;
        address owner;
        uint value;
        bool cancelled;
        bool accepted;
    }

    struct Teir {
        uint teir_above;
        uint value;
        uint teir_below;

        uint front_of_line_id;
        uint back_of_line_id;
        uint line_length;
        mapping (uint => SpotInLine) line; //FIFO DLL
    }

    event NewBid_event(address bidder, uint bid_id, uint value);
}

contract MeDao is Tokenized {

    string public version = '0.0.2';

    address public Founder;

    OngoingAuction public Auction;

    uint public weekly_auction_reward;
    uint public scheduled_auction_timestamp;
    uint public auction_period;

    uint public total_proof_of_work;

    uint public cooldown_timestamp;
    uint burn_minimum = 1;

////////////////
// MeDao Functions
////////////////

    function MeDao (address founder, OngoingAuction auction) {
        Founder = founder;
        Auction = auction;
    }

    function startAuction () isScheduled {
        uint winning_bid_id = Auction.startAuction(withdraw_address);
        address winner = Auction.getBidOwner(winning_bid_id);
        uint winning_bid_value = Auction.getBidValue(winning_bid_id);

        Token.generateTokens(winner, 1 hours);

        AuctionWinner_event(winner,winning_bid_value);
    }

    function submitProofOfWork (uint burnAmount, string metadataHash)
    onlyTokenHolders(burn_minimum) {
        if(Token.balanceOf(msg.sender) < burnAmount) throw;

        Token.destroyTokens(msg.sender,burnAmount);
        total_proof_of_work += burnAmount;

        ProofOfWork_event(msg.sender,burnAmount,metadataHash);
    }

////////////////
// Owner Only
////////////////

    function setWeeklyAuctionReward (uint8 reward) onlyOwner
    hasCooldown(7 days) {
        if(reward > 40 hours || reward == 0) throw;

        weekly_auction_reward = reward;
        auction_period = 5 minutes; //set to 5 minutes for testing normally use:
                                    //7 days / auction_reward;
        scheduled_auction_timestamp = now + auction_period;

        NewWeeklyAuctionReward_event(weekly_auction_reward);
    }

    function setBurnMinimum (uint burnMinimum) onlyOwner {
        burn_minimum = burnMinimum;
    }

////////////////
// Events and Modifiers
////////////////

    modifier isScheduled () {
        if (scheduled_auction_timestamp == 0) throw;
        if (now < scheduled_auction_timestamp) throw;

        if(now < scheduled_auction_timestamp + auction_period)
            scheduled_auction_timestamp += auction_period;
        else
            scheduled_auction_timestamp = now + auction_period;

        _;
    }

    modifier onlyAuction () {
        if (msg.sender != address(Auction)) throw;

        _;
    }

    modifier hasCooldown (uint cooldown) {
        if(now < cooldown_timestamp) throw;

        cooldown_timestamp = now + cooldown;
        _;
    }

    event AuctionWinner_event (address winner, uint ether_bid);
    event ProofOfWork_event(address sender, uint amount, string metadataHash);
    event NewDepositAddress_event(address deposit_address);
    event NewWeeklyAuctionReward_event(uint new_auction_reward);
}

contract MeDaoRegistry {

    MiniMeToken PrimeToken;

    uint public total_medaos;
    mapping (uint => address) public founders;
    mapping (address => MeDao ) public medaos;

    function MeDaoRegistry (MiniMeToken Token) {
        PrimeToken = Token;
    }

    function register (string name) {
        if(medaos[msg.sender] != address(0x0)) throw;

        uint next_id = total_medaos++;
        founders[next_id] = msg.sender;

        OngoingAuction Auction = new OngoingAuction();

        medaos[msg.sender] = new MeDao(msg.sender,Auction);
        medaos[msg.sender].setupToken(msg.sender,PrimeToken,name,0,'seconds',0,true);
        medaos[msg.sender].transferOwnership(msg.sender);
        Auction.transferOwnership(medaos[msg.sender]);

        NewMeDao_event(msg.sender, medaos[msg.sender]);
    }

    event NewMeDao_event(address founder, address medao);
}

pragma solidity ^0.4.11;

import "MiniMeToken.sol";

contract ERC20Token {
    function transfer(address _to, uint256 _value) returns (bool success);
    function balanceOf(address _owner) constant returns (uint256 balance);
}

contract Owned {
    address public owner;

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

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

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

/*
    Copyright 2017, Joseph Reed

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/// @title MeDao Contract
/// @author Joseph Reed
/// @dev A MeDao aims to let anyone issue time shares for themselves. The issuer
///      should talk to shareholders for advice on how to maximize value for
///      themselves and for shareholders. Up to 40 hours worth of time are
///      auctioned off each week. The Owner of the MeDao is expected to burn
///      a certain amount of tokens each week negotiated between the Owner
///      and the Shareholders and thus will be diffrent for every MeDao. For
///      more info go to <github link here>.

contract Tokenized is Owned {

    MiniMeToken public Token;
    address public withdraw_address;

    function setupToken (
        address withdrawAddress,
        MiniMeToken CloneableToken,
        string _tokenName,
        uint8 _decimals,
        string _symbol,
        uint _snapshotBlock,
        bool _transfersEnabled
    ) onlyOwner {
        withdraw_address = withdrawAddress;
        address token = CloneableToken.createCloneToken(
            _tokenName,
            _decimals,
            _symbol,
            _snapshotBlock,
            _transfersEnabled
        );

        Token = MiniMeToken(token);
    }

    function withdrawEther () onlyOwner {
        var balance = this.balance;
        withdraw_address.transfer(balance);

        WithdrawEther_event(withdraw_address,balance);
    }

    function withdrawERC20Token (address Token) onlyOwner {
        uint tokenBalance = ERC20Token(Token).balanceOf(this);
        ERC20Token(Token).transfer(withdraw_address,tokenBalance);

        WithdrawToken_event(withdraw_address,Token,tokenBalance);
    }

    function updateDepositAddress (address _newDepositAddress) onlyOwner {
        withdraw_address = _newDepositAddress;

        NewWithdrawAddress_event(withdraw_address);
    }

    function () payable {
        withdraw_address.transfer(msg.value);

        Payable_event(msg.sender,msg.value);
    }

    modifier onlyTokenHolders (uint _minimum_needed) {
        uint tokens = Token.balanceOf(msg.sender);
        if(tokens < _minimum_needed) throw;
        _;
    }

    event Payable_event(address sender, uint amount);
    event WithdrawEther_event(address withdrawAddress, uint amount);
    event WithdrawToken_event(address withdrawAddress, address token, uint amount);
    event NewWithdrawAddress_event(address withdraw_address);
}

contract OngoingAuction is Owned {

    uint public current_bids_open;
    uint public total_bids_made;
    mapping (uint => Bid) public bids;
    mapping (address => Bidder) public bidders;

    uint public top_teir;
    uint public bottom_teir;
    uint public total_teirs;
    mapping (uint => Teir) public teirs; //DLL

////////////////
// Auction Functions
////////////////

    function placeBid (uint touchingTeir) payable {
        if(msg.value == 0) throw;

        if(teirs[msg.value].line_length == 0) {
            if(teirs[touchingTeir].line_length == 0 && top_teir != 0) throw;

            addNewTeir_internal(touchingTeir);
        }

        addNewBid_internal();
    }

    function removeBid (uint bid_id) {
        if (msg.sender != bids[bid_id].owner) throw;

        removeBid_internal(bid_id);
        bids[bid_id].cancelled = true;

        if (!bids[bid_id].owner.send(bids[bid_id].value)) throw;
    }

    function startAuction () onlyOwner {
        uint winning_bid_id = acceptHighestBid();
        address winner = bids[winning_bid_id].owner;
        uint bidValue = bids[winning_bid_id].value;

        MeDao(owner).declareAuctionWinner(winner,bidValue);
    }

    function getBids (address bidder) constant returns (uint[]) {
        uint total_bids = bidders[bidder].total_bids_made;
        uint[] memory all_bids = new uint[](total_bids);

        for(uint i = 0; i < total_bids; i++)
            all_bids[i] = bidders[bidder].bids[i+1];

        return all_bids;
    }

    function getTeirs () constant returns (uint[]) {
        uint[] memory all_teirs = new uint[](total_teirs);
        uint current_teir = teirs[top_teir].value;
        for (uint i = 0; i < total_teirs; i++) {
            all_teirs[i] = current_teir;
            current_teir = teirs[current_teir].teir_below;
        }

        return all_teirs;
    }

////////////////
// Internal Functions
////////////////

    function acceptHighestBid () internal returns (uint) {
        if(top_teir == 0) throw;

        uint highest_bid_id = teirs[top_teir].front_of_line_id;
        bids[highest_bid_id].accepted = true;
        removeBid_internal(highest_bid_id);

        return highest_bid_id;
    }

    function addNewTeir_internal (uint touching) internal {
        uint value = msg.value;

        if (top_teir == 0) {
            teirs[value] = Teir(0,value,0,0,0,0);
            top_teir = value;
            bottom_teir = value;
        } else if (value > top_teir && touching == top_teir) {
            teirs[value] = Teir(0,value,top_teir,0,0,0);
            teirs[top_teir].teir_above = value;
            top_teir = value;
        } else if (value < bottom_teir && touching == bottom_teir) {
            teirs[value] = Teir(bottom_teir,value,0,0,0,0);
            teirs[bottom_teir].teir_below = value;
            bottom_teir = value;
        } else {
            uint above;
            uint below;
            if(value > touching) {
                above = teirs[touching].teir_above;
                below = touching;
                if(value > above) throw;
            } else if(value < touching) {
                above = touching;
                below = teirs[touching].teir_below;
                if(value < below) throw;
            }

            teirs[value] = Teir(above,value,below,0,0,0);
            teirs[above].teir_below = value;
            teirs[below].teir_above = value;
        }

        total_teirs++;
    }

    function removeTeir_internal (uint value) internal {
        uint teir_below = teirs[value].teir_below;
        uint teir_above = teirs[value].teir_above;

        if (value == top_teir && value == bottom_teir) {
            top_teir = 0;
            bottom_teir = 0;
        } else if (value == top_teir) {
            teirs[teir_below].teir_above = 0;
            top_teir = teir_below;
        } else if (value == bottom_teir) {
            teirs[teir_above].teir_below = 0;
            bottom_teir = teir_above;
        } else {
            teirs[teir_above].teir_below = teir_below;
            teirs[teir_below].teir_above = teir_above;
        }

        delete teirs[value];
        total_teirs--;
    }

    function addNewBid_internal () internal {
        current_bids_open++;
        total_bids_made++;
        uint new_bid_id = total_bids_made;

        teirs[msg.value].line[new_bid_id] = SpotInLine(back_of_line_id,new_bid_id,0);

        if (teirs[msg.value].line_length == 0)
            teirs[msg.value].front_of_line_id = new_bid_id;

        uint back_of_line_id = teirs[msg.value].back_of_line_id;
        if (back_of_line_id != 0)
            teirs[msg.value].line[back_of_line_id].prev = new_bid_id;

        teirs[msg.value].back_of_line_id = new_bid_id;
        teirs[msg.value].line_length++;

        bids[new_bid_id] = Bid(new_bid_id,msg.sender,msg.value,false,false);
        bidders[msg.sender].current_bids_open++;
        bidders[msg.sender].total_bids_made++;
        uint total_bids = bidders[msg.sender].total_bids_made;
        bidders[msg.sender].bids[total_bids] = new_bid_id;

        NewBid_event(msg.sender,new_bid_id,msg.value);
    }

    function removeBid_internal (uint bid_id) internal {
        Bid bid = bids[bid_id];
        if(teirs[bid.value].line_length == 0) throw;
        if(bid.accepted || bid.cancelled) throw;

        uint front_of_line_id = teirs[bid.value].front_of_line_id;
        uint back_of_line_id = teirs[bid.value].back_of_line_id;
        if (bid.id == front_of_line_id) {
            uint prev = teirs[bid.value].line[bid.id].prev;
            teirs[bid.value].front_of_line_id = prev;
            teirs[bid.value].line[prev].prev = 0;
        } else if (bid.id == back_of_line_id) {
            uint next = teirs[bid.value].line[bid.id].next;
            teirs[bid.value].back_of_line_id = next;
            teirs[bid.value].line[next].prev = 0;
        } else {
            uint front_id = teirs[bid.value].line[bid.id].next;
            uint back_id = teirs[bid.value].line[bid.id].prev;
            teirs[bid.value].line[front_id].prev = back_id;
            teirs[bid.value].line[back_id].next = front_id;
        }

        delete teirs[bid.value].line[bid_id];
        teirs[bid.value].line_length--;

        bidders[msg.sender].current_bids_open--;
        current_bids_open--;

        if(teirs[bid.value].line_length == 0)
            removeTeir_internal(bid.value);
    }

////////////////
// Structs and Events
////////////////

    struct SpotInLine {
        uint next;
        uint bid_id;
        uint prev;
    }

    struct Bidder {
        uint current_bids_open;
        uint total_bids_made;
        mapping (uint => uint) bids;
    }

    struct Bid {
        uint id;
        address owner;
        uint value;
        bool cancelled;
        bool accepted;
    }

    struct Teir {
        uint teir_above;
        uint value;
        uint teir_below;

        uint front_of_line_id;
        uint back_of_line_id;
        uint line_length;
        mapping (uint => SpotInLine) line; //FIFO DLL
    }

    event NewBid_event(address bidder, uint bid_id, uint value);
}

contract MeDao is Tokenized {

    string public version = '0.0.2';

    address public Founder;

    OngoingAuction public Auction;

    uint public weekly_auction_reward;
    uint public scheduled_auction_timestamp;
    uint public auction_period;

    uint public total_proof_of_work;

    uint public cooldown_timestamp;
    uint burn_minimum = 1;

////////////////
// MeDao Functions
////////////////

    function MeDao (address founder, OngoingAuction auction) {
        Founder = founder;
        Auction = auction;
    }

    function startAuction () isScheduled {
        Auction.startAuction();
    }

    function declareAuctionWinner (address winner, uint bidValue) payable
    onlyAuction {
        withdraw_address.transfer(bidValue);
        Token.generateTokens(winner, 1 hours);

        AuctionWinner_event(winner,bidValue);
    }

    function submitProofOfWork (uint burnAmount, string metadataHash)
    onlyTokenHolders(burn_minimum) {
        if(Token.balanceOf(msg.sender) < burnAmount) throw;

        Token.destroyTokens(msg.sender,burnAmount);
        total_proof_of_work += burnAmount;

        ProofOfWork_event(msg.sender,burnAmount,metadataHash);
    }

////////////////
// Owner Only
////////////////

    function setWeeklyAuctionReward (uint8 reward) onlyOwner
    hasCooldown(7 days) {
        if(reward > 40 hours || reward == 0) throw;

        weekly_auction_reward = reward;
        auction_period = 5 minutes; //set to 5 minutes for testing normally use:
                                    //7 days / auction_reward;
        scheduled_auction_timestamp = now + auction_period;

        NewWeeklyAuctionReward_event(weekly_auction_reward);
    }

    function setBurnMinimum (uint burnMinimum) onlyOwner {
        burn_minimum = burnMinimum;
    }

////////////////
// Events and Modifiers
////////////////

    modifier isScheduled () {
        if (scheduled_auction_timestamp == 0) throw;
        if (now < scheduled_auction_timestamp) throw;

        if(now < scheduled_auction_timestamp + auction_period)
            scheduled_auction_timestamp += auction_period;
        else
            scheduled_auction_timestamp = now + auction_period;

        _;
    }

    modifier onlyAuction () {
        if (msg.sender != address(Auction)) throw;

        _;
    }

    modifier hasCooldown (uint cooldown) {
        if(now < cooldown_timestamp) throw;

        cooldown_timestamp = now + cooldown;
        _;
    }

    event AuctionWinner_event (address winner, uint ether_bid);
    event ProofOfWork_event(address sender, uint amount, string metadataHash);
    event NewDepositAddress_event(address deposit_address);
    event NewWeeklyAuctionReward_event(uint new_auction_reward);
}

contract MeDaoRegistry {

    MiniMeToken PrimeToken;

    uint public total_medaos;
    mapping (uint => address) public founders;
    mapping (address => MeDao ) public medaos;

    function MeDaoRegistry (MiniMeToken Token) {
        PrimeToken = Token;
    }

    function register (string name) {
        if(medaos[msg.sender] != address(0x0)) throw;

        uint next_id = total_medaos++;
        founders[next_id] = msg.sender;

        OngoingAuction Auction = new OngoingAuction();

        medaos[msg.sender] = new MeDao(msg.sender,Auction);
        medaos[msg.sender].setupToken(msg.sender,Token,name,0,'seconds',0,true);
        medaos[msg.sender].transferOwnership(msg.sender);
        Auction.transferOwnership(medaos[msg.sender]);

        NewMeDao_event(msg.sender, medaos[msg.sender]);
    }

    event NewMeDao_event(address founder, address medao);
}