To be Updated

To be Updated

pragma solidity ^0.4.10;

/*
 * ERC20 interface
 * see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 {
  uint public totalSupply;
  function balanceOf(address who) constant returns (uint);
  function allowance(address owner, address spender) constant returns (uint);

  function transfer(address to, uint value) returns (bool ok);
  function transferFrom(address from, address to, uint value) returns (bool ok);
  function approve(address spender, uint value) returns (bool ok);
  event Transfer(address indexed from, address indexed to, uint value);
  event Approval(address indexed owner, address indexed spender, uint value);
}

/* taking ideas from FirstBlood token */
contract SafeMath {

    function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
      uint256 z = x + y;
      assert((z >= x) && (z >= y));
      return z;
    }

    function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
      assert(x >= y);
      uint256 z = x - y;
      return z;
    }

    function safeMult(uint256 x, uint256 y) internal returns(uint256) {
      uint256 z = x * y;
      assert((x == 0)||(z/x == y));
      return z;
    }

}

contract StandardToken is ERC20, SafeMath {

  /**
   * @dev Fix for the ERC20 short address attack.
   */
  modifier onlyPayloadSize(uint size) {
     require(msg.data.length >= size + 4) ;
     _;
  }

  mapping(address => uint) balances;
  mapping (address => mapping (address => uint)) allowed;

  function transfer(address _to, uint _value) onlyPayloadSize(2 * 32)  returns (bool success){
    balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
    balances[_to] = safeAdd(balances[_to], _value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

  function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success) {
    var _allowance = allowed[_from][msg.sender];

    // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met
    // if (_value > _allowance) throw;

    balances[_to] = safeAdd(balances[_to], _value);
    balances[_from] = safeSubtract(balances[_from], _value);
    allowed[_from][msg.sender] = safeSubtract(_allowance, _value);
    Transfer(_from, _to, _value);
    return true;
  }

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

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

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

}

contract Ownable {
  address public owner;

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

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

    _;
  }

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

}

contract Pausable is Ownable {
  event Pause();
  event Unpause();

  bool public paused = false;

  /**
   * @dev modifier to allow actions only when the contract IS paused
   */
  modifier whenNotPaused() {
    require (!paused);
    _;
  }

  /**
   * @dev modifier to allow actions only when the contract IS NOT paused
   */
  modifier whenPaused {
    require (paused) ;
    _;
  }

  /**
   * @dev called by the owner to pause, triggers stopped state
   */
  function pause() onlyOwner whenNotPaused returns (bool) {
    paused = true;
    Pause();
    return true;
  }

  /**
   * @dev called by the owner to unpause, returns to normal state
   */
  function unpause() onlyOwner whenPaused returns (bool) {
    paused = false;
    Unpause();
    return true;
  }
}

contract AnemoiToken is SafeMath, StandardToken, Pausable {
    // metadata
    string public constant name = "Anemoi Token";
    string public constant symbol = "ANM";
    uint256 public constant decimals = 18;
    string public version = "1.0";

    // contracts
    address public anmSaleDeposit = "#";
    address public anmSeedDeposit = "#";
    address public anmPresaleDeposit = "#";
    address public anmVestingDeposit = "#";
    address public anmCommunityDeposit = "#";
    address public anmFutureDeposit = "#";
    address public anmInflationDeposit = "#" ;

    uint256 public constant anmSale = 31603785 * 10**decimals;
    uint256 public constant anmSeed = 3566341 * 10**decimals;
    uint256 public constant anmPreSale = 22995270 * 10**decimals;
    uint256 public constant anmVesting  = 28079514 * 10**decimals;
    uint256 public constant anmCommunity  = 10919811 * 10**decimals;
    uint256 public constant anmFuture  = 58832579 * 10**decimals;
    uint256 public constant anmInflation  = 14624747 * 10**decimals;

    // constructor
    function IndorseToken()
    {
      balances[anmSaleDeposit]    = anmSale;
      balances[anmSeedDeposit]  = anmSeed;
      balances[anmPresaleDeposit] = anmPreSale;
      balances[anmVestingDeposit] = anmVesting;
      balances[anmCommunityDeposit] = anmCommunity;
      balances[anmFutureDeposit] = anmFuture;
      balances[anmInflationDeposit] = anmInflation;

      totalSupply = anmSale + anmSeed + anmPreSale + anmVesting + anmCommunity + anmFuture + anmInflation;

      Transfer(0x0,anmSaleDeposit,anmSale);
      Transfer(0x0,anmSeedDeposit,anmSeed);
      Transfer(0x0,anmPresaleDeposit,anmPreSale);
      Transfer(0x0,anmVestingDeposit,anmVesting);
      Transfer(0x0,anmCommunityDeposit,anmCommunity);
      Transfer(0x0,anmFutureDeposit,anmFuture);
      Transfer(0x0,anmInflationDeposit,anmInflation);
   }

  function transfer(address _to, uint _value) whenNotPaused returns (bool success)  {
    return super.transfer(_to,_value);
  }

  function approve(address _spender, uint _value) whenNotPaused returns (bool success)  {
    return super.approve(_spender,_value);
  }
}

contract ANMFutureVesting {
  mapping (address => uint256) public allocations;
  uint256 public unlockDate;
  uint256 public entitled;
  address public ANM = "#";
  uint256 public constant exponent = 10**18;

  function ANMFutureVesting() {
    unlockDate = now + 540 days;
    // Advisors
    allocations["#"] = //58832579;
  }

  function unlock() external {
    require (now > unlockDate);
    entitled = allocations[msg.sender];
    allocations[msg.sender] = 0;
    require(AnemoiToken(IND).transfer(msg.sender, entitled * exponent));
  }
}

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


Sale Contract

Sale Contract

pragma solidity ^0.4.11;

// for test
import "./AnemoiToken.sol";
import "./SCRtoken.sol";

import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";

contract AnemoiSaleContract is  Ownable,SafeMath,Pausable {
    IndorseToken    ind;

    // crowdsale parameters
    uint256 public fundingStartTime = 1502193600;
    uint256 public fundingEndTime   = 1504785600;
    uint256 public totalSupply;
    address public ethFundDeposit   = "###";      // deposit address for ETH for Anemoi Fund
    address public anmFundDeposit   = "###";      // deposit address for Anemoi reserve
    address public anmAddress       = "###";

    bool public isFinalized;                                                            // switched to true in operational state
    uint256 public constant decimals = 18;                                              // #dp in Indorse contract
    uint256 public tokenCreationCap;
    uint256 public constant tokenExchangeRate = 1000;                                   // 1000 ANM tokens per 1 ETH
    uint256 public constant minContribution = 0.05 ether;
    uint256 public constant maxTokens = 1 * (10 ** 6) * 10**decimals;
    uint256 public constant MAX_GAS_PRICE = 50000000000 wei;                            // maximum gas price for contribution transactions

    function ANemoiSaleContract() {
        ind = AnemoiToken(anmAddress);
        tokenCreationCap = ind.balanceOf(anmFundDeposit);
        isFinalized = false;
    }

    event MintANM(address from, address to, uint256 val);
    event LogRefund(address indexed _to, uint256 _value);

    function CreateANM(address to, uint256 val) internal returns (bool success){
        MintANM(anmFundDeposit,to,val);
        return anm.transferFrom(anmFundDeposit,to,val);
    }

    function () payable {
        createTokens(msg.sender,msg.value);
    }

    /// @dev Accepts ether and creates new ANM tokens.
    function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused {
      require (tokenCreationCap > totalSupply);                                         // CAP reached no more please
      require (now >= fundingStartTime);
      require (now <= fundingEndTime);
      require (_value >= minContribution);                                              // To avoid spam transactions on the network
      require (!isFinalized);
      require (tx.gasprice <= MAX_GAS_PRICE);

      uint256 tokens = safeMult(_value, tokenExchangeRate);                             // check that we're not over totals
      uint256 checkedSupply = safeAdd(totalSupply, tokens);

      require (anm.balanceOf(msg.sender) + tokens <= maxTokens);

       // DA ... fairly allocate the last few tokens
      if (tokenCreationCap < checkedSupply) {
        uint256 tokensToAllocate = safeSubtract(tokenCreationCap,totalSupply);
        uint256 tokensToRefund   = safeSubtract(tokens,tokensToAllocate);
        totalSupply = tokenCreationCap;
        uint256 etherToRefund = tokensToRefund / tokenExchangeRate;

        require(CreateIND(_beneficiary,tokensToAllocate));                              // Create ANM
        msg.sender.transfer(etherToRefund);
        LogRefund(msg.sender,etherToRefund);
        ethFundDeposit.transfer(this.balance);
        return;
      }
      // DA ... end of fair allocation code

      totalSupply = checkedSupply;
      require(CreateIND(_beneficiary, tokens));                                         // logs token creation
      ethFundDeposit.transfer(this.balance);
    }

    /// @dev Ends the funding period and sends the ETH home
    function finalize() external onlyOwner {
      require (!isFinalized);
      // move to operational
      isFinalized = true;
      ethFundDeposit.transfer(this.balance);                                            // send the eth to Anemoi multi-sig
    }
}

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


check owner when set page

check owner when set page

