Update recommendation of JS library for merkle trees

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The proofs can be generated using our JavaScript library
 * https://github.com/OpenZeppelin/merkle-tree[`@openzeppelin/merkle-tree`].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates merkle trees that are safe
 * against this attack out of the box.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * _Available since v4.7._
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            return hashes[totalHashes - 1];
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            return hashes[totalHashes - 1];
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * _Available since v4.7._
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            return hashes[totalHashes - 1];
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            return hashes[totalHashes - 1];
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}


Added indexOf to stringUtils.sol

Added indexOf to stringUtils.sol

library StringUtils {
    /// @dev Does a byte-by-byte lexicographical comparison of two strings.
    /// @return a negative number if `_a` is smaller, zero if they are equal
    /// and a positive numbe if `_b` is smaller.
    function compare(string _a, string _b) returns (int) {
        bytes memory a = bytes(_a);
        bytes memory b = bytes(_b);
        uint minLength = a.length;
        if (b.length < minLength) minLength = b.length;
        //@todo unroll the loop into increments of 32 and do full 32 byte comparisons
        for (uint i = 0; i < minLength; i ++)
            if (a[i] < b[i])
                return -1;
            else if (a[i] > b[i])
                return 1;
        if (a.length < b.length)
            return -1;
        else if (a.length > b.length)
            return 1;
        else
            return 0;
    }
    /// @dev Compares two strings and returns true iff they are equal.
    function equal(string _a, string _b) returns (bool) {
        return compare(_a, _b) == 0;
    }
    /// @dev Finds the first occurrence of _b in _a and returns its index or -1 if failure
    function indexOf(string _a, string _b) returns (int) // _a = string to search, _b = string we want to find
    {
    	bytes memory a = bytes(_a);
    	bytes memory b = bytes(_b);
    	if(a.length < 1 || b.length < 1 || (b.length > a.length))
    		return -1;
    	else if(a.length > (2**128 -1)) // since we have to be able to return -1 (if the char isn't found or input error), this function must return an "int" type with a max length of (2^128 - 1)
    		return -1;
    	else
    	{
    		uint subindex = 0;
    		for (uint i = 0; i < a.length; i ++)
    		{
    			if (a[i] == b[0]) // found the first char of b
    			{
    				subindex = 1;
    				while(subindex < b.length && (i + subindex) < a.length && a[i + subindex] == b[subindex]) // search until the chars don't match or until we reach the end of a or b
    				{
    					subindex++;
    				}
    				if(subindex == b.length)
    					return int(i);
    			}
    		}
    		return -1;
    	}
    }
}


Add RockPaperScissors contract

Add RockPaperScissors contract

pragma solidity ^0.4.11;

contract RockPaperScissors {

    enum Stages {
        playerOneThrow,
        playerTwoThrow,
        playerOneReveal,
        playerTwoReveal,
        determineWinner
    }

    Stages public stage = Stages.playerOneThrow;

    modifier atStage(Stages _stage) {
        require(stage == _stage);
        _;
    }

    function nextStage() internal {
        stage = Stages(uint(stage) + 1);
    }

    Player player1;
    Player player2;
    uint bet;
    uint public resetTime;

    struct Player{
        address addy;
        bytes32 commitHash;
        uint commitTime;
        uint gameThrow;
        uint revealTime;
    }

    function RockPaperScissors(address _player1, address _player2, uint _bet)  {
        player1.addy = _player1;
        player2.addy = _player2;
        bet = _bet;
    }

    modifier includesPayment(){if(msg.value == bet){ _; }else{ throw; } }

    function playerOneCommit(bytes32 commitHash) payable atStage(Stages.playerOneThrow) includesPayment() {
        if(msg.sender == player1.addy) {
            player1.commitHash = commitHash;
            player1.commitTime = now;
            resetTime = 0;
            nextStage();
        } else {
            throw;
        }
    }

    function playerTwoCommit(bytes32 commitHash) payable atStage(Stages.playerTwoThrow) includesPayment() {
        if(msg.sender == player2.addy) {
            player2.commitHash = commitHash;
            player2.commitTime = now;
            nextStage();
        } else {
            throw;
        }
    }

    function playerOneReveal(uint gameThrow, uint secret) atStage(Stages.playerOneReveal) {
        bytes32 commitHash = sha3(gameThrow, secret);
        if(commitHash == player1.commitHash) {
            player1.gameThrow = gameThrow;
            player1.revealTime = now;
            nextStage();
        } else {
            throw;
        }
    }

    function playerTwoReveal(uint gameThrow, uint secret) atStage(Stages.playerTwoReveal) {
        bytes32 commitHash = sha3(gameThrow, secret);
        if(commitHash == player2.commitHash) {
            player2.gameThrow = gameThrow;
            player2.revealTime = now;
            nextStage();
        } else {
            throw;
        }
    }

    function determineWinner() atStage(Stages.determineWinner) {
        address winner;
        if(player1.gameThrow == 1 && player2.gameThrow == 2) {
            winner = player2.addy;
        } else if(player1.gameThrow == 2 && player2.gameThrow == 3) {
            winner = player2.addy;
        } else if(player1.gameThrow == 3 && player2.gameThrow == 1) {
            winner = player2.addy;
        } else if (player1.gameThrow != player2.gameThrow) {
            winner = player1.addy;
        }

        if(winner != 0x0) {
            winner.transfer(this.balance);
            reset();
        } else { //tie
            splitFunds();
        }
    }

    function returnFunds(){
        if(stage == Stages.playerOneThrow){
            if(player1.commitHash == 0 && resetTime + 3600 > now){
                splitFunds();
            }
        }
        if(stage == Stages.playerTwoThrow){
            if(player1.commitTime + 3600 > now){
                player1.addy.transfer(this.balance);
            }
        }
        if(stage == Stages.playerOneReveal){
            if(player2.commitTime + 3600 > now){
                player2.addy.transfer(this.balance); // or splitFunds() ?
            }
        }
        if(stage == Stages.playerTwoReveal){
            if(player1.revealTime + 3600 > now){
                player1.addy.transfer(this.balance);
            }
        }
    }

    function splitFunds(){
        player1.addy.transfer(this.balance/2);
        player2.addy.transfer(this.balance/2);
    }

    function reset() private{
        delete player1.commitHash;
        delete player1.gameThrow;
        delete player1.commitTime;
        delete player1.revealTime;
        delete player2.commitHash;
        delete player2.gameThrow;
        delete player2.commitTime;
        delete player2.revealTime;
        resetTime = now;
        stage = Stages.playerOneThrow;
    }
}


Updated with association creation

Updated with association creation

import "./owned.sol";
import "./localsCointoken.sol";

