adding User struct for accounting of users positions and prices.

/*
    Copyright 2017 Phillip A. Elsasser

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

pragma solidity ^0.4.0;

import "./Creatable.sol";
import "./Oraclize/oraclizeAPI.sol";

//TODO: fix style issues
//      add accounting for users and positions
//      how to hold ether for needed gas
//      how to hold collateral pool
//      add failsafe for pool distribution.
contract MarketContract is Creatable, usingOraclize  {

    struct User {
        address userAddress;
        uint[] prices;                      // prices user has transacted at (fifo upon exit)
        mapping(uint => int) priceToQty;    // prices to qty at price for users position
        int netPosition;                    // net position across all prices
    }

    struct Order {
        address maker;
        address taker;
        uint qty;
        uint price;
        uint8 makerSide;
        uint expirationTimeStamp;
        bytes32 orderHash;
    }

    // constants
    string public CONTRACT_NAME;
    address public BASE_TOKEN;
    uint public PRICE_CAP;
    uint public PRICE_FLOOR;
    uint public PRICE_DECIMAL_PLACES;   // how to convert the pricing from decimal format (if valid) to integer
    uint public EXPIRATION;
    string public ORACLE_DATA_SOURCE;
    string public ORACLE_QUERY;
    uint public ORACLE_QUERY_REPEAT;
    uint8 public BUY_SIDE = 0;
    uint8 public SELL_SIDE = 1;
    uint public COST_PER_QUERY = 2 finney;    // leave static for now, price of first query from oraclize is 0

    // state variables
    string public lastPriceQueryResult;
    uint public lastPrice;
    bool public isExpired;
    mapping(bytes32 => bool) validQueryIDs;

    // accounting
    mapping(bytes32 => User) addressToUser;

    // events
    event NewOracleQuery(string description);
    event UpdatedLastPrice(string price);
    event ContractSettled();

    function MarketContract(
        string contractName,
        address baseToken,
        string oracleDataSource,
        string oracleQuery,
        uint oracleQueryRepeatSeconds,
        uint floorPrice,
        uint capPrice,
        uint priceDecimalPlaces,
        uint secondsToExpiration
    ) payable {

        require(capPrice > floorPrice);
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        CONTRACT_NAME = contractName;
        BASE_TOKEN = baseToken;
        PRICE_CAP = capPrice;
        PRICE_FLOOR = floorPrice;
        EXPIRATION = now + secondsToExpiration;
        ORACLE_DATA_SOURCE = oracleDataSource;
        ORACLE_QUERY = oracleQuery;
        ORACLE_QUERY_REPEAT = oracleQueryRepeatSeconds;
        PRICE_DECIMAL_PLACES = priceDecimalPlaces;
        require(checkSufficientStartingBalance(secondsToExpiration));
        queryOracle();  // schedules recursive calls to oracle
    }

    function __callback(bytes32 queryID, string result, bytes proof) {
        require(validQueryIDs[queryID]);
        require(msg.sender == oraclize_cbAddress());
        lastPriceQueryResult = result;
        lastPrice = parseInt(result, PRICE_DECIMAL_PLACES);
        UpdatedLastPrice(result);
        delete validQueryIDs[queryID];
        checkSettlement();
        if (!isExpired) {
            queryOracle();  // set up our next query
        }
    }

    function queryOracle() internal
    {
        if (oraclize_getPrice(ORACLE_DATA_SOURCE) > this.balance) {
            NewOracleQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
            lastPriceQueryResult = "FAILED"; //TODO: failsafe
        } else {
            NewOracleQuery("Oraclize query was sent, standing by for the answer..");
            bytes32 queryId = oraclize_query(ORACLE_QUERY_REPEAT, ORACLE_DATA_SOURCE, ORACLE_QUERY);
            validQueryIDs[queryId] = true;
        }
    }

    function checkSettlement() internal
    {
        if(isExpired)   // already expired.
            return;

        if(now > EXPIRATION) {
            isExpired = true;   // time based expiration has occurred.
        } else if(lastPrice >= PRICE_CAP || lastPrice <= PRICE_FLOOR) {
            isExpired = true;   // we have breached/touched our pricing bands
        }

        if(isExpired) {
            settleContract();
        }
    }

    function settleContract() internal
    {
        // TODO: build mechanism for distribution of collateral
        ContractSettled();
    }

    // for now lets require alot of padding for the settlement,
    function checkSufficientStartingBalance(uint secondsToExpiration) private returns (bool isSufficient) {
        //uint costPerQuery = oraclize_getPrice(ORACLE_DATA_SOURCE); this doesn't work prior to first query(its free)
        uint expectedNoOfQueries = secondsToExpiration / ORACLE_QUERY_REPEAT;
        uint approxGasRequired = COST_PER_QUERY * expectedNoOfQueries;
        return this.balance > (approxGasRequired * 2);
    }
}

/*
    Copyright 2017 Phillip A. Elsasser

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

pragma solidity ^0.4.0;

import "./Creatable.sol";
import "./Oraclize/oraclizeAPI.sol";

//TODO: fix style issues
//      add accounting for users and positions
//      how to hold ether for needed gas
//      how to hold collateral pool
//      add failsafe for pool distribution.
contract MarketContract is Creatable, usingOraclize  {

    // constants
    string public CONTRACT_NAME;
    address public BASE_TOKEN;
    uint public PRICE_CAP;
    uint public PRICE_FLOOR;
    uint public PRICE_DECIMAL_PLACES;   // how to convert the pricing from decimal format (if valid) to integer
    uint public EXPIRATION;
    string public ORACLE_DATA_SOURCE;
    string public ORACLE_QUERY;
    uint public ORACLE_QUERY_REPEAT;
    uint8 public BUY_SIDE = 0;
    uint8 public SELL_SIDE = 1;
    uint public COST_PER_QUERY = 2 finney;    // leave static for now, price of first query from oraclize is 0

    // state variables
    string public lastPriceQueryResult;
    uint public lastPrice;
    bool public isExpired;
    mapping(bytes32 => bool) validQueryIDs;

    // how to map user to position?
    event NewOracleQuery(string description);
    event UpdatedLastPrice(string price);
    event ContractSettled();

    struct Order {
        address maker;
        address taker;
        uint qty;
        uint price;
        uint8 makerSide;
        uint expirationTimeStamp;
        bytes32 orderHash;
    }

    function MarketContract(
        string contractName,
        address baseToken,
        string oracleDataSource,
        string oracleQuery,
        uint oracleQueryRepeatSeconds,
        uint floorPrice,
        uint capPrice,
        uint priceDecimalPlaces,
        uint secondsToExpiration) payable {

        require(capPrice > floorPrice);
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        CONTRACT_NAME = contractName;
        BASE_TOKEN = baseToken;
        PRICE_CAP = capPrice;
        PRICE_FLOOR = floorPrice;
        EXPIRATION = now + secondsToExpiration;
        ORACLE_DATA_SOURCE = oracleDataSource;
        ORACLE_QUERY = oracleQuery;
        ORACLE_QUERY_REPEAT = oracleQueryRepeatSeconds;
        PRICE_DECIMAL_PLACES = priceDecimalPlaces;
        require(checkSufficientStartingBalance(secondsToExpiration));
        queryOracle();  // schedules recursive calls to oracle
    }

    function __callback(bytes32 queryID, string result, bytes proof) {
        require(validQueryIDs[queryID]);
        require(msg.sender == oraclize_cbAddress());
        lastPriceQueryResult = result;
        lastPrice = parseInt(result, PRICE_DECIMAL_PLACES);
        UpdatedLastPrice(result);
        delete validQueryIDs[queryID];
        checkSettlement();
        if (!isExpired) {
            queryOracle();  // set up our next query
        }
    }

    function queryOracle() internal
    {
        if (oraclize_getPrice(ORACLE_DATA_SOURCE) > this.balance) {
            NewOracleQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
            lastPriceQueryResult = "FAILED"; //TODO: failsafe
        } else {
            NewOracleQuery("Oraclize query was sent, standing by for the answer..");
            bytes32 queryId = oraclize_query(ORACLE_QUERY_REPEAT, ORACLE_DATA_SOURCE, ORACLE_QUERY);
            validQueryIDs[queryId] = true;
        }
    }

    function checkSettlement() internal
    {
        if(isExpired)   // already expired.
            return;

        if(now > EXPIRATION) {
            isExpired = true;   // time based expiration has occurred.
        } else if(lastPrice >= PRICE_CAP || lastPrice <= PRICE_FLOOR) {
            isExpired = true;   // we have breached/touched our pricing bands
        }

        if(isExpired) {
            settleContract();
        }
    }

    function settleContract() internal
    {
        // TODO: build mechanism for distribution of collateral
        ContractSettled();
    }

    // for now lets require alot of padding for the settlement,
    function checkSufficientStartingBalance(uint secondsToExpiration) private returns (bool isSufficient) {
        //uint costPerQuery = oraclize_getPrice(ORACLE_DATA_SOURCE); this doesn't work prior to first query(its free)
        uint expectedNoOfQueries = secondsToExpiration / ORACLE_QUERY_REPEAT;
        uint approxGasRequired = COST_PER_QUERY * expectedNoOfQueries;
        return this.balance > (approxGasRequired * 2);
    }
}


removed duplicate file

removed duplicate file

import "prefilled-token.sol";

pragma solidity ^0.4.11;

contract AEToken is PrefilledToken {

  // Date when the tokens won't be transferable anymore
  uint public transferableUntil;

  /**
   * HumanStandardToken(
      uint256  initialAmount,
      string   tokenName,
      uint8    decimalUnits,
      string   tokenSymbol
    )
   */
  function AEToken() HumanStandardToken(0, "AEToken", 16, "AE") {
    uint nYears = 2;

    transferableUntil = now + (60 * 60 * 24 * 365 * nYears);
  }

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

  function transferFrom(address _from, address _to, uint256 _value) only_transferable returns (bool success) {
    return super.transferFrom(_from, _to, _value);
  }

  modifier only_transferable () {
    if (now > transferableUntil) {
      throw;
    }
    _;
  }
}