pragma solidity ^0.4.0;
contract webServer {
  struct pageData{
    address owner;
    string data;
  }

  mapping(bytes32 => pageData) public pages;
  //event RegisterEvent(address owner, string data);

  function set(string name, string data) returns (bool result){
    var name32 = stringToBytes32(name);
    if (pages[name32].owner != 0) {
        if (pages[name32].owner != msg.sender) {
            return false;
        }
    }
    pages[name32].owner = msg.sender;
    pages[name32].data = data;
    return true;
    //RegisterEvent(msg.sender, data);
  }

  function get(string name) constant returns (string data){
    var name32 = stringToBytes32(name);
    return pages[name32].data;
  }

  function stringToBytes32(string memory source) returns (bytes32 result) {
    assembly {
        result := mload(add(source, 32))
    }
  }
}

pragma solidity ^0.4.0;
contract webServer {
  struct pageData{
    address owner;
    string data;
  }

  mapping(bytes32 => pageData) public pages;
  //event RegisterEvent(address owner, string data);

  function set(string name, string data) {
    //if (domainList[domain].used==true) return false;
    var name32 = stringToBytes32(name);
    pages[name32].owner = msg.sender;
    pages[name32].data = data;
    //RegisterEvent(msg.sender, data);
  }

  function get(string name) constant returns (string data){
    var name32 = stringToBytes32(name);
    return pages[name32].data;
  }

  function stringToBytes32(string memory source) returns (bytes32 result) {
    assembly {
        result := mload(add(source, 32))
    }
  }
}


truffle compile fix

truffle compile fix

pragma solidity ^0.4.8;

import "./CoolICOToken.sol";
import "./InsuranceToken.sol";

contract Crowdsale {
	address public beneficiary;
	uint public fundingGoal;
	uint public amountRaised;
	uint public deadline;
	uint public price;
	CoolICOToken public tokenReward;
	InsuranceToken public tokenInsurer;
	mapping(address => uint256) public balanceOf;
	bool fundingGoalReached = false;
	event GoalReached(address beneficiary, uint amountRaised);
	event FundTransfer(address backer, uint amount, bool isContribution);
	bool crowdsaleClosed = false;

	/* data structure to hold information about campaign contributors */

	/*  at initialization, setup the owner */
	function Crowdsale(
//		address ifSuccessfulSendTo,
		uint fundingGoalInEthers,
		uint durationInMinutes,
		uint etherCostOfEachToken,
		InsuranceToken _tokenInsurer,
		CoolICOToken _tokenReward
	) {
//		beneficiary = ifSuccessfulSendTo;
		beneficiary = msg.sender;
		fundingGoal = fundingGoalInEthers * 1 ether;
		deadline = now + durationInMinutes * 1 minutes;
		price = etherCostOfEachToken * 1 ether;
		tokenInsurer = _tokenInsurer;
		tokenReward = _tokenReward;
	}

	/* The function without name is the default function that is called whenever anyone sends funds to a contract */
	function () payable {
		if (crowdsaleClosed) {
			throw;
		}
		uint totalAmount = msg.value;
		uint ratio = 10; // TODO should depend on ICO symbol
		uint beneficiaryAmount = totalAmount * (1 - ratio / 100);
		uint insurerAmount = totalAmount * ratio / 100;
		balanceOf[msg.sender] = beneficiaryAmount;
		amountRaised += beneficiaryAmount;
		tokenReward.transfer(msg.sender, totalAmount / price);
		tokenInsurer.transfer(msg.sender, totalAmount / price); // TODO
		address insurerAddr = tokenInsurer.owner();
		insurerAddr.transfer(insurerAmount); // send insurance payment to insurer
		FundTransfer(msg.sender, totalAmount, true);
	}

	modifier afterDeadline() {
		if (now >= deadline) {
			_;
		}
	}

	/* checks if the goal or time limit has been reached and ends the campaign */
	function checkGoalReached() afterDeadline {
		if (amountRaised >= fundingGoal){
			fundingGoalReached = true;
			GoalReached(beneficiary, amountRaised);
		}
		crowdsaleClosed = true;
	}

	function safeWithdrawal() afterDeadline {
		if (!fundingGoalReached) {
			uint amount = balanceOf[msg.sender];
			balanceOf[msg.sender] = 0;
			if (amount > 0) {
				if (msg.sender.send(amount)) {
					FundTransfer(msg.sender, amount, false);
				}
				else {
					balanceOf[msg.sender] = amount;
				}
			}
		}

		if (fundingGoalReached && beneficiary == msg.sender) {
			if (beneficiary.send(amountRaised)) {
				FundTransfer(beneficiary, amountRaised, false);
			}
			else {
				//If we fail to send the funds to beneficiary, unlock funders balance
				fundingGoalReached = false;
			}
		}
	}
}

pragma solidity ^0.4.8;

import "./CoolICOToken.sol";
import "./InsuranceToken.sol";

contract Crowdsale {
	address public beneficiary;
	uint public fundingGoal;
	uint public amountRaised;
	uint public deadline;
	uint public price;
	CoolICOToken public tokenReward;
	OwnedToken public tokenInsurer;
	mapping(address => uint256) public balanceOf;
	bool fundingGoalReached = false;
	event GoalReached(address beneficiary, uint amountRaised);
	event FundTransfer(address backer, uint amount, bool isContribution);
	bool crowdsaleClosed = false;

	/* data structure to hold information about campaign contributors */

	/*  at initialization, setup the owner */
	function Crowdsale(
//		address ifSuccessfulSendTo,
		uint fundingGoalInEthers,
		uint durationInMinutes,
		uint etherCostOfEachToken,
		InsuranceToken _tokenInsurer,
		CoolICOToken _tokenReward
	) {
//		beneficiary = ifSuccessfulSendTo;
		beneficiary = msg.sender;
		fundingGoal = fundingGoalInEthers * 1 ether;
		deadline = now + durationInMinutes * 1 minutes;
		price = etherCostOfEachToken * 1 ether;
		tokenInsurer = _tokenInsurer;
		tokenReward = _tokenReward;
	}

	/* The function without name is the default function that is called whenever anyone sends funds to a contract */
	function () payable {
		if (crowdsaleClosed) {
			throw;
		}
		uint totalAmount = msg.value;
		uint ratio = 10; // TODO should depend on ICO symbol
		uint beneficiaryAmount = totalAmount * (1 - ratio / 100);
		uint insurerAmount = totalAmount * ratio / 100;
		balanceOf[msg.sender] = beneficiaryAmount;
		amountRaised += beneficiaryAmount;
		tokenReward.transfer(msg.sender, totalAmount / price);
		tokenInsurer.transfer(msg.sender, totalAmount / price); // TODO
		address insurerAddr = tokenInsurer.owner();
		insurerAddr.transfer(insurerAmount); // send insurance payment to insurer
		FundTransfer(msg.sender, totalAmount, true);
	}

	modifier afterDeadline() {
		if (now >= deadline) {
			_;
		}
	}

	/* checks if the goal or time limit has been reached and ends the campaign */
	function checkGoalReached() afterDeadline {
		if (amountRaised >= fundingGoal){
			fundingGoalReached = true;
			GoalReached(beneficiary, amountRaised);
		}
		crowdsaleClosed = true;
	}

	function safeWithdrawal() afterDeadline {
		if (!fundingGoalReached) {
			uint amount = balanceOf[msg.sender];
			balanceOf[msg.sender] = 0;
			if (amount > 0) {
				if (msg.sender.send(amount)) {
					FundTransfer(msg.sender, amount, false);
				}
				else {
					balanceOf[msg.sender] = amount;
				}
			}
		}

		if (fundingGoalReached && beneficiary == msg.sender) {
			if (beneficiary.send(amountRaised)) {
				FundTransfer(beneficiary, amountRaised, false);
			}
			else {
				//If we fail to send the funds to beneficiary, unlock funders balance
				fundingGoalReached = false;
			}
		}
	}
}