contract localsStore is owned {

  // Which tokencontract to use
  //MyToken public token;

  // the address of the tokencontract to use
  address public tokenaddr;

  // the address of the foundation to use
  address public foundation;

  event Log(string _log, address _newclub);
  event Error(string _error);
  event Allowance(string _msg, uint256 _balance);
  event ClubCreated(string _clubname, address _newClub, address _creator);

	function localsStore(address _tokenContract, address _foundationContract) {
		tokenaddr = _tokenContract;
    foundation = _foundationContract;
	}

	function createClub(string _nickname, string _clubname, string _clubicon, address _token)
		returns (address clubAddress)

	{
			// Create a new Token contract and return its address.
			// From the JavaScript side, the return type is simply
			// "address", as this is the closest type available in
			// the ABI.
      // the creator should pay localcoin to the localsfoundation
      // create an instance of the token contract
      var tokencontract = localsCointoken(tokenaddr);

      if(tokencontract.allowance(msg.sender,this)<200) {
        Error('LocalCoin allowance too low');
        throw;
        }

      Error('allowance check');
      /*Allowance('TEST ', token.allowance(msg.sender, this));*/

      tokencontract.transferFrom(msg.sender, foundation, 200);

      Error('localcoin transferred');
      //token.transfer(foundation, 200);

      clubAddress = new localsClub(msg.sender, _nickname, _clubicon, _clubname, _token);

      ClubCreated(_clubname, clubAddress, msg.sender);

      return clubAddress;

	}

  function createAssociation(uint _minimumQuorum, uint _debatingPeriodInMinutes, token _sharesTokenAddress) returns address associationAddress {

    var tokencontract = localsCointoken(tokenaddr);

    if(tokencontract.allowance(msg.sender,this)<200) {
      Error('LocalCoin allowance too low');
      throw;
      }

    Error('allowance check');
    /*Allowance('TEST ', token.allowance(msg.sender, this));*/

    tokencontract.transferFrom(msg.sender, foundation, 200);

    Error('localcoin transferred');
    //token.transfer(foundation, 200);

    associationAddress = new Association(_minimumQuorum, _debatingPeriodInMinutes, _sharesTokenAddress);

    ClubCreated('association', associationAddress, msg.sender);

    return associationAddress;

  }

  /* Kill function, for debug purposes (I don't want a mist wallet full of token contracts :) */
  function kill() { if (msg.sender == owner) suicide(owner); }

}

contract token { mapping (address => uint256) public balanceOf;  }