Create PembiCoinICO.sol

Create PembiCoinICO.sol

pragma solidity 0.4.14;

// -----------------------------------------------------------------------------
// PembiCoin crowdsale contract.
// Copyright (c) 2017 Pembient, Inc.
// The MIT License.
// -----------------------------------------------------------------------------

contract PembiCoinICO {

    enum State {Active, Idle, Successful, Failed}

    State public currentState = State.Idle;
    uint256 public contributorCount = 0;

    address public owner;

    mapping(uint256 => address) private contributors;
    mapping(address => uint256) private amounts;

    event Transferred(
        address indexed _from,
        address indexed _to,
        uint256 _amount
    );

    event Transitioned(
        address indexed _subject,
        address indexed _object,
        State _oldState,
        State _newState
    );

    function PembiCoinICO() public {
        owner = msg.sender;
    }

    function() external payable inState(State.Active) {
        require(msg.value > 0);
        if (amounts[msg.sender] == 0) {
            contributors[contributorCount] = msg.sender;
            contributorCount = safeAdd(contributorCount, 1);
        }
        amounts[msg.sender] = safeAdd(amounts[msg.sender], msg.value);
        Transferred(msg.sender, address(this), msg.value);
    }

    function refund() external inState(State.Failed) {
        uint256 amount = amounts[msg.sender];
        assert(amount > 0 && amount <= this.balance);
        amounts[msg.sender] = 0;
        msg.sender.transfer(amount);
        Transferred(address(this), msg.sender, amount);
    }

    function payout() external inState(State.Successful) onlyOwner {
        uint256 amount = this.balance;
        owner.transfer(amount);
        Transferred(address(this), owner, amount);
    }

    function setActive() external inState(State.Idle) onlyOwner {
        State oldState = currentState;
        currentState = State.Active;
        Transitioned(msg.sender, address(this), oldState, currentState);
    }

    function setIdle() external inState(State.Active) onlyOwner {
        State oldState = currentState;
        currentState = State.Idle;
        Transitioned(msg.sender, address(this), oldState, currentState);
    }

    function setSuccessful() external inState(State.Idle) onlyOwner {
        State oldState = currentState;
        currentState = State.Successful;
        Transitioned(msg.sender, address(this), oldState, currentState);
    }

    function setFailed() external inState(State.Idle) onlyOwner {
        State oldState = currentState;
        currentState = State.Failed;
        Transitioned(msg.sender, address(this), oldState, currentState);
    }

    function getContribution(uint256 _i)
        external
        constant
        returns (address o_contributor, uint256 o_amount)
    {
        require(_i >= 0 && _i < contributorCount);
        o_contributor = contributors[_i];
        o_amount = amounts[o_contributor];
    }

    function safeAdd(uint256 a, uint256 b)
        private
        constant
        returns (uint256 o_sum)
    {
        o_sum = a + b;
        assert(o_sum >= a && o_sum >= b);
    }

    modifier inState(State _state) {
        require(_state == currentState);
        _;
    }

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

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


Contract of community

Contract of community

contract CommunityContract {

  struct Community {
    uint    uuid;
    address owner;
    bytes32 name;
    bytes32 description;
  }

  struct CommunityMember {
    uint uuid;
    address member;
    uint community;
  }

  Community[] public communities;
  mapping (address => uint) public communitiesToMembers;
  mapping (address => uint) public communitiesToOwner;

  function create( bytes32 _name, bytes32 _description ){
    uint uuid = communities.length++;
    communities[uuid] = Community({
      uuid: uuid,
      owner: msg.sender,
      name: _name,
      description: _description
    });
    communitiesToOwner[msg.sender] = uuid;
  }

  modifier hasCommunity (uint communityId) {
    if ( communitiesToOwner[msg.sender] == communityId ) return;
    _
  }

  function addMember(uint communityId, address member) hasCommunity(communityId) {
    communitiesToMembers[member] = communityId;
  }

  function removeMember(uint communityId, address member) hasCommunity(communityId) {
    delete communitiesToMembers[member];
  }

}

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


Solidity scrypt implementation

Solidity scrypt implementation

Partially done.

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


Update operation registration

Update operation registration

pragma solidity ^0.4.8;
import "./usingOraclize.sol";
import "./Verification.sol";

contract ComputationService is usingOraclize {
  struct Query {
    string URL;
    string JSON;
  }
  mapping(uint => Query) public computation;
  mapping(bytes32 => uint) public result;
  mapping(bytes32 => address) public request;
  mapping(address => bool) public arbiter;

  event newOraclizeQuery(string description);
  event newResult(string comp_result);
  event newOraclizeID(bytes32 ID);

  // constructor
  function ComputationService() {
    OAR = OraclizeAddrResolverI(0xafC1A0eDAF76076f2FDEAa968B85E3ef46fad79E);
  }

  function __callback(bytes32 _oraclizeID, string _result) {
    if (msg.sender != oraclize_cbAddress()) throw;
    newResult(_result);
    result[_oraclizeID] = parseInt(_result);

    // TODO: send result to verification contract
  }

  function compute(string _val1, string _val2, uint _operation) payable{
    if (!arbiter[msg.sender]) throw;
    bytes32 oraclizeID;

    Query memory _query = computation[_operation];
    _query.JSON = strConcat('\n{"val1": ', _val1, ', "val2": ', _val2, '}');

    newOraclizeQuery("Oraclize query was sent, standing by for the answer.");
    oraclizeID = oraclize_query(60, "URL", _query.URL, _query.JSON);

    // store address for specific request
    request[oraclizeID] = msg.sender;

    newOraclizeID(oraclizeID);
  }

  function registerOperation(uint _operation) payable {
    // operation 0: add two integers
    if (_operation == 0) {
      Query memory twoInt = Query("https://r98ro6hfj5.execute-api.eu-west-1.amazonaws.com/test/int", "");
      computation[0] = twoInt;
    }
  }

  function enableArbiter(address _arbiterAddress) payable {
    arbiter[_arbiterAddress] = true;
    Verification myArbiter = Verification(_arbiterAddress);
    myArbiter.enableService();
  }

  function disableArbiter(address _verification) payable {
    arbiter[_arbiterAddress] = false;
    Verification myArbiter = Verification(_arbiterAddress);
    myArbiter.disableService();
  }

  function getResult(bytes32 _oraclizeID) constant returns (uint) {
    return result[_oraclizeID];
  }
}

pragma solidity ^0.4.8;
import "./usingOraclize.sol";
import "./Verification.sol";

contract ComputationService is usingOraclize {
  struct Query {
    string URL;
    string JSON;
  }
  mapping(uint => Query) public computation;
  mapping(bytes32 => uint) public result;
  mapping(bytes32 => address) public request;
  mapping(address => bool) public arbiter;

  event newOraclizeQuery(string description);
  event newResult(string comp_result);
  event newOraclizeID(bytes32 ID);

  // constructor
  function ComputationService() {
    OAR = OraclizeAddrResolverI(0xafC1A0eDAF76076f2FDEAa968B85E3ef46fad79E);
  }

  function __callback(bytes32 _oraclizeID, string _result) {
    if (msg.sender != oraclize_cbAddress()) throw;
    newResult(_result);
    result[_oraclizeID] = parseInt(_result);

    // TODO: send result to verification contract
  }

  function compute(string _val1, string _val2, uint _variable) payable{
    if (!arbiter[msg.sender]) throw;
    bytes32 oraclizeID;

    Query memory _query = computation[_variable];
    _query.JSON = strConcat('\n{"val1": ', _val1, ', "val2": ', _val2, '}');

    newOraclizeQuery("Oraclize query was sent, standing by for the answer.");
    oraclizeID = oraclize_query(60, "URL", _query.URL, _query.JSON);

    // store address for specific request
    request[oraclizeID] = msg.sender;

    newOraclizeID(oraclizeID);
  }

  function register(uint _variable) payable {
    if (_variable == 0) {
      Query memory twoInt = Query("https://r98ro6hfj5.execute-api.eu-west-1.amazonaws.com/test/int", "");
      computation[0] = twoInt;
    }
  }

  function enableArbiter(address _verification) payable {
    arbiter[_verification] = true;
    Verification myArbiter = Verification(_verification);
    myArbiter.enableService();
  }

  function disableArbiter(address _verification) payable {
    arbiter[_verification] = false;
    Verification myArbiter = Verification(_verification);
    myArbiter.disableService();
  }

  function getResult(bytes32 _oraclizeID) constant returns (uint) {
    return result[_oraclizeID];
  }
}


solve solidity issue

solve solidity issue

contract abstract {}

contract owned is abstract {
  address owner;

  modifier onlyowner() {
    if (currentUser()==owner) _
  }

  function currentUser() returns (address) {
		return msg.sender;
	}
}

contract mortal is abstract, owned {
  function kill() {
    if (msg.sender == owner) suicide(owner);
  }
}

contract Launcheth is mortal {

	struct project {
		uint nbVersions;
		mapping(uint => string) versions;
		mapping(string => repository) packages;
	}

	struct repository {
		mapping (string => string) source;
		string checksum;
	}

	struct namespace{
		uint nbProjects;
		mapping(uint => string) names;
		mapping(string => project) projects;
	}

	struct namespaces {
		uint length;
		mapping(uint => string) ids;
		mapping(string => address) owners;
		mapping(string => namespace) spaces;
	}

	namespaces contexts;

	modifier nameSpaceOwner(string namespace, address owner) {
		if(contexts.owners[namespace] != owner) throw;
		_
	}

    function getNbNamespaces() constant returns (uint){
        return contexts.length;
    }

    function getNamespace(uint id) constant returns (string) {
        return contexts.ids[id];
    }

    function getNbProjects(string namespace) constant returns (uint){
        return contexts.spaces[namespace].nbProjects;
    }

    function getProject(string namespace, uint id) constant returns (string) {
        return contexts.spaces[namespace].names[id];
    }

    function getNbVersions(string namespace, string project) constant returns (uint) {
        return contexts.spaces[namespace].projects[project].nbVersions;
    }

    function getVersion(string namespace, string project, uint id) constant returns(string) {
        return contexts.spaces[namespace].projects[project].versions[id];
    }

    function getOwner(string namespace) constant returns(address) {
        return contexts.owners[namespace];
    }

	function LegalContractManager() {
        owner = currentUser();
	}

	function getSource(string namespace, string project, string version, string protocol) constant returns (string) {
		return contexts.spaces[namespace].projects[project].packages[version].source[protocol];
	}

	function getChecksum(string namespace, string project, string version) constant returns (string) {
		return contexts.spaces[namespace].projects[project].packages[version].checksum;
	}

	function canWrite(string namespace, address user) constant returns (bool) {
		return contexts.owners[namespace] == user;
	}

	function register(string namespace, string project, string version, string protocol, string source, string checksum) {
		if(bytes(getSource(namespace,project,version, protocol)).length != 0 || !canWrite(namespace,currentUser())) throw;

		registerProject(namespace,project);

		contexts.spaces[namespace].projects[project].packages[version].source[protocol] = source;
		if(bytes(contexts.spaces[namespace].projects[project].packages[version].checksum).length == 0) {
			contexts.spaces[namespace].projects[project].packages[version].checksum = checksum;
		}else if(stringsEqual(contexts.spaces[namespace].projects[project].packages[version].checksum, checksum) == false) throw;

		contexts.spaces[namespace].projects[project].versions[contexts.spaces[namespace].projects[project].nbVersions] = version;
		contexts.spaces[namespace].projects[project].nbVersions++;
	}

	function createNamespace(string namespace, address owner) onlyowner nameSpaceOwner(namespace,0) {
		contexts.owners[namespace] = owner;
		contexts.ids[contexts.length] = namespace;
		contexts.length++;
	}

	function registerProject(string namespace, string project) private {
		if(contexts.spaces[namespace].projects[project].nbVersions == 0) {
			contexts.spaces[namespace].names[contexts.spaces[namespace].nbProjects] = project;
			contexts.spaces[namespace].nbProjects++;
		}
	}

	function changeOwner(string namespace, address newOwner) nameSpaceOwner(namespace,currentUser()){
		contexts.owners[namespace] = newOwner;
	}

	function stringsEqual(string storage _a, string memory _b) internal returns (bool) {
		bytes storage a = bytes(_a);
		bytes memory b = bytes(_b);
		if (a.length != b.length)
			return false;
		// @todo unroll this loop
		for (uint i = 0; i < a.length; i ++)
			if (a[i] != b[i])
				return false;
		return true;
	}
}

contract abstract {}

contract owned is abstract {
  address owner;

  modifier onlyowner() {
    if (currentUser()==owner) _
  }

  function currentUser() returns (address) {
		return msg.sender;
	}
}

contract mortal is abstract, owned {
  function kill() {
    if (msg.sender == owner) suicide(owner);
  }
}

contract Launcheth is mortal {

	struct project {
		uint nbVersions;
		mapping(uint => string) versions;
		mapping(string => repository) packages;
	}

	struct repository {
		mapping (string => string) source;
		string checksum;
	}

	struct namespace{
		uint nbProjects;
		mapping(uint => string) names;
		mapping(string => project) projects;
	}

	struct namespaces {
		uint length;
		mapping(uint => string) ids;
		mapping(string => address) owners;
		mapping(string => namespace) spaces;
	}

	namespaces contexts;

	modifier nameSpaceOwner(string namespace, address owner) {
		if(contexts.owners[namespace] != owner) throw;
		_;
	}

    function getNbNamespaces() constant returns (uint){
        return contexts.length;
    }

    function getNamespace(uint id) constant returns (string) {
        return contexts.ids[id];
    }

    function getNbProjects(string namespace) constant returns (uint){
        return contexts.spaces[namespace].nbProjects;
    }

    function getProject(string namespace, uint id) constant returns (string) {
        return contexts.spaces[namespace].names[id];
    }

    function getNbVersions(string namespace, string project) constant returns (uint) {
        return contexts.spaces[namespace].projects[project].nbVersions;
    }

    function getVersion(string namespace, string project, uint id) constant returns(string) {
        return contexts.spaces[namespace].projects[project].versions[id];
    }

    function getOwner(string namespace) constant returns(address) {
        return contexts.owners[namespace];
    }

	function LegalContractManager() {
        owner = currentUser();
	}

	function getSource(string namespace, string project, string version, string protocol) constant returns (string) {
		return contexts.spaces[namespace].projects[project].packages[version].source[protocol];
	}

	function getChecksum(string namespace, string project, string version) constant returns (string) {
		return contexts.spaces[namespace].projects[project].packages[version].checksum;
	}

	function canWrite(string namespace, address user) constant returns (bool) {
		return contexts.owners[namespace] == user;
	}

	function register(string namespace, string project, string version, string protocol, string source, string checksum) {
		if(bytes(getSource(namespace,project,version, protocol)).length != 0 || !canWrite(namespace,currentUser())) throw;

		registerProject(namespace,project);

		contexts.spaces[namespace].projects[project].packages[version].source[protocol] = source;
		if(bytes(contexts.spaces[namespace].projects[project].packages[version].checksum).length == 0) {
			contexts.spaces[namespace].projects[project].packages[version].checksum = checksum;
		}else if(stringsEqual(contexts.spaces[namespace].projects[project].packages[version].checksum, checksum) == false) throw;

		contexts.spaces[namespace].projects[project].versions[contexts.spaces[namespace].projects[project].nbVersions] = version;
		contexts.spaces[namespace].projects[project].nbVersions++;
	}

	function createNamespace(string namespace, address owner) onlyowner nameSpaceOwner(namespace,0) {
		contexts.owners[namespace] = owner;
		contexts.ids[contexts.length] = namespace;
		contexts.length++;
	}

	function registerProject(string namespace, string project) private {
		if(contexts.spaces[namespace].projects[project].nbVersions == 0) {
			contexts.spaces[namespace].names[contexts.spaces[namespace].nbProjects] = project;
			contexts.spaces[namespace].nbProjects++;
		}
	}

	function changeOwner(string namespace, address newOwner) nameSpaceOwner(namespace,currentUser()){
		contexts.owners[namespace] = newOwner;
	}

	function stringsEqual(string storage _a, string memory _b) internal returns (bool) {
		bytes storage a = bytes(_a);
		bytes memory b = bytes(_b);
		if (a.length != b.length)
			return false;
		// @todo unroll this loop
		for (uint i = 0; i < a.length; i ++)
			if (a[i] != b[i])
				return false;
		return true;
	}
}


Rebuilt TicTacToeLockedState.sol

Rebuilt TicTacToeLockedState.sol

import "LockedStateWithFunds.sol";

contract TicTacToeLockedState is LockedStateWithFunds {

    // byte mappings for state
    // 0-19 address1
    // 20-39 address2
    // 40-71 send1
    // 72-104 send2

    function parseState(bytes state)
        constant returns (address address1, address address2, uint send1, uint send2)
    {
        uint i;
        uint160 uintAddress1 = 0;
        uint160 uintAddress2 = 0;

        for (i = 0; i < 20; i++) {
            uintAddress1 |= uint8(state[i]) * uint160(2**(i*8));
        }
        address1 = uintAddress1;

        for (i = 0; i < 20; i++) {
            uintAddress2 |= uint8(state[i+20]) * uint160(2**(i*8));
        }
        address2 = uintAddress2;

        for (i = 0; i < 32; i++) {
            send1 |= uint8(state[i+40]) * 2**(i*8);
        }

        for (i = 0; i < 32; i++) {
            send2 |= uint8(state[i+72]) * 2**(i*8);
        }
    }

    function checkState(bytes state) constant returns (bool) {
        address address1;
        address address2;
        uint send1;
        uint send2;

        (address1, address2, send1, send2) = parseState(state);
        return send1 + send2 == getBalance(address1) + getBalance(address2);
    }

    function broadcastState(bytes state) external onlyOwner returns (bool) {
        if (!checkState(state)) {
            return false;
        }

        address address1;
        address address2;
        uint send1;
        uint send2;

        (address1, address2, send1, send2) = parseState(state);

        if (!address1.send(send1)) {
            throw;
        }

        if (!address2.send(send2)) {
            throw;
        }

        return true;
    }
}

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


Two phase transfers

Two phase transfers

pragma solidity ^0.4.11;

import 'zeppelin-solidity/contracts/token/ERC20.sol';

/**
 * @title TwoPhaseTransfers
 * @dev The TwoPhaseTransfers add an extra security for transfer processing introducing an extra confirmation step.
 */
contract TwoPhaseTransfers {
    bool checkProposers;
    bool checkValidators;
    mapping(address => bool) proposers;
    mapping(address => bool) validators;

    uint idGenerator;

    struct TransferProposal {
        ERC20 token;
        address to;
        uint value;
    }

    mapping(uint => TransferProposal) transferProposals;

    event TransferProposed(address indexed token, address indexed to, uint indexed value);
    event TransferAuthorized(address indexed token, address indexed to, uint indexed value);

    modifier onlyProposer() {
        require(!checkProposers || proposers[msg.sender]);
        _;
    }

    modifier onlyValidator() {
        require(!checkValidators || validators[msg.sender]);
        _;
    }

    function TwoPhaseTransfers(address[] _proposers, address[] _validators) {
        if (_proposers.length > 0) {
            checkProposers = true;
            for(uint i=0; i<_proposers.length; i++) {
                proposers[_proposers[i]] = true;
            }
        }
    }

    function proposeTransfer(ERC20 token, address to, uint value) onlyProposer returns(uint) {
        uint id = idGenerator++;
        transferProposals[id] = TransferProposal(token, to, value);
        return id;
    }

    function confirmTransfer(uint transferId) {
        TransferProposal proposal = transferProposals[transferId];
        require(ERC20(proposal.token).transfer(proposal.to, proposal.value));
        TransferAuthorized(proposal.token, proposal.to, proposal.value);
    }

}

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


Little bug fixed

Little bug fixed

import './Proposal.sol';
import 'lib/AddressList.sol';
import 'common/Mortal.sol';
import 'token/Token.sol';

contract CashFlow is Owned {
    Token public credits;
    Token public shares;

    // Proposal list
    Proposal[] public proposals;

    // Events
    event Created(address indexed proposal);
    event Updated(address indexed proposal);
    event Closed(address indexed proposal);

    // Constructor
    function CashFlow(address _credits, address _shares) {
        credits = Token(_credits);
        shares  = Token(_shares);
    }

    /**
     * @dev Nominal price of one share in credits
     * @return amount of credits in one share
     */
    function nominalSharePrice() constant returns (uint)
    { return credits.getBalance() / shares.totalSupply(); }

    /**
     * @dev Initial new proposal
     * @param _target is a destination address
     * @param _total is a credits goal
     * @param _description is a short description of new proposal
     * @return proposal address
     */
    function init(address _target, uint _total, string _description) returns (Proposal) {
        var proposal = new Proposal(_target, _total, _description);
        proposals.push(proposal);
        Created(proposal);
        return proposal;
    }

    /**
     * @dev Vote for the proposal
     * @param _proposal is an proposal instance
     * @param _value is a count of given shares
     */
    function fund(Proposal _proposal, uint _value) {
        if (_proposal.closed() == 0 ||
            shares.getBalance(msg.sender) < _value) throw;

        var share_price = nominalSharePrice();
        var summary     = _proposal.summaryShares() + _value;

        bool overload = summary * share_price > _proposal.targetValue();
        if (overload) {
            var correction = summary * share_price - _proposal.targetValue();
            _value -= correction / share_price;
        }

        // Transfer shares
        shares.transferFrom(msg.sender, this, _value);

        // Append new funder
        _proposal.appendFunder(msg.sender);
        _proposal.setSharesOf(msg.sender, _proposal.sharesOf(msg.sender) + _value);
        _proposal.setSummaryShares(_proposal.summaryShares() + _value);

        // Is proposal done?
        if (_proposal.summaryShares() * share_price >= _proposal.targetValue()) {
            // Transfer credits
            if (!credits.transfer(_proposal.destination(),
                                  _proposal.targetValue())) throw;

            // Close proposal
            _proposal.close();
            _proposal.setSharePrice(share_price);
            Closed(_proposal);
        } else {
            Updated(_proposal);
        }
    }

    /**
     * @dev Refund shares from proposal
     * @param _proposal is a proposal instance
     * @param _value is how amount shares will be refunded
     * @notice target proposal should be open
     */
    function refund(Proposal _proposal, uint _value) {
        uint sender_balance = _proposal.sharesOf(msg.sender);
        uint refund_shares  = 0;

        if (_proposal.closed() > 0) {
            // CLOSED proposal
            var free_shares  = sender_balance
                             * _proposal.backValue()
                             / _proposal.targetValue();

            refund_shares = free_shares > sender_balance
                          ? sender_balance : free_shares;
            refund_shares = refund_shares > _value
                          ? _value : refund_shares;

            _proposal.setRefunSharesOf(msg.sender, refund_shares);
        } else {
            // OPEN proposal
            refund_shares  = sender_balance > _value ? _value : sender_balance;

            _proposal.setSharesOf(msg.sender, sender_balance - refund_shares);
            _proposal.setSummaryShares(_proposal.summaryShares() - refund_shares);
        }

        if (!shares.transfer(msg.sender, refund_shares)) throw;
        Updated(_proposal);
    }

    /**
     * @dev Request for release shares by sending
     * @param _proposal is a proposal instance
     * @param _value is a value of returned credits
     */
    function fundback(Proposal _proposal, uint _value) {
        // Try to take a credits
        if (!credits.transferFrom(msg.sender, this, _value)) throw;

        // Update back value
        _proposal.setBackValue(_proposal.backValue() + _value);
        Updated(_proposal);
    }
}

import './Proposal.sol';
import 'lib/AddressList.sol';
import 'common/Mortal.sol';
import 'token/Token.sol';

contract CashFlow is Owned {
    Token public credits;
    Token public shares;

    // Proposal list
    Proposal[] public proposals;

    // Events
    event Created(address indexed proposal);
    event Updated(address indexed proposal);
    event Closed(address indexed proposal);

    // Constructor
    function CashFlow(address _credits, address _shares) {
        credits = Token(_credits);
        shares  = Token(_shares);
    }

    /**
     * @dev Nominal price of one share in credits
     * @return amount of credits in one share
     */
    function nominalSharePrice() constant returns (uint)
    { return credits.getBalance() / shares.totalSupply(); }

    /**
     * @dev Initial new proposal
     * @param _target is a destination address
     * @param _total is a credits goal
     * @param _description is a short description of new proposal
     * @return proposal address
     */
    function init(address _target, uint _total, string _description) returns (Proposal) {
        var proposal = new Proposal(_target, _total, _description);
        proposals.push(proposal);
        Created(proposal);
        return proposal;
    }

    /**
     * @dev Vote for the proposal
     * @param _proposal is an proposal instance
     * @param _value is a count of given shares
     */
    function fund(Proposal _proposal, uint _value) {
        if (_proposal.closed() == 0 ||
            shares.getBalance(msg.sender) < _value) throw;

        var share_price = nominalSharePrice();
        var summary     = _proposal.summaryShares() + _value;

        bool overload = summary * share_price > _proposal.targetValue();
        if (overload) {
            var correction = summary * share_price - _proposal.targetValue();
            _value -= correction / share_price;
        }

        // Transfer shares
        shares.transferFrom(msg.sender, this, _value);

        // Append new funder
        _proposal.appendFunder(msg.sender);
        _proposal.setSharesOf(msg.sender, _proposal.sharesOf(msg.sender) + _value);
        _proposal.setSummaryShares(_proposal.summaryShares() + _value);

        // Is proposal done?
        if (_proposal.summaryShares() * share_price >= _proposal.targetValue()) {
            // Transfer credits
            if (!credits.transfer(_proposal.destination(),
                                  _proposal.targetValue())) throw;

            // Close proposal
            _proposal.close();
            _proposal.setSharePrice(share_price);
            Closed(_proposal);
        } else {
            Updated(_proposal);
        }
    }

    /**
     * @dev Refund shares from proposal
     * @param _proposal is a proposal instance
     * @param _value is how amount shares will be refunded
     * @notice target proposal should be open
     */
    function refund(Proposal _proposal, uint _value) {
        uint sender_balance = _proposal.sharesOf(msg.sender);
        uint refund_shares  = 0;

        if (_proposal.closed() == 0) {
            // CLOSED proposal
            var free_shares  = sender_balance
                             * _proposal.backValue()
                             / _proposal.targetValue();

            refund_shares = free_shares > sender_balance
                          ? sender_balance : free_shares;
            refund_shares = refund_shares > _value
                          ? _value : refund_shares;

            _proposal.setRefunSharesOf(msg.sender, refund_shares);
        } else {
            // OPEN proposal
            refund_shares  = sender_balance > _value ? _value : sender_balance;

            _proposal.setSharesOf(msg.sender, sender_balance - refund_shares);
            _proposal.setSummaryShares(_proposal.summaryShares() - refund_shares);
        }

        if (!shares.transfer(msg.sender, refund_shares)) throw;
        Updated(_proposal);
    }

    /**
     * @dev Request for release shares by sending
     * @param _proposal is a proposal instance
     * @param _value is a value of returned credits
     */
    function fundback(Proposal _proposal, uint _value) {
        // Try to take a credits
        if (!credits.transferFrom(msg.sender, this, _value)) throw;

        // Update back value
        _proposal.setBackValue(_proposal.backValue() + _value);
        Updated(_proposal);
    }
}


bug in greeter

bug in greeter

import "./mortal.sol";

contract greeter is mortal {
    /* define variable greeting of the type string */
    string greeting;

    /* this runs when the contract is executed */
    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    /* main function */
    // function greet() constant returns (string greeting) { // bug: greeting comes up empty
    function greet() constant returns (string theGreeting) {
        return greeting;
    }

    /* constant reply */
    function echo(string value1, string value2) constant returns (string, string, int16) {
        return (value1, value2, 2);
    }

    /* update greeting */
    event Updated (string newGreeting);

    function update(string value) returns (bool success) {
        greeting = value;
        Updated(greeting);
        return true;
    }
}

import "./mortal.sol";

contract greeter is mortal {
    /* define variable greeting of the type string */
    string greeting;

    /* this runs when the contract is executed */
    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    /* main function */
    function greet() constant returns (string greeting) {
        return greeting;
    }

    /* constant reply */
    function echo(string value1, string value2) constant returns (string, string, int16) {
        return (value1, value2, 2);
    }

    /* update greeting */
    event Updated (string newGreeting);

    function update(string value) returns (bool success) {
        greeting = value;
        Updated(greeting);
        return true;
    }
}


Commented LockedStateWithFunds.sol

Commented LockedStateWithFunds.sol

import "LockedState.sol";

/**
 * LockedStateWithFunds
 *
 * LockedState which implements the tracking of funds sent to it.
 */
contract LockedStateWithFunds is LockedState {

    // Event triggered whenever funds have been added
    event FundsAdded(address from, address to, uint amount);

    mapping (address => uint) balances;

    /**
     * Gets the balance of the address passed in.
     *
     * toCheck: the address to check the balance for
     * returns: the balance
     */
    function getBalance(address toCheck) constant returns (uint) {
        return balances[toCheck];
    }

	// Adds funds to the recipient account
    function addFunds(address recipient) {
        balances[recipient] += msg.value;
    }

	// By default, funds are added to the sender's account
    function () {
        addFunds(msg.sender);
    }
}

import "LockedState.sol";

/**
 * LockedStateWithFunds
 *
 * LockedState which implements the tracking of funds sent to it.
 */
contract LockedStateWithFunds is LockedState {

    // Event triggered whenever funds have been added
    event FundsAdded(address from, address to, uint amount);

    mapping (address => uint) balances;

    /**
     * Gets the balance of the address passed in.
     *
     * toCheck: the address to check the balance for
     * returns: the balance
     */
    function getBalance(address toCheck) constant returns (uint) {
        return balances[toCheck];
    }

    function addFunds(address recipient) {
        balances[recipient] += msg.value;
    }

    function () {
        addFunds(msg.sender);
    }
}