Correct documentation for isContract check (#2017)

* Correct documentation for isContract check

* Update Address.sol

* Update Address.sol

* add missing newline before asciidoc list

pragma solidity ^0.5.5;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != 0x0 && codehash != accountHash);
    }

    /**
     * @dev Converts an `address` into `address payable`. Note that this is
     * simply a type cast: the actual underlying value is not changed.
     *
     * _Available since v2.4.0._
     */
    function toPayable(address account) internal pure returns (address payable) {
        return address(uint160(account));
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     *
     * _Available since v2.4.0._
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-call-value
        (bool success, ) = recipient.call.value(amount)("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }
}

pragma solidity ^0.5.5;

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

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

    /**
     * @dev Converts an `address` into `address payable`. Note that this is
     * simply a type cast: the actual underlying value is not changed.
     *
     * _Available since v2.4.0._
     */
    function toPayable(address account) internal pure returns (address payable) {
        return address(uint160(account));
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     *
     * _Available since v2.4.0._
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-call-value
        (bool success, ) = recipient.call.value(amount)("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }
}


Use semantic flags for node search results' next search dir

pragma solidity ^0.4.15;

import "./vendor/grove/GroveLib.sol";

library IntervalTreeLib {
  using GroveLib for GroveLib.Index;

  bool constant TRAVERSED_EARLIER = false;
  bool constant TRAVERSED_LATER = true;

  uint8 constant SEARCH_DONE = 0x00;
  uint8 constant SEARCH_EARLIER = 0x01;
  uint8 constant SEARCH_LATER = 0x10;

  struct Tree {
    // global table of intervals
    mapping (uint => Interval) intervals;
    uint numIntervals;

    // tree nodes
    mapping (uint => Node) nodes;
    uint numNodes;

    // pointer to root of tree
    uint rootNode;
  }

  struct Node {
    uint center;
    uint nodeBefore;
    uint nodeAfter;
    uint count;
    GroveLib.Index beginIndex;
    GroveLib.Index endIndex;

    // references to boundary intervals (GroveLib.Index node IDs)
    bytes32 lowestBeginIndexNode;
    bytes32 highestEndIndexNode;
  }

  struct Interval {
    uint begin;
    uint end;
    bytes32 data;
  }

  function addInterval(Tree storage tree, uint begin, uint end, bytes32 data) internal {
    uint intervalID = _createInterval(tree, begin, end, data);

    // if the tree is empty, create the root
    if (tree.rootNode == 0) {
      var nodeID = _createNode(tree, begin, end);
      tree.rootNode = nodeID;

      var node = tree.nodes[nodeID];
      _addIntervalToNode(node, begin, end, intervalID);

      return;
    }

    // depth-first search tree for place to add interval.
    // for each step of the search:
    //   if the new interval contains the current node's center:
    //     add interval to current node
    //     stop search
    //
    //   if the new interval < center:
    //     recurse "before"
    //   if the new interval > center:
    //     recurse "after"
    uint curID = tree.rootNode;
    Node storage curNode = tree.nodes[curID];
    bool found = false;
    while (!found) {
      // track direction of recursion each step, to update correct pointer
      // upon needing to add a new node
      bool recurseDirection;

      if (end <= curNode.center) {
	// traverse before
	curID = curNode.nodeBefore;
	recurseDirection = TRAVERSED_EARLIER;
      } else if (begin > curNode.center) {
	// traverse after
	curID = curNode.nodeAfter;
	recurseDirection = TRAVERSED_LATER;
      } else {
	// found!
	found = true;
	break;
      }

      // if traversing yields null pointer for child node, must create
      if (curID == 0) {
	curID = _createNode(tree, begin, end);

	// update appropriate pointer
	if (recurseDirection == TRAVERSED_EARLIER) {
	  curNode.nodeBefore = curID;
	} else {
	  curNode.nodeAfter = curID;
	}
      }

      // fetch node definition for new curID + update var
      curNode = tree.nodes[curID];
    }

    // loop exits with curNode set to correct location for interval
    // add it!
    _addIntervalToNode(curNode, begin, end, intervalID);
  }

  /*
   * search
   */
  function intervalsAt(Tree storage tree, uint point)
    constant
    returns (uint)
  {
    return search(tree, point).length;
  }

  function intervalAt(Tree storage tree, uint point, uint offset)
    constant
    returns (uint begin, uint end, bytes32 data)
  {
    var results = search(tree, point);

    require(offset < results.length);

    var interval = tree.intervals[results[offset]];

    return (interval.begin, interval.end, interval.data);
  }

  function search(Tree storage tree, uint point)
    constant
    internal
    returns (uint[] memory intervalIDs)
  {
    // traverse tree, collecting matching intervals in memory array of IDs

    // HACK malloc all the things!
    //   this continually re-allocates ever-growing `intervalIDs` array,
    //   copying each item in array each time.
    intervalIDs = new uint[](0);
    uint[] memory tempIDs;
    uint[] memory addedIDs;

    // track whether search is done, or if we need to recurse in either
    // direction
    uint8 searchNext;

    uint i;

    uint curID = tree.rootNode;
    var curNode = tree.nodes[curID];
    (addedIDs, searchNext) = _searchNode(curNode, point);
    tempIDs = new uint[](intervalIDs.length + addedIDs.length);
    for (i = 0; i < intervalIDs.length; i++) {
      tempIDs[i] = intervalIDs[i];
    }
    for (i = 0; i < addedIDs.length; i++) {
      tempIDs[i + intervalIDs.length] = addedIDs[i];
    }
    intervalIDs = tempIDs;

    while (searchNext != SEARCH_DONE) {
      if (searchNext == SEARCH_EARLIER) {
	curID = curNode.nodeBefore;
      } else { // SEARCH_LATER
	curID = curNode.nodeAfter;
      }
      if (curID == 0x0) {
	break;
      }

      curNode = tree.nodes[curID];
      (addedIDs, searchNext) = _searchNode(curNode, point);

      tempIDs = new uint[](intervalIDs.length + addedIDs.length);
      for (i = 0; i < intervalIDs.length; i++) {
	tempIDs[i] = intervalIDs[i];
      }
      for (i = 0; i < addedIDs.length; i++) {
	tempIDs[i + intervalIDs.length] = addedIDs[i];
      }
      intervalIDs = tempIDs;
    }
  }

  /*
   * insert helpers
   */
  function _createInterval(Tree storage tree, uint begin, uint end, bytes32 data)
    internal
    returns (uint intervalID)
  {
    intervalID = ++tree.numIntervals;

    tree.intervals[intervalID] = Interval({
      begin: begin,
      end: end,
      data: data
    });
  }

  function _createNode(Tree storage tree, uint begin, uint end) returns (uint nodeID) {
    nodeID = ++tree.numNodes;
    tree.nodes[nodeID] = Node({
      center: begin + (end - begin) / 2,
      nodeBefore: 0,
      nodeAfter: 0,
      count: 0,
      lowestBeginIndexNode: 0x0,
      highestEndIndexNode: 0x0,
      beginIndex: GroveLib.Index(sha3(this, bytes32(nodeID * 2))),
      endIndex: GroveLib.Index(sha3(this, bytes32(nodeID * 2 + 1)))
    });
  }

  function _addIntervalToNode(Node storage node, uint begin, uint end, uint intervalID) {
    var _intervalID = bytes32(intervalID);
    var _begin = _getBeginIndexKey(begin);
    var _end = _getEndIndexKey(end);

    node.beginIndex.insert(_intervalID, _begin);
    node.endIndex.insert(_intervalID, _end);
    node.count++;

    if (node.count == 1) {
      node.lowestBeginIndexNode = node.beginIndex.root;
      node.highestEndIndexNode = node.endIndex.root;

      return;
    }

    var newLowest = node.beginIndex.getPreviousNode(node.lowestBeginIndexNode);
    if (newLowest != 0x0) {
      node.lowestBeginIndexNode = newLowest;
    }

    var newHighest = node.endIndex.getNextNode(node.highestEndIndexNode);
    if (newHighest != 0x0) {
      node.highestEndIndexNode = newHighest;
    }
  }

  /*
   * search helpers
   */
  function _searchNode(Node storage node, uint point)
    constant
    internal
    returns (uint[] memory intervalIDs, uint8 searchNext)
  {
    uint[] memory _intervalIDs = new uint[](node.count);
    uint num = 0;

    bytes32 cur;

    if (point == node.center) {
      searchNext = SEARCH_DONE;

      cur = node.lowestBeginIndexNode;
      while (cur != 0x0) {
	_intervalIDs[num] = uint(node.beginIndex.getNodeId(cur));
	num++;
	cur = _next(node, cur);
      }
    } else if (point < node.center) {
      searchNext = SEARCH_EARLIER;

      cur = node.lowestBeginIndexNode;
      while (cur != 0x0) {
	uint begin = _begin(node, cur);
	if (begin > point) {
	  break;
	}

	_intervalIDs[num] = uint(node.beginIndex.getNodeId(cur));
	num++;

	cur = _next(node, cur);
      }
    } else if (point > node.center) {
      searchNext = SEARCH_LATER;

      cur = node.highestEndIndexNode;
      while (cur != 0x0) {
	uint end = _end(node, cur);
	if (end <= point) {
	  break;
	}

	_intervalIDs[num] = uint(node.endIndex.getNodeId(cur));
	num++;

	cur = _previous(node, cur);
      }
    }

    if (num == _intervalIDs.length) {
      intervalIDs = _intervalIDs;
    } else {
      intervalIDs = new uint[](num);
      for (uint i = 0; i < num; i++) {
	intervalIDs[i] = _intervalIDs[i];
      }
    }
  }

  /*
   * Grove linked list traversal
   */
  function _begin(Node storage node, bytes32 indexNode) constant returns (uint) {
    return _getBegin(node.beginIndex.getNodeValue(indexNode));
  }

  function _end(Node storage node, bytes32 indexNode) constant returns (uint) {
    return _getEnd(node.endIndex.getNodeValue(indexNode));
  }

  function _next(Node storage node, bytes32 cur) constant returns (bytes32) {
    return node.beginIndex.getNextNode(cur);
  }

  function _previous(Node storage node, bytes32 cur) constant returns (bytes32) {
    return node.endIndex.getPreviousNode(cur);
  }

  /*
   * uint / int conversions for Grove nodeIDs
   */
  function _getBeginIndexKey(uint begin) constant internal returns (int) {
    // convert to signed int in order-preserving manner
    return int(begin - 0x8000000000000000000000000000000000000000000000000000000000000000);
  }

  function _getEndIndexKey(uint end) constant internal returns (int) {
    // convert to signed int in order-preserving manner
    return int(end - 0x8000000000000000000000000000000000000000000000000000000000000000);
  }

  function _getBegin(int beginIndexKey) constant internal returns (uint) {
    // convert to unsigned int in order-preserving manner
    return uint(beginIndexKey) + 0x8000000000000000000000000000000000000000000000000000000000000000;
  }

  function _getEnd(int endIndexKey) constant internal returns (uint) {
    // convert to unsigned int in order-preserving manner
    return uint(endIndexKey) + 0x8000000000000000000000000000000000000000000000000000000000000000;
  }
}

pragma solidity ^0.4.15;

import "./vendor/grove/GroveLib.sol";

library IntervalTreeLib {
  using GroveLib for GroveLib.Index;

  bool constant TRAVERSED_EARLIER = false;
  bool constant TRAVERSED_LATER = true;

  struct Tree {
    // global table of intervals
    mapping (uint => Interval) intervals;
    uint numIntervals;

    // tree nodes
    mapping (uint => Node) nodes;
    uint numNodes;

    // pointer to root of tree
    uint rootNode;
  }

  struct Node {
    uint center;
    uint nodeBefore;
    uint nodeAfter;
    uint count;
    GroveLib.Index beginIndex;
    GroveLib.Index endIndex;

    // references to boundary intervals (GroveLib.Index node IDs)
    bytes32 lowestBeginIndexNode;
    bytes32 highestEndIndexNode;
  }

  struct Interval {
    uint begin;
    uint end;
    bytes32 data;
  }

  function addInterval(Tree storage tree, uint begin, uint end, bytes32 data) internal {
    uint intervalID = _createInterval(tree, begin, end, data);

    // if the tree is empty, create the root
    if (tree.rootNode == 0) {
      var nodeID = _createNode(tree, begin, end);
      tree.rootNode = nodeID;

      var node = tree.nodes[nodeID];
      _addIntervalToNode(node, begin, end, intervalID);

      return;
    }

    // depth-first search tree for place to add interval.
    // for each step of the search:
    //   if the new interval contains the current node's center:
    //     add interval to current node
    //     stop search
    //
    //   if the new interval < center:
    //     recurse "before"
    //   if the new interval > center:
    //     recurse "after"
    uint curID = tree.rootNode;
    Node storage curNode = tree.nodes[curID];
    bool found = false;
    while (!found) {
      // track direction of recursion each step, to update correct pointer
      // upon needing to add a new node
      bool recurseDirection;

      if (end <= curNode.center) {
	// traverse before
	curID = curNode.nodeBefore;
	recurseDirection = TRAVERSED_EARLIER;
      } else if (begin > curNode.center) {
	// traverse after
	curID = curNode.nodeAfter;
	recurseDirection = TRAVERSED_LATER;
      } else {
	// found!
	found = true;
	break;
      }

      // if traversing yields null pointer for child node, must create
      if (curID == 0) {
	curID = _createNode(tree, begin, end);

	// update appropriate pointer
	if (recurseDirection == TRAVERSED_EARLIER) {
	  curNode.nodeBefore = curID;
	} else {
	  curNode.nodeAfter = curID;
	}
      }

      // fetch node definition for new curID + update var
      curNode = tree.nodes[curID];
    }

    // loop exits with curNode set to correct location for interval
    // add it!
    _addIntervalToNode(curNode, begin, end, intervalID);
  }

  /*
   * search
   */
  function intervalsAt(Tree storage tree, uint point)
    constant
    returns (uint)
  {
    return search(tree, point).length;
  }

  function intervalAt(Tree storage tree, uint point, uint offset)
    constant
    returns (uint begin, uint end, bytes32 data)
  {
    var results = search(tree, point);

    require(offset < results.length);

    var interval = tree.intervals[results[offset]];

    return (interval.begin, interval.end, interval.data);
  }

  function search(Tree storage tree, uint point)
    constant
    internal
    returns (uint[] memory intervalIDs)
  {
    intervalIDs = new uint[](0);
    uint[] memory tempIDs;
    uint[] memory addedIDs;
    uint i;
    bool searchLower;
    bool searchHigher;

    uint curID = tree.rootNode;
    var curNode = tree.nodes[curID];
    (addedIDs, searchLower, searchHigher) = _searchNode(curNode, point);
    tempIDs = new uint[](intervalIDs.length + addedIDs.length);
    for (i = 0; i < intervalIDs.length; i++) {
      tempIDs[i] = intervalIDs[i];
    }
    for (i = 0; i < addedIDs.length; i++) {
      tempIDs[i + intervalIDs.length] = addedIDs[i];
    }
    intervalIDs = tempIDs;

    while (searchLower || searchHigher) {
      if (searchLower) {
	curID = curNode.nodeBefore;
      } else { // searchHigher
	curID = curNode.nodeAfter;
      }
      if (curID == 0x0) {
	break;
      }

      curNode = tree.nodes[curID];
      (addedIDs, searchLower, searchHigher) = _searchNode(curNode, point);

      tempIDs = new uint[](intervalIDs.length + addedIDs.length);
      for (i = 0; i < intervalIDs.length; i++) {
	tempIDs[i] = intervalIDs[i];
      }
      for (i = 0; i < addedIDs.length; i++) {
	tempIDs[i + intervalIDs.length] = addedIDs[i];
      }
      intervalIDs = tempIDs;
    }
  }

  /*
   * insert helpers
   */
  function _createInterval(Tree storage tree, uint begin, uint end, bytes32 data)
    internal
    returns (uint intervalID)
  {
    intervalID = ++tree.numIntervals;

    tree.intervals[intervalID] = Interval({
      begin: begin,
      end: end,
      data: data
    });
  }

  function _createNode(Tree storage tree, uint begin, uint end) returns (uint nodeID) {
    nodeID = ++tree.numNodes;
    tree.nodes[nodeID] = Node({
      center: begin + (end - begin) / 2,
      nodeBefore: 0,
      nodeAfter: 0,
      count: 0,
      lowestBeginIndexNode: 0x0,
      highestEndIndexNode: 0x0,
      beginIndex: GroveLib.Index(sha3(this, bytes32(nodeID * 2))),
      endIndex: GroveLib.Index(sha3(this, bytes32(nodeID * 2 + 1)))
    });
  }

  function _addIntervalToNode(Node storage node, uint begin, uint end, uint intervalID) {
    var _intervalID = bytes32(intervalID);
    var _begin = _getBeginIndexKey(begin);
    var _end = _getEndIndexKey(end);

    node.beginIndex.insert(_intervalID, _begin);
    node.endIndex.insert(_intervalID, _end);
    node.count++;

    if (node.count == 1) {
      node.lowestBeginIndexNode = node.beginIndex.root;
      node.highestEndIndexNode = node.endIndex.root;

      return;
    }

    var newLowest = node.beginIndex.getPreviousNode(node.lowestBeginIndexNode);
    if (newLowest != 0x0) {
      node.lowestBeginIndexNode = newLowest;
    }

    var newHighest = node.endIndex.getNextNode(node.highestEndIndexNode);
    if (newHighest != 0x0) {
      node.highestEndIndexNode = newHighest;
    }
  }

  /*
   * search helpers
   */
  function _searchNode(Node storage node, uint point)
    constant
    internal
    returns (uint[] memory intervalIDs, bool searchLower, bool searchHigher)
  {
    uint[] memory _intervalIDs = new uint[](node.count);
    uint num = 0;

    bytes32 cur;

    if (point < node.center) {
      searchLower = true;
      searchHigher = false;

      cur = node.lowestBeginIndexNode;
      while (cur != 0x0) {
	uint begin = _begin(node, cur);
	if (begin > point) {
	  break;
	}

	_intervalIDs[num] = uint(node.beginIndex.getNodeId(cur));
	num++;

	cur = _next(node, cur);
      }
    }

    if (point >= node.center) {
      searchHigher = true;
      searchLower = false;

      cur = node.highestEndIndexNode;
      while (cur != 0x0) {
	uint end = _end(node, cur);
	if (end <= point) {
	  break;
	}

	_intervalIDs[num] = uint(node.endIndex.getNodeId(cur));
	num++;

	cur = _previous(node, cur);
      }
    }

    if (num == _intervalIDs.length) {
      intervalIDs = _intervalIDs;
    } else {
      intervalIDs = new uint[](num);
      for (uint i = 0; i < num; i++) {
	intervalIDs[i] = _intervalIDs[i];
      }
    }
  }

  /*
   * Grove linked list traversal
   */
  function _begin(Node storage node, bytes32 indexNode) constant returns (uint) {
    return _getBegin(node.beginIndex.getNodeValue(indexNode));
  }

  function _end(Node storage node, bytes32 indexNode) constant returns (uint) {
    return _getEnd(node.endIndex.getNodeValue(indexNode));
  }

  function _next(Node storage node, bytes32 cur) constant returns (bytes32) {
    return node.beginIndex.getNextNode(cur);
  }

  function _previous(Node storage node, bytes32 cur) constant returns (bytes32) {
    return node.endIndex.getPreviousNode(cur);
  }

  /*
   * uint / int conversions for Grove nodeIDs
   */
  function _getBeginIndexKey(uint begin) constant internal returns (int) {
    // convert to signed int in order-preserving manner
    return int(begin - 0x8000000000000000000000000000000000000000000000000000000000000000);
  }

  function _getEndIndexKey(uint end) constant internal returns (int) {
    // convert to signed int in order-preserving manner
    return int(end - 0x8000000000000000000000000000000000000000000000000000000000000000);
  }

  function _getBegin(int beginIndexKey) constant internal returns (uint) {
    // convert to unsigned int in order-preserving manner
    return uint(beginIndexKey) + 0x8000000000000000000000000000000000000000000000000000000000000000;
  }

  function _getEnd(int endIndexKey) constant internal returns (uint) {
    // convert to unsigned int in order-preserving manner
    return uint(endIndexKey) + 0x8000000000000000000000000000000000000000000000000000000000000000;
  }
}


make PullPayment.withdrawPaymentsWithGas external

(cherry picked from commit 76a1d7a3cd29fb7797cd12d2a5906b94325b773e)

pragma solidity ^0.5.0;

import "./escrow/Escrow.sol";

/**
 * @dev Simple implementation of a
 * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
 * strategy, where the paying contract doesn't interact directly with the
 * receiver account, which must withdraw its payments itself.
 *
 * Pull-payments are often considered the best practice when it comes to sending
 * Ether, security-wise. It prevents recipients from blocking execution, and
 * eliminates reentrancy concerns.
 *
 * To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
 * instead of Solidity's `transfer` function. Payees can query their due
 * payments with {payments}, and retrieve them with {withdrawPayments}.
 */
contract PullPayment {
    Escrow private _escrow;

    constructor () internal {
        _escrow = new Escrow();
    }

    /**
     * @dev Withdraw accumulated payments.
     *
     * Note that _any_ account can call this function, not just the `payee`.
     * This means that contracts unaware of the `PullPayment` protocol can still
     * receive funds this way, by having a separate account call
     * {withdrawPayments}.
     *
     * NOTE: This function has been deprecated, use {withdrawPaymentsWithGas}
     * instead. Calling contracts with fixed gas limits is an anti-pattern and
     * may break contract interactions in network upgrades (hardforks).
     * https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more.]
     *
     * @param payee Whose payments will be withdrawn.
     */
    function withdrawPayments(address payable payee) public {
        _escrow.withdraw(payee);
    }

    /**
     * @dev Same as {withdrawPayments}, but forwarding all gas to the recipient.
     *
     * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
     * Make sure you trust the recipient, or are either following the
     * checks-effects-interactions pattern or using {ReentrancyGuard}.
     */
    function withdrawPaymentsWithGas(address payable payee) external {
        _escrow.withdrawWithGas(payee);
    }

    /**
     * @dev Returns the payments owed to an address.
     * @param dest The creditor's address.
     */
    function payments(address dest) public view returns (uint256) {
        return _escrow.depositsOf(dest);
    }

    /**
     * @dev Called by the payer to store the sent amount as credit to be pulled.
     * Funds sent in this way are stored in an intermediate {Escrow} contract, so
     * there is no danger of them being spent before withdrawal.
     *
     * @param dest The destination address of the funds.
     * @param amount The amount to transfer.
     */
    function _asyncTransfer(address dest, uint256 amount) internal {
        _escrow.deposit.value(amount)(dest);
    }
}

pragma solidity ^0.5.0;

import "./escrow/Escrow.sol";

/**
 * @dev Simple implementation of a
 * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
 * strategy, where the paying contract doesn't interact directly with the
 * receiver account, which must withdraw its payments itself.
 *
 * Pull-payments are often considered the best practice when it comes to sending
 * Ether, security-wise. It prevents recipients from blocking execution, and
 * eliminates reentrancy concerns.
 *
 * To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
 * instead of Solidity's `transfer` function. Payees can query their due
 * payments with {payments}, and retrieve them with {withdrawPayments}.
 */
contract PullPayment {
    Escrow private _escrow;

    constructor () internal {
        _escrow = new Escrow();
    }

    /**
     * @dev Withdraw accumulated payments.
     *
     * Note that _any_ account can call this function, not just the `payee`.
     * This means that contracts unaware of the `PullPayment` protocol can still
     * receive funds this way, by having a separate account call
     * {withdrawPayments}.
     *
     * NOTE: This function has been deprecated, use {withdrawPaymentsWithGas}
     * instead. Calling contracts with fixed gas limits is an anti-pattern and
     * may break contract interactions in network upgrades (hardforks).
     * https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more.]
     *
     * @param payee Whose payments will be withdrawn.
     */
    function withdrawPayments(address payable payee) public {
        _escrow.withdraw(payee);
    }

    /**
     * @dev Same as {withdrawPayments}, but forwarding all gas to the recipient.
     *
     * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
     * Make sure you trust the recipient, or are either following the
     * checks-effects-interactions pattern or using {ReentrancyGuard}.
     */
    function withdrawPaymentsWithGas(address payable payee) public {
        _escrow.withdrawWithGas(payee);
    }

    /**
     * @dev Returns the payments owed to an address.
     * @param dest The creditor's address.
     */
    function payments(address dest) public view returns (uint256) {
        return _escrow.depositsOf(dest);
    }

    /**
     * @dev Called by the payer to store the sent amount as credit to be pulled.
     * Funds sent in this way are stored in an intermediate {Escrow} contract, so
     * there is no danger of them being spent before withdrawal.
     *
     * @param dest The destination address of the funds.
     * @param amount The amount to transfer.
     */
    function _asyncTransfer(address dest, uint256 amount) internal {
        _escrow.deposit.value(amount)(dest);
    }
}


Doubly linked list as library.

Doubly linked list as library.

library DoublyLinkedList {
    struct data {
        uint80 first;
        uint80 last;
        uint80 count;
        Item[] items;
    }
    uint80 constant None = uint80(-1);
    struct Item {
        uint80 prev;
        uint80 next;
        bytes32 data;
    }
    function append(data storage self, bytes32 _data) {
        var index = self.items.push(Item({prev: self.last, next: None, data: _data}));
        if (self.last == None)
        {
            if (self.first != None || self.count != 0) throw;
            self.first = self.last = uint80(index - 1);
            self.count = 1;
        }
        else
        {
            self.items[self.last].next = uint80(index - 1);
            self.last = uint80(index - 1);
            self.count ++;
        }
    }
    function remove(data storage self, uint80 _index) {
        Item item = self.items[_index];
        if (item.prev == None)
            self.first = item.next;
        if (item.next == None)
            self.last = item.prev;
        if (item.prev != None)
            self.items[item.prev].next = item.next;
        if (item.next != None)
            self.items[item.next].prev = item.prev;
        delete self.items[_index];
        self.count++;
    }
    // Iterator interface
    function iterate_start(data storage self) returns (uint80) { return self.first; }
    function iterate_valid(data storage self, uint80 _index) returns (bool) { return _index < self.items.length; }
    function iterate_prev(data storage self, uint80 _index) returns (uint80) { return self.items[_index].prev; }
    function iterate_next(data storage self, uint80 _index) returns (uint80) { return self.items[_index].next; }
    function iterate_get(data storage self, uint80 _index) returns (bytes32) { return self.items[_index].data; }
}

contract Test {
    DoublyLinkedList.data list;
    function append() {
        DoublyLinkedList.append(list, "123");
    }
    function remove(bytes32 data) returns (bool success) {
        var it = DoublyLinkedList.iterate_start(list);
        while (DoublyLinkedList.iterate_valid(list, it)) {
            if (DoublyLinkedList.iterate_get(list, it) == data) {
                DoublyLinkedList.remove(list, it);
                return true;
            }
            it = DoublyLinkedList.iterate_next(list, it);
        }
        return false;
    }
}

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


human standard token

human standard token

/*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.

In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.

1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.

.*/

import "./StandardToken.sol";

pragma solidity ^0.4.6;

contract HumanStandardToken is StandardToken {

    function () {
        //if ether is sent to this address, send it back.
        throw;
    }

    /* Public variables of the token */

    /*
    NOTE:
    The following variables are OPTIONAL vanities. One does not have to include them.
    They allow one to customise the token contract & in no way influences the core functionality.
    Some wallets/interfaces might not even bother to look at this information.
    */
    string public name;                   //fancy name: eg Simon Bucks
    uint8 public decimals;                //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
    string public symbol;                 //An identifier: eg SBX
    string public version = 'H0.1';       //human 0.1 standard. Just an arbitrary versioning scheme.

    function HumanStandardToken(
        uint256 _initialAmount,
        string _tokenName,
        uint8 _decimalUnits,
        string _tokenSymbol
        ) {
        balances[msg.sender] = _initialAmount;               // Give the creator all initial tokens
        totalSupply = _initialAmount;                        // Update total supply
        name = _tokenName;                                   // Set the name for display purposes
        decimals = _decimalUnits;                            // Amount of decimals for display purposes
        symbol = _tokenSymbol;                               // Set the symbol for display purposes
    }

    /* Approves and then calls the receiving contract */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);

        //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
        //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
        //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
        if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
        return true;
    }
}

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