// Here we start an Association
/* The democracy contract itself */
contract Association is owned {

    /* Contract Variables and events */
    uint public minimumQuorum;
    uint public debatingPeriodInMinutes;
    Proposal[] public proposals;
    uint public numProposals;
    token public sharesTokenAddress;

    event ProposalAdded(uint proposalID, address recipient, uint amount, string description);
    event Voted(uint proposalID, bool position, address voter);
    event ProposalTallied(uint proposalID, int result, uint quorum, bool active);
    event ChangeOfRules(uint minimumQuorum, uint debatingPeriodInMinutes, address sharesTokenAddress);

    struct Proposal {
        address recipient;
        uint amount;
        string description;
        uint votingDeadline;
        bool executed;
        bool proposalPassed;
        uint numberOfVotes;
        bytes32 proposalHash;
        Vote[] votes;
        mapping (address => bool) voted;
    }

    struct Vote {
        bool inSupport;
        address voter;
    }

    /* modifier that allows only shareholders to vote and create new proposals */
    modifier onlyShareholders {
        if (sharesTokenAddress.balanceOf(msg.sender) == 0) throw;
        _
    }

    /* First time setup */
    function Association(token sharesAddress, uint minimumSharesToPassAVote, uint minutesForDebate) {
        changeVotingRules(sharesAddress, minimumSharesToPassAVote, minutesForDebate);
    }

    /*change rules*/
    function changeVotingRules(token sharesAddress, uint minimumSharesToPassAVote, uint minutesForDebate) onlyOwner {
        sharesTokenAddress = token(sharesAddress);
        if (minimumSharesToPassAVote == 0 ) minimumSharesToPassAVote = 1;
        minimumQuorum = minimumSharesToPassAVote;
        debatingPeriodInMinutes = minutesForDebate;
        ChangeOfRules(minimumQuorum, debatingPeriodInMinutes, sharesTokenAddress);
    }

    /* Function to create a new proposal */
    function newProposal(
        address beneficiary,
        uint etherAmount,
        string JobDescription,
        bytes transactionBytecode
    )
        onlyShareholders
        returns (uint proposalID)
    {
        proposalID = proposals.length++;
        Proposal p = proposals[proposalID];
        p.recipient = beneficiary;
        p.amount = etherAmount;
        p.description = JobDescription;
        p.proposalHash = sha3(beneficiary, etherAmount, transactionBytecode);
        p.votingDeadline = now + debatingPeriodInMinutes * 1 minutes;
        p.executed = false;
        p.proposalPassed = false;
        p.numberOfVotes = 0;
        ProposalAdded(proposalID, beneficiary, etherAmount, JobDescription);
        numProposals = proposalID+1;
    }

    /* function to check if a proposal code matches */
    function checkProposalCode(
        uint proposalNumber,
        address beneficiary,
        uint etherAmount,
        bytes transactionBytecode
    )
        constant
        returns (bool codeChecksOut)
    {
        Proposal p = proposals[proposalNumber];
        return p.proposalHash == sha3(beneficiary, etherAmount, transactionBytecode);
    }

    /* */
    function vote(uint proposalNumber, bool supportsProposal)
        onlyShareholders
        returns (uint voteID)
    {
        Proposal p = proposals[proposalNumber];
        if (p.voted[msg.sender] == true) throw;

        voteID = p.votes.length++;
        p.votes[voteID] = Vote({inSupport: supportsProposal, voter: msg.sender});
        p.voted[msg.sender] = true;
        p.numberOfVotes = voteID +1;
        Voted(proposalNumber,  supportsProposal, msg.sender);
    }

    function executeProposal(uint proposalNumber, bytes transactionBytecode) returns (int result) {
        Proposal p = proposals[proposalNumber];
        /* Check if the proposal can be executed */
        if (now < p.votingDeadline  /* has the voting deadline arrived? */
            ||  p.executed        /* has it been already executed? */
            ||  p.proposalHash != sha3(p.recipient, p.amount, transactionBytecode)) /* Does the transaction code match the proposal? */
            throw;

        /* tally the votes */
        uint quorum = 0;
        uint yea = 0;
        uint nay = 0;

        for (uint i = 0; i <  p.votes.length; ++i) {
            Vote v = p.votes[i];
            uint voteWeight = sharesTokenAddress.balanceOf(v.voter);
            quorum += voteWeight;
            if (v.inSupport) {
                yea += voteWeight;
            } else {
                nay += voteWeight;
            }
        }

        /* execute result */
        if (quorum <= minimumQuorum) {
            /* Not enough significant voters */
            throw;
        } else if (yea > nay ) {
            /* has quorum and was approved */
            p.recipient.call.value(p.amount * 1 ether)(transactionBytecode);
            p.executed = true;
            p.proposalPassed = true;
        } else {
            p.executed = true;
            p.proposalPassed = false;
        }
        // Fire Events
        ProposalTallied(proposalNumber, result, quorum, p.proposalPassed);
    }

// Here we start the item contracts
contract localsClub {

	address public creator;
  string public clubname;
  string public clubicon;
  string public token;

  uint public numMembers;
  address[] public members;

	struct clubMember {
		string nickName;
		bool active;
	}

  event MemberAdded(string _clubname, string _nickName, address _newmember);
  event MemberDissed(string _clubname, address _newmember);

	mapping (address => clubMember) public clubMembers;

	function localsClub(address _creator, string _nickName, string _clubicon, string _clubname){
		creator = _creator;
    clubname = _clubname;
    clubicon = _clubicon;
		clubMembers[_creator].nickName = _nickName;
		clubMembers[_creator].active = true;
	}

	// Add a member to the club and make em active
	function addMember(address _newmember, string _nickName) {
    //if(msg.sender!=creator) throw;
    if(clubMembers[_newmember].active) throw;
		clubMembers[_newmember].nickName = _nickName;
		clubMembers[_newmember].active = true;
    members.push(_newmember);
    numMembers = members.length;
    MemberAdded(clubname, _nickName, _newmember);
	}

	// Set a member to active = false
	function disMember(address _newmember){
    if(msg.sender!=creator) throw;
		clubMembers[_newmember].active = false;
    MemberDissed(clubname, _newmember);
	}

  // When someone just sends value to the contract
  function () {
    throw;
  }

}

import "./owned.sol";
import "./localsCointoken.sol";

contract localsStore is owned {

  // Which tokencontract to use
  //MyToken public token;

  // the address of the tokencontract to use
  address public tokenaddr;

  // the address of the foundation to use
  address public foundation;

  event Log(string _log, address _newclub);
  event Error(string _error);
  event Allowance(string _msg, uint256 _balance);
  event ClubCreated(string _clubname, address _newClub, address _creator);

	function localsStore(address _tokenContract, address _foundationContract) {
		tokenaddr = _tokenContract;
    foundation = _foundationContract;
	}

	function createClub(string _nickname, string _clubname, string _clubicon)
		returns (address clubAddress)

	{
			// Create a new Token contract and return its address.
			// From the JavaScript side, the return type is simply
			// "address", as this is the closest type available in
			// the ABI.
      // the creator should pay localcoin to the localsfoundation
      // create an instance of the token contract
      var token = localsCointoken(tokenaddr);

      if(token.allowance(msg.sender,this)<200) {
        Error('LocalCoin allowance too low');
        throw;
        }

      Error('allowance check');
      /*Allowance('TEST ', token.allowance(msg.sender, this));*/

      token.transferFrom(msg.sender, foundation, 200);

      Error('localcoin transferred');
      //token.transfer(foundation, 200);

      clubAddress = new localsClub(msg.sender, _nickname, _clubicon, _clubname);

      ClubCreated(_clubname, clubAddress, msg.sender);

      return clubAddress;

	}

  /* Kill function, for debug purposes (I don't want a mist wallet full of token contracts :) */
  function kill() { if (msg.sender == owner) suicide(owner); }

}

// Here we start the item contracts
contract localsClub {

	address public creator;
  string public clubname;
  string public clubicon;

  uint public numMembers;
  address[] public members;

	struct clubMember {
		string nickName;
		bool active;
	}

  event MemberAdded(string _clubname, string _nickName, address _newmember);
  event MemberDissed(string _clubname, address _newmember);

	mapping (address => clubMember) public clubMembers;

	function localsClub(address _creator, string _nickName, string _clubicon, string _clubname){
		creator = _creator;
    clubname = _clubname;
    clubicon = _clubicon;
		clubMembers[_creator].nickName = _nickName;
		clubMembers[_creator].active = true;
	}

	// Add a member to the club and make em active
	function addMember(address _newmember, string _nickName) {
    //if(msg.sender!=creator) throw;
    if(clubMembers[_newmember].active) throw;
		clubMembers[_newmember].nickName = _nickName;
		clubMembers[_newmember].active = true;
    members.push(_newmember);
    numMembers = members.length;
    MemberAdded(clubname, _nickName, _newmember);
	}

	// Set a member to active = false
	function disMember(address _newmember){
    if(msg.sender!=creator) throw;
		clubMembers[_newmember].active = false;
    MemberDissed(clubname, _newmember);
	}

  // When someone just sends value to the contract
  function () {
    throw;
  }

}


Add events for ECDSASignatureProxy

Add events for ECDSASignatureProxy

import "./UnanimousConsent.sol";

/**
* This contract will consent to some hashes on behalf of a specified
* address if and only if the specified address has signed off on it
*/
contract ECDSASignatureProxy {

	event HashesForwarded(bytes32[] _hashes);

	address signer;
	UnanimousConsent unanimousConsent;

	function ECDSASignatureProxy(address _signer, UnanimousConsent _unanimousConsent) {
		signer = _signer;
		unanimousConsent = _unanimousConsent;
	}

	// Checks if all of the hashes have been signed off on
	function forward(bytes32[] _hashes, uint8 _v, bytes32 _r, bytes32 _s) external returns (bool) {
		bytes32 hash = sha3(_hashes);
		if (ecrecover(hash, _v, _r, _s) != signer) {
			return false;
		} else {
			unanimousConsent.consent(_hashes);
			HashesForwarded(_hashes);
			return true;
		}
	}
}

import "./UnanimousConsent.sol";

/**
* This contract will consent to some hashes on behalf of a specified
* address if and only if the specified address has signed off on it
*/
contract ECDSASignatureProxy {
	address signer;
	UnanimousConsent unanimousConsent;

	function ECDSASignatureProxy(address _signer, UnanimousConsent _unanimousConsent) {
		signer = _signer;
		unanimousConsent = _unanimousConsent;
	}

	// Checks if all of the hashes have been signed off on
	function forward(bytes32[] _hashes, uint8 _v, bytes32 _r, bytes32 _s) external returns (bool) {
		bytes32 hash = sha3(_hashes);
		if (ecrecover(hash, _v, _r, _s) != signer) {
			return false;
		} else {
			unanimousConsent.consent(_hashes);
			return true;
		}
	}
}


add mew as parent for 0-parent concepts

add mew as parent for 0-parent concepts

pragma solidity ^0.4.0;

import "./Concept.sol";

//@purpose: To create and store the concept ontology
contract ConceptRegistry {
  mapping (address => bool) public conceptExists; //Maps concepts to a bool
  address userRegistry; //The address of the userRegistry contract
  bool initialized = false; // for locking the init function
  address public mewAddress; // a manually created contract with no parents

  event ConceptCreation (address _concept);

  //@purpose: give this contract the address of a UserRegistry and mew Concept
  function init(address _userRegistry, address mew) returns(bool){
    if(initialized == false) { //Checks if the function has already been called
      userRegistry = _userRegistry;
      mewAddress = mew;
      conceptExists[mewAddress] = true;
      initialized = true; //locks this function
    }
    else {
      return(false);
    }
  }

  /*
  @purpose: To make a concept
  @param: address[] parentList = an array of addresses containing the addresses of the concepts parents
  */
  function makeConcept(address[] parentList) {
    Concept newConcept = new Concept(parentList, userRegistry);
    address newConceptAddress = address(newConcept);
    conceptExists[newConceptAddress] = true;

    if(parentList.length == 0) { // if no parents specified make it a child of the Mew concept
      Concept(mewAddress).addChild(newConceptAddress);
      newConcept.addParent(mewAddress);
    }
    for(uint j=0; j < parentList.length; j++) { // Iterates parents to add this concept as a child
      Concept(parentList[j]).addChild(newConceptAddress);
    }
    ConceptCreation(newConceptAddress);
  }
}

pragma solidity ^0.4.0;

import "./Concept.sol";

//@purpose: To create and store the concept ontology
contract ConceptRegistry {
  mapping (address => bool) public conceptExists; //Maps concepts to a bool
  address userRegistry; //The address of the userRegistry contract
  bool initialized = false; // for locking the init function
  address public mewAddress; // a manually created contract with no parents

  event ConceptCreation (address _concept);

  //@purpose: give this contract the address of a UserRegistry and mew Concept
  function init(address _userRegistry, address mew) returns(bool){
    if(initialized == false) { //Checks if the function has already been called
      userRegistry = _userRegistry;
      mewAddress = mew;
      conceptExists[mewAddress] = true;
      initialized = true; //locks this function
    }
    else {
      return(false);
    }
  }

  /*
  @purpose: To make a concept
  @param: address[] parentList = an array of addresses containing the addresses of the concepts parents
  */
  function makeConcept(address[] parentList) {
    Concept newConcept = new Concept(parentList, userRegistry);
    address newConceptAddress = address(newConcept);
    conceptExists[newConceptAddress] = true;

    if(parentList.length == 0) { // if no parents specified make it a child of the Mew concept
      Concept(mewAddress).addChild(newConceptAddress);
    }
    for(uint j=0; j < parentList.length; j++) { // Iterates parents to add this concept as a child
      Concept(parentList[j]).addChild(newConceptAddress);
    }
    ConceptCreation(newConceptAddress);
  }
}


Adding contract to simulate errors

Adding contract to simulate errors

pragma solidity ^0.4.6;

contract ErrorContract {
	address public Owner;
	address public Sender;
	event Completed(uint value);
	event NoThrow();

	function ErrorContract()
	{
		Owner = tx.origin;
		Sender = msg.sender;
	}

	function ThrowError()
	{
		if (Owner != tx.origin)
		{
			throw;
		}

		NoThrow();
	}

	function AddValues(uint a, uint b)
	{
		Completed(a + b);
	}

	function ConsumeGas(uint iterations)
	{
		uint x = 0;

		for (uint i = 0; i< iterations; i++)
		{
			x += i;
		}

		Completed(x);
	}
}

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


Airplane fixes

Airplane fixes

pragma solidity ^0.4.2;
/*
This file is part of the SPREAD Pivot 0.

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

The CRUB Contract 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 lesser General Public License for more details.

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

@author Stanislav Sobolev <imajacke@gmail.com>

*/
// key:
//  0x0b15fc43713df036aa0b321c7a29729f1422bd27

// Someone should define workflow(elements)
enum State { Created, Locked, Inactive }; // often used for state machine

contract Workflow {
	// sequences of elements
    mapping (uint => flow_elem) public elements;
    address public owner;
	string public name;

}

contract WorkflowElement {
   string public name;
   mapping (uint => wf_state) public states;

}

/**
 * The WorkflowState contract does this and that...
 */
contract WorkflowState {
    // boolean return
    // numeric return

    /*
       -100
       0
       ______
       0
       100
    /*
	/*
	float return
       -100.0
       0.0
       ______
       0.0
       100.0
    /*
    */

	function WorkflowState () {

	}
}

/**
 * The workflow contract does this and that...
 */
contract workflowExecutor {
	 function executeByAction() public returns (address) {
        balances[msg.sender] += msg.value;

        LogDepositMade(msg.sender, msg.value); // fire event

        return balances[msg.sender];
    }
    private replicateForInstace() public return (instantiatedWorkflow) {

    }
}

/**
 * The workflowAction contract does this and that...
 */
contract workflowAction {
	function workflowAction (stateAddr, delta) {
		this.element =
		// will change state
	}

	private function dispenceDelta(delta) return (float) {
		/////
		reuturn 100.0
	}
}

pragma solidity ^0.4.2;
/*
This file is part of the SPREAD Pivot 0.

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

The CRUB Contract 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 lesser General Public License for more details.

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

@author Stanislav Sobolev <imajacke@gmail.com>

*/

// Someone should define workflow(elements)

contract Workflow {
	// sequences of elements
    mapping (uint => flow_elem) public elements;
    address public owner;
	string public name;

}

// Action will change state
contract WorkflowAction {

}

contract WorkflowElement {

}
contract Element {
   string public name;
   mapping (uint => wf_state) public states;

}

/**
 * The WorkflowState contract does this and that...
 */
contract WorkflowState {
    // boolean return
    // numeric return

    /*
       -100
       0
       ______
       0
       100
    /*
	/*
	float return
       -100.0
       0.0
       ______
       0.0
       100.0
    /*

	function WorkflowState () {

	}
}

/**
 * The workflow contract does this and that...
 */
contract workflowExecutor {
	 function executeByAction() public returns (address) {
        balances[msg.sender] += msg.value;

        LogDepositMade(msg.sender, msg.value); // fire event

        return balances[msg.sender];
    }
    private replicateForInstace() public return (instantiatedWorkflow) {

    }
}

/**
 * The workflowAction contract does this and that...
 */
contract workflowAction {
	function workflowAction () {
		// will change state
	}
}


function setAgentContract() write right name

contract token {
    address public creator;
    string public symbol;
    string public name;
    uint public baseUnit;
    uint totalSupply;
    mapping (address => uint) balanceOf;
    mapping (address => mapping(address => bool)) approveOf;
    mapping (address => mapping(address => bool)) approveOnceOf;
    mapping (address => mapping(address => uint)) approveOnceValueOf;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Events */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event AddressApproval(address indexed _address, address indexed _proxy, bool _result);
    event AddressApprovalOnce(address indexed _address, address indexed _proxy, uint256 _value);

    /*Initial */
    function token() {
        creator = msg.sender;
    }

    /* Creator functions */
    function setSymbol(string _s) creatorCheck returns(bool result) {
        symbol = _s;
        return true;
    }

    function setName(string _n) creatorCheck returns(bool result) {
        name = _n;
        return true;
    }

    function setBaseUnit(uint _unit) creatorCheck returns(bool result) {
        baseUnit = _unit;
        return true;
    }

    function getTotalSupply()  creatorCheck returns (uint supply) {
        return totalSupply;
    }

    function emmision(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] + _amount < balanceOf[creator]) {return false;}
        balanceOf[creator] += _amount;
        totalSupply += _amount;
        return true;
    }

    function burn(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] < _amount) {return false;}
        if (balanceOf[msg.sender] + _amount < balanceOf[msg.sender]) {return false;}
        balanceOf[creator] -= _amount;
        totalSupply += _amount;
        return true;
    }

    /* Agent function */

    function myBalance() returns (uint256 balance) {
        balance = balanceOf[msg.sender];
        return balance;
    }

    function transfer(address _to, uint256 _value) returns (bool result) {
        if (balanceOf[msg.sender] < _value) {return false;}
        if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) {return false;}
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        if(approveOf[_from][msg.sender])
        {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else if(approveOnceOf[_from][msg.sender] && approveOnceValueOf[_from][msg.sender]<=_value) {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        }
    }

    function approve(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = true;
        AddressApproval(_address, msg.sender, true);
        return true;
    }

    function unapprove(address _address) returns (bool success) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

    function approveOnce(address _address, uint256 _maxValue) returns (bool success) {
        approveOnceOf[msg.sender][_address] = true;
        approveOnceValueOf[msg.sender][_address] = _maxValue;
        AddressApprovalOnce(_address, msg.sender, _maxValue);
        return true;
    }

    function unapproveOnce(address _address) returns (bool success) {
        approveOnceOf[msg.sender][_address] = false;
        approveOnceValueOf[msg.sender][_address] = 0;
        return true;
    }

    function isApprovedOnceFor(address _target, address _proxy) returns (uint256 maxValue) {
        maxValue = approveOnceValueOf[_target][_proxy];
        return maxValue;
    }

    function isApprovedFor(address _target, address _proxy) constant returns (bool success) {
        success = approveOnceOf[_target][_proxy];
        return success;
    }
}

contract agent {
    address creator;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Struct */
    AgentContract[] public agentContracts;

    struct AgentContract {
        address agentContractAddr;
        string abi;
        string helper;
    }

    /* Functions */
    function agent() {
        creator = msg.sender;
    }

    function setAgentContract(address _agentContractAddr, address _abi, address _helper) creatorCheck returns(uint agentContractID) {
        agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _agentContractAddr;
        a.abi = _abi;
        a.helper = _helper;
        return (agentContractID);
    }
}

contract DAO {
    address public daoFounder;
    address public daoFounderContr;
    address public daoMarketContr;
    address public daoGovermentContr;
    bool public initialization;
    uint public creditAmount;
    uint public sharesAmount;
    uint public creditTurn;
    uint public numAgents;

    token public daoShares;
    token public daoCredits;

    /* Assets data */
    Asset[] public assetsList;
    mapping (address => uint) public assetDataOf;
    mapping (address => bool) public assetExistOf;
    struct Asset {
        address assetAddr;
    }

    /* Agents data */
    Agent[] public agentsList;
    mapping (address => uint) public agentDataOf;
    mapping (address => bool) public agentActiveOf;
    struct Agent {
        address agentContrAddr;
        uint joinData;
    }

    function DAO(token _shares, token _credits, market _daoMarketContr, goverment _daoGovermentContr) {
        daoFounder = msg.sender;
        daoShares = token(_shares);
        daoCredits = token(_credits);
        daoMarketContr = _daoMarketContr;
        daoGovermentContr = _daoGovermentContr;
    }

    function initializationDaoBalances(uint _founderSharesAmount, uint _founderCreditsAmount) returns (bool result) {
        if(!initialization) {
        daoShares.emission(msg.sender, _founderSharesAmount);
        sharesAmount = _founderSharesAmount;
        daoCredits.emission(msg.sender, _founderCreditsAmount);
        creditAmount = _founderCreditsAmount;
        return true;
        }
    }

    function daoEfficiency() returns (uint daoEfficiency) {
        daoEfficiency = creditTurn*100/creditAmount;
    }

    function daoShareCost() returns (uint shareCost) {
        shareCost = creditTurn/sharesAmount;
    }

    function daoCreditPower() returns (uint creditPower) {
        creditPower = sharesAmount*100/creditTurn;
    }

    function daoShareSale(uint _shareAmount) returns (uint creditReward) {
        if(daoShares.tokenBalanceOf(msg.sender)>=_shareAmount) {
            creditReward = daoShareCost()*_shareAmount;
            daoCredits.emission(msg.sender, creditReward);
            daoShares.burn(msg.sender, _shareAmount);
        }
    }

    function daoShareBuy(uint _creditAmount) returns (uint shares) {
        if(daoCredits.tokenBalanceOf(msg.sender)>=_creditAmount) {
            shares = daoCreditPower()*_creditAmount;
            daoShares.emission(msg.sender, shares);
            daoCredits.burn(msg.sender, _creditAmount);
        }
    }

    function daoSharesEmission(address _agentContrAddr, uint _sharesAmount) {
        daoShares.emission(_agentContrAddr, _sharesAmount);
    }

    function daoCreditEmission(uint _creditsAMount) {
        daoCredits.emission(msg.sender, _creditsAMount);
    }

    function setAgent(address _agentContAddr) returns(uint agentID) {
        if(daoShares.tokenBalanceOf(msg.sender)>0) {
            agentID = agentsList.length++;
            Agent a = agentsList[agentID];
            a.agentContrAddr = _agentContAddr;
            a.joinData = now;
            uint newAgentSharesAmount;
            newAgentSharesAmount = sharesAmount/numAgents;
            daoShares.emission(_agentContAddr, newAgentSharesAmount);
            numAgents = agentID;
            agentDataOf[_agentContAddr] = agentID;
            agentActiveOf[_agentContAddr] = true;
            return agentID;
        }
    }

    function setAssets(address _assetAddr) returns(uint assetID) {
        if (msg.sender == daoMarketContr) {
            assetID = assetsList.length++;
            Asset a = assetsList[assetID];
            a.assetAddr = _assetAddr;
            assetDataOf[_assetAddr] = assetID;
            assetExistOf[_assetAddr] = true;
            return assetID;
        }
    }
}