Create PLUtoken.sol

Create PLUtoken.sol

20 000 000 PLU emission limitation.
*8 decimals

import 'common/Mortal.sol';

/**
 * @title Token contract represents any asset in digital economy
 */
contract Token is Mortal {
    /* Short description of token */
    string public name;
    string public symbol;
    uint8 public decimals;

    /* Total count of tokens exist */
    uint public totalSupply;

    /* Token approvement system */
    mapping(address => uint) public balanceOf;
    mapping(address => mapping (address => uint)) public approveOf;

    /**
     * @return available balance of `sender` account (self balance)
     */
    function getBalance() constant returns (uint)
    { return balanceOf[msg.sender]; }

    /**
     * @dev This method returns non zero result when sender is approved by
     *      argument address and target address have non zero self balance
     * @param _address target address
     * @return available for `sender` balance of given address
     */
    function getBalance(address _address) constant returns (uint) {
        return approveOf[_address][msg.sender]
             > balanceOf[_address] ? balanceOf[_address]
                                   : approveOf[_address][msg.sender];
    }

    /**
     * @return `true` wnen `sender` have non zero available balance for target address
     * @dev Synonym for getBalance(address _address)
     */
    function isApproved(address _address) constant returns (bool)
    { return approveOf[_address][msg.sender] > 0; }

    /* Token constructor */
    function Token() {
        name   = "Pluton";
        symbol = "PLU";
        decimals = 8;
    }

    /*
     * Token manipulation methods only for owner
     */

    /**
     * @dev Token emission
     * @param _value amount of token values to emit
     * @notice owner balance will be increased by `_value`
     */
    function emission(uint _value) onlyOwner {
        if ((totalSupply + _value) <= 2000000000000000) {
            totalSupply      += _value;
            balanceOf[owner] += _value;
            }
    }

    /**
     * @dev Burn the token values from owner balance and from total
     * @param _value amount of token values for burn
     * @notice owner balance will be decreased by `_value`
     */
    function burn(uint _value) onlyOwner {
        if (balanceOf[owner] >= _value) {
            balanceOf[owner] -= _value;
            totalSupply      -= _value;
        }
    }

    /*
     * Public token methods for everyone
     */

    /**
     * @dev Transfer self tokens to given address
     * @param _to destination address
     * @param _value amount of token values to send
     * @notice `_value` tokens will be sended to `_to`
     * @return `true` when transfer done
     */
    function transfer(address _to, uint _value) returns (bool) {
        if (balanceOf[msg.sender] >= _value) {
            balanceOf[msg.sender] -= _value;
            balanceOf[_to]        += _value;
            return true;
        }
        return false;
    }

    /**
     * @dev Transfer with approvement mechainsm
     * @param _from source address, `_value` tokens shold be approved for `sender`
     * @param _to destination address
     * @param _value amount of token values to send
     * @notice from `_from` will be sended `_value` tokens to `_to`
     * @return `true` when transfer is done
     */
    function transferFrom(address _from, address _to, uint _value) returns (bool) {
        var avail = approveOf[_from][msg.sender]
                  > balanceOf[_from] ? balanceOf[_from]
                                     : approveOf[_from][msg.sender];
        if (avail >= _value) {
            approveOf[_from][msg.sender] -= _value;
            balanceOf[_from] -= _value;
            balanceOf[_to]   += _value;
            return true;
        }
        return false;
    }

    /**
     * @dev Give to target address ability for self token manipulation without sending
     * @param _address target address
     * @param _value amount of token values for approving
     */
    function approve(address _address, uint _value)
    { approveOf[msg.sender][_address] += _value; }

    /**
     * @dev Reset count of tokens approved for given address
     * @param _address target address
     */
    function unapprove(address _address)
    { approveOf[msg.sender][_address] = 0; }
}

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