contract market {
    address daoAddr;
    DAO public dao;

    struct Order {
        uint orderID;
        address owner;
        uint amount;
        uint price;
    }

    struct OrderList {
        address assetAddr;
        Order[] orders;
    }

    OrderList[] public sellList;
    Order[] public sellOrders;
    mapping (address => bool) sellExistOf;
    mapping (address => uint) sellDataOf;

    OrderList[] public buyList;
    Order[] public buyOrders;
    mapping (address => bool) buyExistOf;
    mapping (address => uint) buyDataOf;

    function getSellList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function getBuyList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function addSell(address _assetAddr, uint _amount, uint _price) returns(uint sellID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(sellExistOf[_assetAddr]) {
                uint assetID;
                assetID = sellDataOf[_assetAddr];
                OrderList[] assetOrders = sellList[assetID];
                sellID = sellOrders.sellOrders.length++;
                sellOrders.orders[sellID] = Order({orderID: sellID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function addBuy(address _assetAddr, uint _amount, uint _price) returns(uint buyID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(buyExistOf[_assetAddr]) {
                uint assetID;
                assetID = buyDataOf[_assetAddr];
                OrderList[] buyOrders = buyList[assetID];
                buyID = buyOrders.orders.length++;
                buyOrders.orders[buyID] = Order({orderID: buyID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function BuyDeal(address _assetAddr, uint _buyID) {
        uint profit = msg.value*dao.daoEfficiency()/100;
        dao.daoCredits.emission(daoAddr, profit);
        return true;
    }

    function SellDeal(address _assetAddr, uint sellID) returns(bool result) {
        return true;
    }

}

contract goverment {
    address daoAddr;
    DAO public dao;

}

contract token {
    address public creator;
    string public symbol;
    string public name;
    uint public baseUnit;
    uint totalSupply;
    mapping (address => uint) balanceOf;
    mapping (address => mapping(address => bool)) approveOf;
    mapping (address => mapping(address => bool)) approveOnceOf;
    mapping (address => mapping(address => uint)) approveOnceValueOf;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Events */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event AddressApproval(address indexed _address, address indexed _proxy, bool _result);
    event AddressApprovalOnce(address indexed _address, address indexed _proxy, uint256 _value);

    /*Initial */
    function token() {
        creator = msg.sender;
    }

    /* Creator functions */
    function setSymbol(string _s) creatorCheck returns(bool result) {
        symbol = _s;
        return true;
    }

    function setName(string _n) creatorCheck returns(bool result) {
        name = _n;
        return true;
    }

    function setBaseUnit(uint _unit) creatorCheck returns(bool result) {
        baseUnit = _unit;
        return true;
    }

    function getTotalSupply()  creatorCheck returns (uint supply) {
        return totalSupply;
    }

    function emmision(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] + _amount < balanceOf[creator]) {return false;}
        balanceOf[creator] += _amount;
        totalSupply += _amount;
        return true;
    }

    function burn(uint _amount) creatorCheck returns(bool result) {
        if (balanceOf[creator] < _amount) {return false;}
        if (balanceOf[msg.sender] + _amount < balanceOf[msg.sender]) {return false;}
        balanceOf[creator] -= _amount;
        totalSupply += _amount;
        return true;
    }

    /* Agent function */

    function myBalance() returns (uint256 balance) {
        balance = balanceOf[msg.sender];
        return balance;
    }

    function transfer(address _to, uint256 _value) returns (bool result) {
        if (balanceOf[msg.sender] < _value) {return false;}
        if (balanceOf[msg.sender] + _value < balanceOf[msg.sender]) {return false;}
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        if(approveOf[_from][msg.sender])
        {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        } else if(approveOnceOf[_from][msg.sender] && approveOnceValueOf[_from][msg.sender]<=_value) {
            if (balanceOf[_from] < _value) {return false;}
            if (balanceOf[_from] + _value < balanceOf[_from]) {return false;}
            balanceOf[_from] -= _value;
            balanceOf[_to] += _value;
            Transfer(_from, _to, _value);
            return true;
        }
    }

    function approve(address _address) returns (bool result) {
        approveOf[msg.sender][_address] = true;
        AddressApproval(_address, msg.sender, true);
        return true;
    }

    function unapprove(address _address) returns (bool success) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

    function approveOnce(address _address, uint256 _maxValue) returns (bool success) {
        approveOnceOf[msg.sender][_address] = true;
        approveOnceValueOf[msg.sender][_address] = _maxValue;
        AddressApprovalOnce(_address, msg.sender, _maxValue);
        return true;
    }

    function unapproveOnce(address _address) returns (bool success) {
        approveOnceOf[msg.sender][_address] = false;
        approveOnceValueOf[msg.sender][_address] = 0;
        return true;
    }

    function isApprovedOnceFor(address _target, address _proxy) returns (uint256 maxValue) {
        maxValue = approveOnceValueOf[_target][_proxy];
        return maxValue;
    }

    function isApprovedFor(address _target, address _proxy) constant returns (bool success) {
        success = approveOnceOf[_target][_proxy];
        return success;
    }
}

contract agent {
    address creator;

    modifier creatorCheck { if (msg.sender == creator) _ }

    /* Struct */
    AgentContract[] public agentContracts;

    struct AgentContract {
        address agentContractAddr;
        string abi;
        string helper;
    }

    /* Functions */
    function agent() {
        creator = msg.sender;
    }

    function setAgentToken(address _agentContractAddr, address _abi, address _helper) creatorCheck returns(uint agentContractID) {
        agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _agentContractAddr;
        a.abi = _abi;
        a.helper = _helper;
        return (agentContractID);
    }
}

contract DAO {
    address public daoFounder;
    address public daoFounderContr;
    address public daoMarketContr;
    address public daoGovermentContr;
    bool public initialization;
    uint public creditAmount;
    uint public sharesAmount;
    uint public creditTurn;
    uint public numAgents;

    token public daoShares;
    token public daoCredits;

    /* Assets data */
    Asset[] public assetsList;
    mapping (address => uint) public assetDataOf;
    mapping (address => bool) public assetExistOf;
    struct Asset {
        address assetAddr;
    }

    /* Agents data */
    Agent[] public agentsList;
    mapping (address => uint) public agentDataOf;
    mapping (address => bool) public agentActiveOf;
    struct Agent {
        address agentContrAddr;
        uint joinData;
    }

    function DAO(token _shares, token _credits, market _daoMarketContr, goverment _daoGovermentContr) {
        daoFounder = msg.sender;
        daoShares = token(_shares);
        daoCredits = token(_credits);
        daoMarketContr = _daoMarketContr;
        daoGovermentContr = _daoGovermentContr;
    }

    function initializationDaoBalances(uint _founderSharesAmount, uint _founderCreditsAmount) returns (bool result) {
        if(!initialization) {
        daoShares.emission(msg.sender, _founderSharesAmount);
        sharesAmount = _founderSharesAmount;
        daoCredits.emission(msg.sender, _founderCreditsAmount);
        creditAmount = _founderCreditsAmount;
        return true;
        }
    }

    function daoEfficiency() returns (uint daoEfficiency) {
        daoEfficiency = creditTurn*100/creditAmount;
    }

    function daoShareCost() returns (uint shareCost) {
        shareCost = creditTurn/sharesAmount;
    }

    function daoCreditPower() returns (uint creditPower) {
        creditPower = sharesAmount*100/creditTurn;
    }

    function daoShareSale(uint _shareAmount) returns (uint creditReward) {
        if(daoShares.tokenBalanceOf(msg.sender)>=_shareAmount) {
            creditReward = daoShareCost()*_shareAmount;
            daoCredits.emission(msg.sender, creditReward);
            daoShares.burn(msg.sender, _shareAmount);
        }
    }

    function daoShareBuy(uint _creditAmount) returns (uint shares) {
        if(daoCredits.tokenBalanceOf(msg.sender)>=_creditAmount) {
            shares = daoCreditPower()*_creditAmount;
            daoShares.emission(msg.sender, shares);
            daoCredits.burn(msg.sender, _creditAmount);
        }
    }

    function daoSharesEmission(address _agentContrAddr, uint _sharesAmount) {
        daoShares.emission(_agentContrAddr, _sharesAmount);
    }

    function daoCreditEmission(uint _creditsAMount) {
        daoCredits.emission(msg.sender, _creditsAMount);
    }

    function setAgent(address _agentContAddr) returns(uint agentID) {
        if(daoShares.tokenBalanceOf(msg.sender)>0) {
            agentID = agentsList.length++;
            Agent a = agentsList[agentID];
            a.agentContrAddr = _agentContAddr;
            a.joinData = now;
            uint newAgentSharesAmount;
            newAgentSharesAmount = sharesAmount/numAgents;
            daoShares.emission(_agentContAddr, newAgentSharesAmount);
            numAgents = agentID;
            agentDataOf[_agentContAddr] = agentID;
            agentActiveOf[_agentContAddr] = true;
            return agentID;
        }
    }

    function setAssets(address _assetAddr) returns(uint assetID) {
        if (msg.sender == daoMarketContr) {
            assetID = assetsList.length++;
            Asset a = assetsList[assetID];
            a.assetAddr = _assetAddr;
            assetDataOf[_assetAddr] = assetID;
            assetExistOf[_assetAddr] = true;
            return assetID;
        }
    }
}

contract market {
    address daoAddr;
    DAO public dao;

    struct Order {
        uint orderID;
        address owner;
        uint amount;
        uint price;
    }

    struct OrderList {
        address assetAddr;
        Order[] orders;
    }

    OrderList[] public sellList;
    Order[] public sellOrders;
    mapping (address => bool) sellExistOf;
    mapping (address => uint) sellDataOf;

    OrderList[] public buyList;
    Order[] public buyOrders;
    mapping (address => bool) buyExistOf;
    mapping (address => uint) buyDataOf;

    function getSellList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function getBuyList(address _assetAddr) returns(uint assetID) {
        return 0;
    }

    function addSell(address _assetAddr, uint _amount, uint _price) returns(uint sellID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(sellExistOf[_assetAddr]) {
                uint assetID;
                assetID = sellDataOf[_assetAddr];
                OrderList[] assetOrders = sellList[assetID];
                sellID = sellOrders.sellOrders.length++;
                sellOrders.orders[sellID] = Order({orderID: sellID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function addBuy(address _assetAddr, uint _amount, uint _price) returns(uint buyID) {
        if (dao.agentActiveOf(msg.sender) && dao.assetExistOf(_assetAddr)) {
            if(buyExistOf[_assetAddr]) {
                uint assetID;
                assetID = buyDataOf[_assetAddr];
                OrderList[] buyOrders = buyList[assetID];
                buyID = buyOrders.orders.length++;
                buyOrders.orders[buyID] = Order({orderID: buyID, owner: msg.sender, amount: _amount, price: _price});
                return assetID;
            }

        }
    }

    function BuyDeal(address _assetAddr, uint _buyID) {
        uint profit = msg.value*dao.daoEfficiency()/100;
        dao.daoCredits.emission(daoAddr, profit);
        return true;
    }

    function SellDeal(address _assetAddr, uint sellID) returns(bool result) {
        return true;
    }

}

contract goverment {
    address daoAddr;
    DAO public dao;

}


Remove unecessary code from Context (#2718)

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}


add constant qualifier

add constant qualifier

pragma solidity ^0.4.11;

import "../token/StandardToken.sol";

/**
 * @title SimpleToken
 * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
 * Note they can later distribute these tokens as they wish using `transfer` and other
 * `StandardToken` functions.
 */
contract SimpleToken is StandardToken {

  string public constant name = "SimpleToken";
  string public constant symbol = "SIM";
  uint256 public constant decimals = 18;

  uint256 public constant INITIAL_SUPPLY = 10000;

  /**
   * @dev Contructor that gives msg.sender all of existing tokens.
   */
  function SimpleToken() {
    totalSupply = INITIAL_SUPPLY;
    balances[msg.sender] = INITIAL_SUPPLY;
  }

}

pragma solidity ^0.4.11;

import "./StandardToken.sol";

/**
 * @title SimpleToken
 * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
 * Note they can later distribute these tokens as they wish using `transfer` and other
 * `StandardToken` functions.
 */
contract SimpleToken is StandardToken {

  string public name = "SimpleToken";
  string public symbol = "SIM";
  uint256 public decimals = 18;
  uint256 public INITIAL_SUPPLY = 10000;

  /**
   * @dev Contructor that gives msg.sender all of existing tokens.
   */
  function SimpleToken() {
    totalSupply = INITIAL_SUPPLY;
    balances[msg.sender] = INITIAL_SUPPLY;
  }

}


PM: Remove checkDepositPenaltyEscrowSplit in ERC20TicketBroker

pragma solidity ^0.4.25;
// solium-disable-next-line
pragma experimental ABIEncoderV2;

import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./TicketBroker.sol";

// JUST AN EXAMPLE
contract ERC20TicketBroker is TicketBroker {
    ERC20 public token;

    constructor(
        address _token,
        uint256 _minPenaltyEscrow,
        uint256 _unlockPeriod
    )
        TicketBroker(_minPenaltyEscrow, _unlockPeriod)
        public
    {
        token = ERC20(_token);
    }

    function fundAndApproveSigners(
        uint256 _depositAmount,
        uint256 _penaltyEscrowAmount,
        address[] _signers
    )
        external
        processDeposit(msg.sender, _depositAmount)
        processPenaltyEscrow(msg.sender, _penaltyEscrowAmount)
    {
        approveSigners(_signers);

        require(
            token.transferFrom(msg.sender, address(this), _depositAmount + _penaltyEscrowAmount),
            "token transfer for deposit and penalty escrow failed"
        );
    }

    function fundDeposit(uint256 _amount)
        external
        processDeposit(msg.sender, _amount)
    {
        require(
            token.transferFrom(msg.sender, address(this), _amount),
            "token transfer for deposit failed"
        );
    }

    function fundPenaltyEscrow(uint256 _amount)
        external
        processPenaltyEscrow(msg.sender, _amount)
    {
        require(
            token.transferFrom(msg.sender, address(this), _amount),
            "token transfer for penalty escrow failed"
        );
    }

    function withdrawTransfer(address _sender, uint256 _amount) internal {
        token.transfer(_sender, _amount);
    }

    function winningTicketTransfer(address _recipient, uint256 _amount) internal {
        token.transfer(_recipient, _amount);
    }

    function penaltyEscrowSlash(uint256 _amount) internal {
        token.transfer(address(0), _amount);
    }
}

pragma solidity ^0.4.25;
// solium-disable-next-line
pragma experimental ABIEncoderV2;

import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./TicketBroker.sol";

// JUST AN EXAMPLE
contract ERC20TicketBroker is TicketBroker {
    ERC20 public token;

    constructor(
        address _token,
        uint256 _minPenaltyEscrow,
        uint256 _unlockPeriod
    )
        TicketBroker(_minPenaltyEscrow, _unlockPeriod)
        public
    {
        token = ERC20(_token);
    }

    function fundAndApproveSigners(
        uint256 _depositAmount,
        uint256 _penaltyEscrowAmount,
        address[] _signers
    )
        external
        checkDepositPenaltyEscrowSplit(_depositAmount, _penaltyEscrowAmount)
        processDeposit(msg.sender, _depositAmount)
        processPenaltyEscrow(msg.sender, _penaltyEscrowAmount)
    {
        approveSigners(_signers);

        require(
            token.transferFrom(msg.sender, address(this), _depositAmount + _penaltyEscrowAmount),
            "token transfer for deposit and penalty escrow failed"
        );
    }

    function fundDeposit(uint256 _amount)
        external
        processDeposit(msg.sender, _amount)
    {
        require(
            token.transferFrom(msg.sender, address(this), _amount),
            "token transfer for deposit failed"
        );
    }

    function fundPenaltyEscrow(uint256 _amount)
        external
        processPenaltyEscrow(msg.sender, _amount)
    {
        require(
            token.transferFrom(msg.sender, address(this), _amount),
            "token transfer for penalty escrow failed"
        );
    }

    function withdrawTransfer(address _sender, uint256 _amount) internal {
        token.transfer(_sender, _amount);
    }

    function winningTicketTransfer(address _recipient, uint256 _amount) internal {
        token.transfer(_recipient, _amount);
    }

    function penaltyEscrowSlash(uint256 _amount) internal {
        token.transfer(address(0), _amount);
    }
}


Fix node manager contract: check node before set stake

pragma solidity ^0.4.24;

import "../lib/address_array.sol";
import "../lib/safe_math.sol";
import "../common/error.sol";
import "../common/admin.sol";
import "../common/address.sol";

/// @title The interface of node_manager
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
interface NodeInterface {

    event ApproveNode(address indexed _node);
    event DeleteNode(address indexed _node);
    event SetStake(address indexed _node, uint _stake);

    /// @notice Approve to be consensus node. status will be start
    function approveNode(address _node) external returns (bool);

    /// @notice Delete the consensus node that has been approved. status will be close
    function deleteNode(address _node) external returns (bool);

    /// @notice List the consensus nodes that have been approved
    /// which means list the node whose status is start
    function listNode() external view returns (address[]);

    /// @notice Set node stake
    function setStake(address _node, uint64 stake) external;
    /*
     * @notice Get the status of the node:
     * @return 0: Close
     * @return 1: Start
     */
    function getStatus(address _node) external view returns (uint8);

    /// @notice Node stake list
    function listStake() external view returns (uint64[] _stakes);

    /// @notice Stake permillage
    function stakePermillage(address _node) external view returns (uint64);
}

/// @title Node manager contract
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
/// @notice The address: 0xffffffffffffffffffffffffffffffffff020001
contract NodeManager is NodeInterface, Error, ReservedAddress {

    mapping(address => NodeStatus) public status;
    // Recode the operation of the block
    mapping(uint => bool) block_op;
    // Consensus node list
    address[] nodes;
    mapping(address => uint64) stakes;

    // Default: Close
    enum NodeStatus { Close, Start }

    Admin admin = Admin(adminAddr);

    // Should operate one time in a block
    modifier oneOperate {
        if (!block_op[block.number])
            _;
        else {
            emit ErrorLog(ErrorType.NotOneOperate, "should operate one time in a block");
            return;
        }
    }

    modifier onlyClose(address _node) {
        if (NodeStatus.Close == status[_node])
            _;
        else {
            emit ErrorLog(ErrorType.NotClose, "node does not close");
            return;
        }
    }

    modifier onlyStart(address _node) {
        if (NodeStatus.Start == status[_node])
            _;
        else {
            emit ErrorLog(ErrorType.NotStart, "node does not start");
            return;
        }
    }

    modifier onlyAdmin {
        if (admin.isAdmin(msg.sender))
            _;
        else return;
    }

    /// @notice Setup
    constructor(address[] _nodes, uint64[] _stakes)
        public
    {
        // Initialize the address to Start
        require(_nodes.length == _stakes.length);
        for (uint i = 0; i < _nodes.length; i++) {
            status[_nodes[i]] = NodeStatus.Start;
            nodes.push(_nodes[i]);
            stakes[_nodes[i]] = _stakes[i];
        }
    }

    /// @notice Set node stake
    function setStake(address _node, uint64 stake)
        public
        onlyAdmin
        returns (bool)
    {
        require(AddressArray.exist(_node, nodes));
        emit SetStake(_node, stake);
        stakes[_node] = stake;
        return true;
    }

    /// @notice Approve the new node
    /// @param _node The node to be approved
    /// @return true if successed, otherwise false
    function approveNode(address _node)
        public
        onlyAdmin
        oneOperate
        onlyClose(_node)
        returns (bool)
    {
        status[_node] = NodeStatus.Start;
        block_op[block.number] = true;
        nodes.push(_node);
        emit ApproveNode(_node);
        return true;
    }

    /// @notice Delete the node
    /// @param _node The node to be deleted
    /// @return true if successed, otherwise false
    function deleteNode(address _node)
        public
        onlyAdmin
        oneOperate
        onlyStart(_node)
        returns (bool)
    {
        require(AddressArray.remove(_node, nodes));
        block_op[block.number] = false;
        status[_node] = NodeStatus.Close;
        stakes[_node] = 0;
        emit DeleteNode(_node);
        return true;
    }

    /// @notice Query the consensus nodes
    /// @return All the consensus nodes
    function listNode()
        public
        view
        returns (address[])
    {
        return nodes;
    }

    /// @notice Query the status of node
    /// @param _node The node to be deleted
    /// @return The status of the node
    function getStatus(address _node)
        public
        view
        returns (uint8)
    {
        return uint8(status[_node]);
    }

    /// @notice Node stake list
    /// @return All the node stake list
    function listStake()
        public
        view
        returns (uint64[] _stakes)
    {
        _stakes = new uint64[](nodes.length);
        for (uint j = 0; j < nodes.length; j++) {
            _stakes[j] = stakes[nodes[j]];
        }
        return _stakes;
    }

    /// @notice Stake permillage
    /// This is the slot number which ignore the remainder, not exactly precise.
    /// https://en.wikipedia.org/wiki/Largest_remainder_method
    /// Hare quota
    function stakePermillage(address _node)
        public
        view
        returns (uint64)
    {
        uint total;
        for (uint j = 0; j < nodes.length; j++) {
            total = SafeMath.add(uint(total), uint(stakes[nodes[j]]));
        }
        return uint64(SafeMath.div(SafeMath.mul(stakes[_node], 1000), total));
    }
}

pragma solidity ^0.4.24;

import "../lib/address_array.sol";
import "../lib/safe_math.sol";
import "../common/error.sol";
import "../common/admin.sol";
import "../common/address.sol";

/// @title The interface of node_manager
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
interface NodeInterface {

    event ApproveNode(address indexed _node);
    event DeleteNode(address indexed _node);
    event SetStake(address indexed _node, uint _stake);

    /// @notice Approve to be consensus node. status will be start
    function approveNode(address _node) external returns (bool);

    /// @notice Delete the consensus node that has been approved. status will be close
    function deleteNode(address _node) external returns (bool);

    /// @notice List the consensus nodes that have been approved
    /// which means list the node whose status is start
    function listNode() external view returns (address[]);

    /// @notice Set node stake
    function setStake(address _node, uint64 stake) external;
    /*
     * @notice Get the status of the node:
     * @return 0: Close
     * @return 1: Start
     */
    function getStatus(address _node) external view returns (uint8);

    /// @notice Node stake list
    function listStake() external view returns (uint64[] _stakes);

    /// @notice Stake permillage
    function stakePermillage(address _node) external view returns (uint64);
}

/// @title Node manager contract
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
/// @notice The address: 0xffffffffffffffffffffffffffffffffff020001
contract NodeManager is NodeInterface, Error, ReservedAddress {

    mapping(address => NodeStatus) public status;
    // Recode the operation of the block
    mapping(uint => bool) block_op;
    // Consensus node list
    address[] nodes;
    mapping(address => uint64) stakes;

    // Default: Close
    enum NodeStatus { Close, Start }

    Admin admin = Admin(adminAddr);

    // Should operate one time in a block
    modifier oneOperate {
        if (!block_op[block.number])
            _;
        else {
            emit ErrorLog(ErrorType.NotOneOperate, "should operate one time in a block");
            return;
        }
    }

    modifier onlyClose(address _node) {
        if (NodeStatus.Close == status[_node])
            _;
        else {
            emit ErrorLog(ErrorType.NotClose, "node does not close");
            return;
        }
    }

    modifier onlyStart(address _node) {
        if (NodeStatus.Start == status[_node])
            _;
        else {
            emit ErrorLog(ErrorType.NotStart, "node does not start");
            return;
        }
    }

    modifier onlyAdmin {
        if (admin.isAdmin(msg.sender))
            _;
        else return;
    }

    /// @notice Setup
    constructor(address[] _nodes, uint64[] _stakes)
        public
    {
        // Initialize the address to Start
        require(_nodes.length == _stakes.length);
        for (uint i = 0; i < _nodes.length; i++) {
            status[_nodes[i]] = NodeStatus.Start;
            nodes.push(_nodes[i]);
            stakes[_nodes[i]] = _stakes[i];
        }
    }

    /// @notice Set node stake
    function setStake(address _node, uint64 stake)
        public
        onlyAdmin
    {
        emit SetStake(_node, stake);
        stakes[_node] = stake;
    }

    /// @notice Approve the new node
    /// @param _node The node to be approved
    /// @return true if successed, otherwise false
    function approveNode(address _node)
        public
        onlyAdmin
        oneOperate
        onlyClose(_node)
        returns (bool)
    {
        status[_node] = NodeStatus.Start;
        block_op[block.number] = true;
        nodes.push(_node);
        emit ApproveNode(_node);
        return true;
    }

    /// @notice Delete the node
    /// @param _node The node to be deleted
    /// @return true if successed, otherwise false
    function deleteNode(address _node)
        public
        onlyAdmin
        oneOperate
        onlyStart(_node)
        returns (bool)
    {
        require(AddressArray.remove(_node, nodes));
        block_op[block.number] = false;
        status[_node] = NodeStatus.Close;
        stakes[_node] = 0;
        emit DeleteNode(_node);
        return true;
    }

    /// @notice Query the consensus nodes
    /// @return All the consensus nodes
    function listNode()
        public
        view
        returns (address[])
    {
        return nodes;
    }

    /// @notice Query the status of node
    /// @param _node The node to be deleted
    /// @return The status of the node
    function getStatus(address _node)
        public
        view
        returns (uint8)
    {
        return uint8(status[_node]);
    }

    /// @notice Node stake list
    /// @return All the node stake list
    function listStake()
        public
        view
        returns (uint64[] memory _stakes)
    {
        _stakes = new uint64[](nodes.length);
        for (uint j = 0; j < nodes.length; j++) {
            _stakes[j] = stakes[nodes[j]];
        }
        return _stakes;
    }

    /// @notice Stake permillage
    /// This is the slot number which ignore the remainder, not exactly precise.
    /// https://en.wikipedia.org/wiki/Largest_remainder_method
    /// Hare quota
    function stakePermillage(address _node)
        public
        view
        returns (uint64)
    {
        uint total;
        for (uint j = 0; j < nodes.length; j++) {
            total = SafeMath.add(uint(total), uint(stakes[nodes[j]]));
        }
        return uint64(SafeMath.div(SafeMath.mul(stakes[_node], 1000), total));
    }
}