Checking payment of the bet when joining the game

pragma solidity ^0.4.6; // Specify compiler version

contract Connect4eth {
  address player1;
  address player2;
  bool player1sTurn;

  bool player1Paid;
  bool player2Paid;
  bool gameOver;

  uint bet;

  uint8[7][] grid;

  function Connect4eth(address firstPlayer, address secondPlayer, uint b) {
    player1 = firstPlayer;
    player2 = secondPlayer;
    player1Paid = false;
    player2Paid = false;
    player1sTurn = true;
    gameOver = false;
    bet = b;
    for (uint8 i = 0; i < 7; i++) {
      grid.push([0,0,0,0,0,0]);
    }
  }

  function joinGame() payable {
    if (msg.sender == player1 && !player1Paid && msg.value == bet) {
      player1Paid = true;
    }
    else if (msg.sender == player2 && !player2Paid && msg.value == bet) {
      player2Paid = true;
    }
    else {
      throw;
    }
  }

  function isStarted() returns (bool) {
    return player1Paid && player2Paid;
  }

  function isFinished() returns (bool) {
    return gameOver;
  }

  function isPlayer1sTurn() returns (bool) {
    if (!player1Paid || !player2Paid || gameOver) throw;
    return player1sTurn;
  }
}

pragma solidity ^0.4.6; // Specify compiler version

contract Connect4eth {
  address player1;
  address player2;
  bool player1sTurn;

  bool player1Paid;
  bool player2Paid;
  bool gameOver;

  uint bet;

  uint8[7][] grid;

  function Connect4eth(address firstPlayer, address secondPlayer, uint b) {
    player1 = firstPlayer;
    player2 = secondPlayer;
    player1Paid = false;
    player2Paid = false;
    player1sTurn = true;
    gameOver = false;
    bet = b;
    for (uint8 i = 0; i < 7; i++) {
      grid.push([0,0,0,0,0,0]);
    }
  }

  function joinGame() payable {
    if (msg.sender == player1 && !player1Paid) {
      player1Paid = true;
    }
    else if (msg.sender == player2 && !player2Paid) {
      player2Paid = true;
    }
    else {
      throw;
    }
  }

  function isStarted() returns (bool) {
    return player1Paid && player2Paid;
  }

  function isFinished() returns (bool) {
    return gameOver;
  }

  function isPlayer1sTurn() returns (bool) {
    if (!player1Paid || !player2Paid || gameOver) throw;
    return player1sTurn;
  }
}


Minor alterations to wallet.

Minor alterations to wallet.

// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
contract multiowned {
	// struct for the status of a pending operation.
	struct PendingState {
		uint yetNeeded;
		uint ownersDone;
	}

	// this contract only has two types of events: it can accept a confirmation, in which case
	// we record owner and operation (hash) alongside it.
	event Confirmation(address owner, hash operation);
	// the other is in the case of an owner changing. here we record the old and new owners.
	event OwnerChanged(address oldOwner, address newOwner);

	// constructor is given number of sigs required to do protected "onlyowners" transactions
	// as well as the selection of addresses capable of confirming them.
	function multiowned(uint _required, address[] _owners) {
		m_required = _required;
		m_owners = _owners;
	}

	// simple single-sig function modifier.
	modifier onlyowner {
		if (m_owners.find(msg.sender) != notfound)
			_
	}

	// multi-sig function modifier: the operation must have an intrinsic hash in order
	// that later attempts can be realised as the same underlying operation and
	// thus count as confirmations.
	modifier onlymanyowners(hash _operation) {
		if (confirm(_operation))
			_
	}

	function confirm(hash _operation) protected returns (bool _r) {
		// determine what index the present sender is:
		uint ownerIndex = m_owners.find(msg.sender);

		// make sure they're an owner
		if (ownerIndex != notfound) {
			// if we're not yet working on this operation, switch over and reset the confirmation status.
			if (!m_pending[_operation].yetNeeded) {
				// reset count of confirmations needed.
				m_pending[_operation].yetNeeded = _sigs.size();
				// reset which owners have confirmed (none) - set our bitmap to 0.
				m_pending[_operation].ownersDone = 0;
			}
			// determine the bit to set for this owner.
			uint ownerIndexBit = 1 << ownerIndex;

			// make sure we (the message sender) haven't confirmed this operation previously.
			assert(m_pending[_operation].yetNeeded > 0);
			if (!(m_pending[_operation].ownersDone & ownerIndexBit)) {
				Confirmation(msg.sender, _operation);
				// ok - check if count is enough to go ahead.
				if (m_pending[_operation].yetNeeded == 1) {
					// enough confirmations: reset and run interior.
					delete m_pending[_operation];
					_r = true;
				}
				else
				{
					// not enough: record that this owner in particular confirmed.
					m_pending[_operation].yetNeeded--;
					m_pending[_operation].ownersDone |= ownerIndexBit;
				}
			}
		}
	}

	// replaces an owner `_from` with another `_to`.
	function changeOwner(address _from, address _to) external multiowned(sha3(msg.sig, _from, _to)) {
		uint ownerIndex = m_owners.find(_from);
		if (ownerIndex != notfound)
		{
			m_owners[ownerIndex] = _to;
			OwnerChanged(_from, _to);
		}
	}

	// the number of owners that must confirm the same operation before it is run.
	uint constant m_required;

	//stateset owners {
	set address[] m_owners;
	// set meaning you can do a fast look up into it to get the index.
	// suggested impl as combination of count-prefixed contiguous series and normal mapping for the reverse lookup:
	// sha3(BASE + 0) => N,
	// sha3(BASE + 1) => address[0],
	// ...
	// sha3(BASE + N) => address[N-1],
	// sha3(BASE ++ address[0]) => 1,
	// ...
	// sha3(BASE ++ address[N-1]) -> N
	//
	// provides:
	// size: m_owners.size()
	// dereference: m_owners[0], ..., m_owners[m_owners.size() - 1]
	// alteration: m_owners[2] = newValue; (original m_owners[2] is removed)
	// find: m_owners.find(m_owners[0]) == 0, ..., m_owners.find(m_owners[m_owners.size() - 1]) == m_owners.size() - 1,  m_owners.find(...) == (uint)-1 == notfound
	// append: m_owners.insert(n): m_owners[m_owners.size() - 1] == n, m_owners.lookup(n) == m_owners.size() - 1
	// delete: delete m_owners[n]
	// clear: m_owners.clear(): m_owners.size() == 0 (or just delete m_owners)
	//}

	/*
	// for now could just be:
	uint m_ownersCount;
	mapping (uint => address) m_owners;
	mapping (address => uint) m_ownersFind;
	*/

	// the ongoing operations.
	mapping { hash => PendingState } m_pending;
}

// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
	// constructor - just records the present day's index.
	function daylimit() {
		m_lastDay = today();
	}

	// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
	function setDailyLimit(uint _newLimit) external onlyowners(sha3(msg.sig, _newLimit)) {
		m_dailyLimit = _newLimit;
	}

	// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
	function resetSpentToday() external onlyowners(sha3(msg.sig)) {
		m_spentToday = 0;
	}

	// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
	// returns true. otherwise just returns false.
	function underLimit(uint _value) protected onlyowner {
		// reset the spend limit if we're on a different day to last time.
		if (today() > m_lastDay) {
			m_spentToday = 0;
			m_lastDay = today();
		}
		// check to see if there's enough left - if so, subtract and return true.
		if (m_spentToday + _value <= m_dailyLimit) {
			m_spendToday += _value;
			return true;
		}
		return false;
	}

	// simple modifier for daily limit.
	modifier limitedDaily(uint _value) {
		if (underLimit(_value))
			_
	}

	// determines today's index.
	function today() private constant returns (uint r) { r = block.timestamp / (60 * 60 * 24); }

	uint m_spentToday;
	uint m_dailyLimit;
	uint m_lastDay;
}

// interface contract for multisig proxy contracts.
contract multisig {
	function changeOwner(address _from, address _to);
	function transact(address _to, uint _value) returns (hash _r);
	function confirm(hash _h);
}

// usage:
// hash h = Wallet(w).from(oneOwner).transact(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig multiowned daylimit {
	// Transaction structure to remember details of transaction lest it need be saved for a later call.
	structure Transaction {
		address to;
		uint value;
		byte[] data;
	}

	// logged events:
	// Funds has arrived into the wallet (record how much).
	event CashIn(uint value);
	// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
	event SingleTransact(string32 indexed out = "out", address owner, uint value, address to);
	// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
	event MultiTransact(string32 indexed out = "out", address owner, hash operation, uint value, address to);

	// constructor - just pass on the owner arra to the multiowned.
	function Wallet(address[] _owners) multiowned(2, _owners) {}

	// kills the contract sending everything to `_to`.
	function kill(address _to) external onlyowners(sha3("kill", _to)) {
		this.suicide(_to);
	}

	// gets called when no other function matches
	function() {
		// just being sent some cash?
		if (msg.value) {
			CashIn(msg.value);
		}
	}

	// Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
	// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
	// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
	// and _data arguments). They still get the option of using them if they want, anyways.
	function transact(address _to, uint _value, bytes[] _data) external returns (hash _r) {
		// first, take the opportunity to check that we're under the daily limit.
		if (underLimit(_value)) {
			log SingleTransact(_value, _to);
			// yes - just execute the call.
			_to.call(_value, _data);
			return 0;
		}

		// determine our operation hash.
		_r = sha3("transact", _to, _value, _data);
		if (!confirm(_r) && m_txs[_r].to == 0) {
			m_txs[_r].to = _to;
			m_txs[_r].value = _value;
			m_txs[_r].data = _data;
		}
	}

	// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
	// to determine the body of the transaction from the hash provided.
	function confirm(hash _h) external onlyowners(_h) {
		if (m_txs[_h].to != 0) {
			m_txs[_h].to.call(m_txs[_h].value, m_txs[_h].data);
			MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to);
			delete m_txs[_h];
		}
	}

	// internally confirm transaction with all of the info. returns true iff confirmed good and executed.
	function confirm(hash _h, address _to, uint _value, bytes[] _data) private onlyowners(_h) returns (bool _r) {
		_to.call(_value, _data);
		MultiTransact(msg.sender, _h, _value, _to);
		_r = true;
	}

	// pending transactions we have at present.
	mapping (hash => Transaction) m_txs;
}

// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
contract multiowned {
	// struct for the status of a pending operation.
	struct PendingState {
		uint yetNeeded;
		uint ownersDone;
	}

	// this contract only has two types of events: it can accept a confirmation, in which case
	// we record owner and operation (hash) alongside it.
	event Confirmation(address owner, hash operation);
	// the other is in the case of an owner changing. here we record the old and new owners.
	event OwnerChanged(address oldOwner, address newOwner);

	// constructor is given number of sigs required to do protected "onlyowners" transactions
	// as well as the selection of addresses capable of confirming them.
	function multiowned(uint _required, address[] _owners) {
		m_required = _required;
		m_owners = _owners;
	}

	// simple single-sig function modifier.
	modifier onlyowner {
		if (m_owners.find(msg.sender) != notfound)
			_
	}

	// multi-sig function modifier: the operation must have an intrinsic hash in order
	// that later attempts can be realised as the same underlying operation and
	// thus count as confirmations.
	modifier onlymanyowners(hash _operation) {
		if (confirm(_operation))
			_
	}

	function confirm(hash _operation) protected returns (bool _r) {
		// determine what index the present sender is:
		uint ownerIndex = m_owners.find(msg.sender);

		// make sure they're an owner
		if (ownerIndex != notfound) {
			// if we're not yet working on this operation, switch over and reset the confirmation status.
			if (!m_pending[_operation].yetNeeded) {
				// reset count of confirmations needed.
				m_pending[_operation].yetNeeded = _sigs.size();
				// reset which owners have confirmed (none) - set our bitmap to 0.
				m_pending[_operation].ownersDone = 0;
			}
			// determine the bit to set for this owner.
			uint ownerIndexBit = 1 << ownerIndex;

			// make sure we (the message sender) haven't confirmed this operation previously.
			assert(m_pending[_operation].yetNeeded > 0);
			if (!(m_pending[_operation].ownersDone & ownerIndexBit)) {
				Confirmation(msg.sender, _operation);
				// ok - check if count is enough to go ahead.
				if (m_pending[_operation].yetNeeded == 1) {
					// enough confirmations: reset and run interior.
					delete m_pending[_operation];
					_r = true;
				}
				else
				{
					// not enough: record that this owner in particular confirmed.
					m_pending[_operation].yetNeeded--;
					m_pending[_operation].ownersDone |= ownerIndexBit;
				}
			}
		}
	}

	// replaces an owner `_from` with another `_to`.
	function changeOwner(address _from, address _to) external multiowned(sha3(msg.sig, _from, _to)) {
		uint ownerIndex = m_owners.find(_from);
		if (ownerIndex != notfound)
		{
			m_owners[ownerIndex] = _to;
			OwnerChanged(_from, _to);
		}
	}

	// the number of owners that must confirm the same operation before it is run.
	uint constant m_required;

	//stateset owners {
	set address[] m_owners;
	// set meaning you can do a fast look up into it to get the index.
	// suggested impl as combination of count-prefixed contiguous series and normal mapping for the reverse lookup:
	// sha3(BASE + 0) => N,
	// sha3(BASE + 1) => address[0],
	// ...
	// sha3(BASE + N) => address[N-1],
	// sha3(BASE ++ address[0]) => 1,
	// ...
	// sha3(BASE ++ address[N-1]) -> N
	//
	// provides:
	// size: m_owners.size()
	// dereference: m_owners[0], ..., m_owners[m_owners.size() - 1]
	// alteration: m_owners[2] = newValue; (original m_owners[2] is removed)
	// find: m_owners.find(m_owners[0]) == 0, ..., m_owners.find(m_owners[m_owners.size() - 1]) == m_owners.size() - 1,  m_owners.find(...) == (uint)-1 == notfound
	// append: m_owners.insert(n): m_owners[m_owners.size() - 1] == n, m_owners.lookup(n) == m_owners.size() - 1
	// delete: delete m_owners[n]
	// clear: m_owners.clear(): m_owners.size() == 0 (or just delete m_owners)
	//}

	/*
	// for now could just be:
	uint m_ownersCount;
	mapping (uint => address) m_owners;
	mapping (address => uint) m_ownersFind;
	*/

	// the ongoing operations.
	mapping { hash => PendingState } m_pending;
}

// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
	// constructor - just records the present day's index.
	function daylimit() {
		m_lastDay = today();
	}

	// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
	function setDailyLimit(uint _newLimit) external onlyowners(sha3(msg.sig, _newLimit)) {
		m_dailyLimit = _newLimit;
	}

	// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
	function resetSpentToday() external onlyowners(sha3(msg.sig)) {
		m_spentToday = 0;
	}

	// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
	// returns true. otherwise just returns false.
	function underLimit(uint _value) protected onlyowner {
		// reset the spend limit if we're on a different day to last time.
		if (today() > m_lastDay) {
			m_spentToday = 0;
			m_lastDay = today();
		}
		// check to see if there's enough left - if so, subtract and return true.
		if (m_spentToday + _value <= m_dailyLimit) {
			m_spendToday += _value;
			return true;
		}
		return false;
	}

	// simple modifier for daily limit.
	modifier limitedDaily(uint _value) {
		if (underLimit(_value))
			_
	}

	// determines today's index.
	function today() private constant returns (uint r) { r = block.timestamp / (60 * 60 * 24); }

	uint m_spentToday;
	uint m_dailyLimit;
	uint m_lastDay;
}

// interface contract for multisig proxy contracts.
contract multisig {
	function changeOwner(address _from, address _to);
	function transact(address _to, uint _value) returns (hash _r);
	function confirm(hash _h);
}

// usage:
// hash h = Wallet(w).from(oneOwner).transact(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig multiowned daylimit {
	// Transaction structure to remember details of transaction lest it need be saved for a later call.
	structure Transaction {
		address to;
		uint value;
		byte[] data;
	}

	// logged events:
	// Funds has arrived into the wallet (record how much).
	event CashIn(uint value);
	// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
	event SingleTransact(indexed string32 = "out", address owner, uint value, address to);
	// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
	event MultiTransact(indexed string32 = "out", address owner, hash operation, uint value, address to);

	// constructor - just pass on the owner arra to the multiowned.
	function Wallet(address[] _owners) multiowned(2, _owners) {}

	// kills the contract sending everything to `_to`.
	function kill(address _to) external onlyowners(sha3("kill", _to)) {
		this.suicide(_to);
	}

	// gets called when no other function matches
	function() {
		// just being sent some cash?
		if (msg.value) {
			CashIn(msg.value);
		}
	}

	// Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
	// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
	// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
	// and _data arguments). They still get the option of using them if they want, anyways.
	function transact(address _to, uint _value, bytes[] _data) external returns (hash _r) {
		// first, take the opportunity to check that we're under the daily limit.
		if (underLimit(_value)) {
			log SingleTransact(_value, _to);
			// yes - just execute the call.
			_to.call(_value, _data);
			return 0;
		}

		// determine our operation hash.
		_r = sha3("transact", _to, _value, _data);
		if (!confirm(_r) && m_txs[_r].to == 0) {
			m_txs[_r].to = _to;
			m_txs[_r].value = _value;
			m_txs[_r].data = _data;
		}
	}

	// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
	// to determine the body of the transaction from the hash provided.
	function confirm(hash _h) external onlyowners(_h) {
		if (m_txs[_h].to != 0) {
			m_txs[_h].to.call(m_txs[_h].value, m_txs[_h].data);
			MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to);
			delete m_txs[_h];
		}
	}

	// internally confirm transaction with all of the info. returns true iff confirmed good and executed.
	function confirm(hash _h, address _to, uint _value, bytes[] _data) private onlyowners(_h) returns (bool _r) {
		_to.call(_value, _data);
		MultiTransact(msg.sender, _h, _value, _to);
		_r = true;
	}

	// pending transactions we have at present.
	mapping (hash => Transaction) m_txs;
}


fix: replace contract with correct version

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.11;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/access/Ownable.sol';

import './Renderer.sol';

/*

▀█▀ █░█ █▀▀
░█░ █▀█ ██▄

█▀▀ █░█ █▀▀ █▀ ▀█▀   █▄▄ █▀█ █▀█ █▄▀
█▄█ █▄█ ██▄ ▄█ ░█░   █▄█ █▄█ █▄█ █░█

*/

contract TheGuestBook is ERC721, Ownable {
  constructor() ERC721('The Guest Book', 'GUEST') {}

  // Emitted when we know that something about the token has changed
  event MetadataUpdated(uint256 indexed tokenId);
  event GuestUpdated(uint256 indexed guestId);

  // Define tokenId, guestID, etc
  uint256 public tokenId;
  uint256 public guestId;

  // Store renderer as separate contract so we can update it if needed
  Renderer public renderer;

  // Store content for the nfts
  mapping(uint256 => string[]) _tokenMetadata;

  struct Guest {
    uint256 guestId; // Enumerated ID of the guest
    string guest; // The address of the guest.
    string message; // The message the guest sent.
    string timestamp; // The timestamp when the guest visited.
    string minted; // boolean if minted
    uint256 tokenId; // tokenId, set to 0 if `minted` is false
  }

  event NewGuest(
    uint256 guestId,
    string author,
    string message,
    string timestamp
  );

  Guest[] public guests;

  /// @notice returns all guests
  function getAllGuests() public view returns (Guest[] memory) {
    return guests;
  }

  function addGuest(
    string memory _message,
    string memory _minted,
    uint256 _tokenId
  ) private {
    // struct the guest values
    string memory _a = Strings.toHexString(uint256(uint160(msg.sender)));
    string memory _timestamp = Strings.toString(block.number);

    // emit event for new guest
    Guest memory g = Guest(
      guestId,
      _a,
      _message,
      _timestamp,
      _minted,
      _tokenId
    );
    guests.push(g);
    emit NewGuest(guestId, _a, _message, _timestamp);

    // increment guestId
    guestId++;
  }

  /// @notice write a message to the blockchain
  /// @notice recommend less than 280 characters
  function signWithoutMint(string memory _message) public {
    require(
      bytes(_message).length <= 280,
      'Message should be less than 280 characters.'
    );
    addGuest(_message, 'false', 0);
  }

  /// @notice write a message to the blockchain and get an nft
  /// @notice your message will be inscribed in an on-chain svg, recommend less than 280 characters
  function signWithMint(string memory _message) public payable {
    require(msg.value >= 0.01 ether, 'Not enough ETH');
    require(
      bytes(_message).length <= 280,
      'Message should be less than 280 characters.'
    );
    addGuest(_message, 'true', tokenId);
    string memory _a = Strings.toHexString(uint256(uint160(msg.sender)));
    _tokenMetadata[tokenId] = [_a];
    _mint(msg.sender, tokenId);
    tokenId++;
  }

  function tokenURI(uint256 _tokenId)
    public
    view
    override
    returns (string memory)
  {
    return renderer.render(_tokenId, _tokenMetadata[_tokenId][0]);
  }

  /* ADMIN */
  // @notice admin reserves the right to rewrite any message that contains hurtful or inflammatory language
  function rewriteMessage(uint256 _guestId, string calldata _message)
    external
    onlyOwner
  {
    // struct the updated guest message
    guests[_guestId].message = _message;
    emit GuestUpdated(_guestId);
  }

  function withdrawAll() external {
    payable(owner()).transfer(address(this).balance);
  }

  function withdrawAllERC20(IERC20 _erc20Token) external {
    _erc20Token.transfer(owner(), _erc20Token.balanceOf(address(this)));
  }

  function setRenderer(Renderer _renderer) external onlyOwner {
    renderer = _renderer;
    emit MetadataUpdated(type(uint256).max);
  }
}

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.11;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/access/Ownable.sol';

import './Renderer.sol';

/*

▀█▀ █░█ █▀▀
░█░ █▀█ ██▄

█▀▀ █░█ █▀▀ █▀ ▀█▀   █▄▄ █▀█ █▀█ █▄▀
█▄█ █▄█ ██▄ ▄█ ░█░   █▄█ █▄█ █▄█ █░█

*/

contract TheGuestBook is ERC721, Ownable {
  // Emitted when we know that something about the token has changed
  event MetadataUpdated(uint256 indexed tokenId);
  event GuestUpdated(uint256 indexed guestId);

  // Define tokenId, guestID, etc
  uint256 public tokenId;
  uint256 public guestId;

  string _a = Strings.toHexString(uint256(uint160(msg.sender)));
  string _timestamp = Strings.toString(block.number);

  // Store renderer as separate contract so we can update it if needed
  Renderer public renderer;

  // Store content for the nfts
  mapping(uint256 => string[]) _tokenMetadata;

  constructor() ERC721('The Guest Book', 'GUEST') {}

  struct Guest {
    uint256 guestId; // Enumerated ID of the guest
    string guest; // The address of the guest.
    string message; // The message the guest sent.
    string timestamp; // The timestamp when the guest visited.
  }

  event NewGuest(
    uint256 guestId,
    string author,
    string message,
    string timestamp
  );

  Guest[] public guests;

  /// @notice returns all guests
  function getAllGuests() public view returns (Guest[] memory) {
    return guests;
  }

  function addGuest(string memory _message) private {
    // struct the guest values
    Guest memory g = Guest(guestId, _a, _message, _timestamp);
    guests.push(g);

    // emit event for new guest
    emit NewGuest(guestId, _a, _message, _timestamp);

    // increment guestId
    guestId++;
  }

  /// @notice write a message to the blockchain
  function signWithoutMint(string memory _message) public {
    require(
      bytes(_message).length <= 280,
      'Message should be less than 280 characters.'
    );
    addGuest(_message);
  }

  /// @notice write a message to the blockchain and get an nft
  /// @notice your message will be inscribed in an on-chain svg, recommend less than 280 characters
  function signWithMint(string memory _message) public payable {
    require(msg.value >= 0.001 ether, 'Not enough ETH');
    require(
      bytes(_message).length <= 280,
      'Message should be less than 280 characters.'
    );
    addGuest(_message);
    _tokenMetadata[tokenId] = [_a];
    _mint(msg.sender, tokenId);
    tokenId++;
  }

  function tokenURI(uint256 _tokenId)
    public
    view
    override
    returns (string memory)
  {
    return renderer.render(_tokenId, _tokenMetadata[_tokenId][0]);
  }

  /* ADMIN */
  // If a message contains any text that is hurtful, inflammatory, hateful, or otherwise unwanted language this allows for it to be changed.
  // admins can rewrite at their discretion.
  function rewriteMessage(uint256 _guestId, string calldata _message)
    external
    onlyOwner
  {
    // struct the updated guest message
    guests[_guestId].message = _message;
    emit GuestUpdated(_guestId);
  }

  function withdrawAll() external {
    payable(owner()).transfer(address(this).balance);
  }

  function withdrawAllERC20(IERC20 _erc20Token) external {
    _erc20Token.transfer(owner(), _erc20Token.balanceOf(address(this)));
  }

  function setRenderer(Renderer _renderer) external onlyOwner {
    renderer = _renderer;
    emit MetadataUpdated(type(uint256).max);
  }
}