commit de status

commit de status

// Pokemon create template: 1,500,40,"at1",1,"at2",500
// owner "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"

contract owned {
    address public owner;
    address public market;

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

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

    modifier Market {
        if (msg.sender != market || msg.sender != owner) throw;
        _
    }

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

    function updateMarket(address newMarket) onlyOwner {
        market = newMarket;
    }
}

contract IssuePokemon is owned {

    uint256 public totalPokemonSupply;
    address public marketAddress;

    Pokemon[] public pokemons;
    PokemonMaster[] public pokeMasters;

    mapping (uint256 => address) public pokemonToMaster;
    mapping (address => uint256) public pokeOwnerIndex;
    mapping (address => uint256) public totalPokemonsFromMaster;

    struct Pokemon {
        uint pokeNumber;
        string pokeName;
        string pokeType;
        uint pokeCP;
        uint pokeHP;
        //string pokeAttack;
        //uint pokeAttackPower;
        //string pokeSpecial;
        //uint pokeSpecialPower;
        bytes32 pokemonHash;
        address pokeOwner;
    }

    struct PokemonMaster {
        address pokeMaster;
        uint[] pokemons;
    }

    string[][] public pokemonNameTypes = [["Pokemon 0", "invalid"], ["Bulbassauro", "Grass/Poison"], ["Charmander", "Fire"], ["Squirtle","Water"], ["Pikachu","Eletric"]]; // nÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂ£o aceita bytes

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address from, address to, uint256 value);
    event CreatePokemon(uint id, string name, uint cp, uint hp );
    event UpdateMasterPokemons(address owner, uint total);
    event Log1(uint number);
    event Log2(string message);

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function IssuePokemon() {
        owner = msg.sender;
        newPokemonMaster(owner);                            // Todos pokemons serao criados para este owner
        newPokemon(0,0,0);                                  // Pokemon Índice 0
        totalPokemonSupply-=1;                              // Ajusta o total de pokemons porque o primeiro é fake

        /* Criacao de pokemons iniciais */
        newPokemon(3,500,40);
        newPokemon(1,535,70);
        newPokemon(4,546,80);
        newPokemon(2,557,90);

    }

    //function newPokemon(uint pokemonNumber, uint cp, uint hp, string attack, uint attackPower, string special, uint specialPower ) returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
    function newPokemon(uint pokemonNumber, uint cp, uint hp )  returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
        address owner = msg.sender;
        uint pokemonID = pokemons.length++;
        Pokemon p = pokemons[pokemonID];
        p.pokeNumber = pokemonNumber;
        p.pokeName = pokemonNameTypes[pokemonNumber][0];
        p.pokeType = pokemonNameTypes[pokemonNumber][1];
        p.pokeCP = cp;
        p.pokeHP = hp;
        //p.pokeAttack = attack;
        //p.pokeAttackPower = attackPower;
        //p.pokeSpecial = special;
        //p.pokeSpecialPower = specialPower;

        //p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP, p.pokeAttack, p.pokeAttackPower, p.pokeSpecial, p.pokeSpecialPower);
        p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP);
        p.pokeOwner = owner;

        pokemonToMaster[pokemonID] = owner;
        addPokemonToMaster(owner, pokemonID);

        totalPokemonSupply += 1;
        CreatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP);
        return true;
    }

    function newPokemonMaster(address pokemonMaster)  returns (bool success) {
        uint ownerID = pokeMasters.length++;
        PokemonMaster o = pokeMasters[ownerID];
        o.pokeMaster = pokemonMaster;
        pokeOwnerIndex[pokemonMaster] = ownerID;
        return true;
    }

    function transferPokemon(address _from, address _to, uint256 _pokemonID)   returns (uint pokemonID, address from, address to) {
        Pokemon p = pokemons[_pokemonID];
        if (p.pokeOwner != _from) throw;
        if (pokeOwnerIndex[_to] == 0 && _to != pokemonToMaster[0] ) newPokemonMaster(_to);
        // Construir controle de acesso somente para o owner
        p.pokeOwner = _to;
        pokemonToMaster[_pokemonID] = _to;
        delPokemonFromMaster(_from, _pokemonID);
        addPokemonToMaster(_to, _pokemonID);
        Transfer(_from, _to, _pokemonID);
        return (_pokemonID, _from, _to);
    }

    function addPokemonToMaster(address _pokemonOwner, uint256 _pokemonID)  returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) {
        uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;

        // o.pokemons.push(_pokemonID);
        // usando .push ele adiciona 0,_pokemonID

        // Ao invés de simplesmente adicionar um pokemon ao final da lista,
        // verifica se há slot zerado no array, senao adiciona ao final
        bool slot;
        for (uint i=0; i < pokeList.length; i++){
            if (pokeList[i] == 0){
                slot = true;
                break;
            }
        }
        if (slot == true){
            o.pokemons[i] = _pokemonID;
        } else {
            uint j = pokeList.length++;
            o.pokemons[j] = _pokemonID;
        }

        qtdePokemons(_pokemonOwner);
        UpdateMasterPokemons(_pokemonOwner, o.pokemons.length);
        return (_pokemonOwner, o.pokemons, o.pokemons.length);
    }

    function delPokemonFromMaster(address _pokemonOwner, uint256 _pokemonID)  returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) {
        uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;

        for (uint i=0; i < pokeList.length; i++){
            if (pokeList[i] == _pokemonID){
                delete pokeList[i];
            }
        }

        // http://ethereum.stackexchange.com/questions/3373/how-to-clear-large-arrays-without-blowing-the-gas-limit
        o.pokemons=pokeList; // Se usar delete, usa a propria pokeList

        qtdePokemons(_pokemonOwner);
        UpdateMasterPokemons(_pokemonOwner, o.pokemons.length);
        return (_pokemonOwner, o.pokemons, o.pokemons.length);
    }

    function listPokemons( address _pokeOwner )  returns (address, uint[]){
        uint ownerID = pokeOwnerIndex[_pokeOwner];
        PokemonMaster o = pokeMasters[ownerID];
        return ( _pokeOwner, o.pokemons );
    }

    function qtdePokemons( address _pokeOwner)  returns (uint qtde){
        uint ownerID = pokeOwnerIndex[_pokeOwner];
        PokemonMaster o = pokeMasters[ownerID];
        uint[] pokeList = o.pokemons;
        uint count = 0;
        for (uint i=0; i < pokeList.length; i++){
            if ( pokeList[i] > 0 ){
                count++;
            }
        }
        totalPokemonsFromMaster[_pokeOwner] = count;
        return count;
    }

    /* Se tentarem enviar ether para o end desse contrato, ele rejeita */
    function () {
        throw;
    }
}

// Pokemon create template: 1,500,40,"at1",1,"at2",500
// owner 0xca35b7d915458ef540ade6068dfe2f44e8fa733c

contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }

contract IssuePokemon {
    /* Public variables of the token */

    string public standard = 'Pokemon 0.1';
    string public name = 'IssuePokemon';
    uint256 public totalSupply;

    Pokemon[] public pokemons;
    PokemonOwner[] public pokeOwners;

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

    struct Pokemon {
        uint pokeNumber;
        string pokeName;
        string pokeType;
        uint pokeCP;
        uint pokeHP;
        //string pokeAttack;
        //uint pokeAttackPower;
        //string pokeSpecial;
        //uint pokeSpecialPower;
        bytes32 pokemonHash;
        address pokeOwner;
    }

    struct PokemonOwner {
        address pokeOwner;
        uint[] pokemons;
    }

    string[][] public pokemonNameTypes = [["Pokemon 0", "invalid"], ["Bulbassauro", "Grass/Poison"], ["Charmander", "Fire"], ["Squirtle","Water"], ["Pikachu","Eletric"]]; // nÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂ£o aceita bytes

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address indexed from, address indexed to, uint256 value);
    event CreatePokemon(uint id, string name, uint cp, uint hp );
    event UpdateMasterPokemons(string message);
    event Log1(uint number);
	event Log2(string message);

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function IssuePokemon( ) {
        newPokemonOwner(msg.sender); 						// Todos pokemons serao criados para este owner
        newPokemon(0,0,0); 									// Pokemon índice 0

		/* Criacao de pokemons iniciais */
		//newPokemon(3,500,40);
		//newPokemon(1,535,70);
		//newPokemon(0,546,80);
		//newPokemon(2,557,90);

        //balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
        //totalSupply = initialSupply;                        // Update total supply
        //msg.sender.send(msg.value);                         // Send back any ether sent accidentally
    }

	//function newPokemon(uint pokemonNumber, uint cp, uint hp, string attack, uint attackPower, string special, uint specialPower ) returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
    function newPokemon(uint pokemonNumber, uint cp, uint hp ) returns (bool success) { // cp e hp fornecidos por https://api.random.org/json-rpc/1/basic
        address owner = msg.sender;
        uint pokemonID = pokemons.length++;
        Pokemon p = pokemons[pokemonID];
        p.pokeNumber = pokemonNumber;
        p.pokeName = pokemonNameTypes[pokemonNumber][0];
        p.pokeType = pokemonNameTypes[pokemonNumber][1];
        p.pokeCP = cp;
        p.pokeHP = hp;
        //p.pokeAttack = attack;
        //p.pokeAttackPower = attackPower;
        //p.pokeSpecial = special;
        //p.pokeSpecialPower = specialPower;
        p.pokeOwner = owner;
        pokemonMaster[pokemonID] = owner;

        //p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP, p.pokeAttack, p.pokeAttackPower, p.pokeSpecial, p.pokeSpecialPower);
		p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP);

        updateMasterPokemons(owner, pokemonID, true);

        totalSupply += 1;
        CreatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP);
        return true;
    }

    function newPokemonOwner(address pokeOwner) returns (bool success) {
        uint ownerID = pokeOwners.length++;
        PokemonOwner o = pokeOwners[ownerID];
        o.pokeOwner = pokeOwner;
        pokeOwnerIndex[pokeOwner] = ownerID;
        return true;
    }

    /* Send coins */
    function transfer(address _to, uint256 _pokemonID) {
        Pokemon p = pokemons[_pokemonID];
        if (p.pokeOwner != msg.sender) throw; // Checa se quem estÃ¡ solicitando a transferde proprietÃ¡rio do pokemon
        if (pokeOwnerIndex[_to] == 0 && _to != pokemonMaster[0] ) newPokemonOwner(_to);
        p.pokeOwner = _to;
        pokemonMaster[_pokemonID] = _to;
        updateMasterPokemons(msg.sender, _pokemonID, false);
        updateMasterPokemons(_to, _pokemonID, true);
        Transfer(msg.sender, _to, _pokemonID);                   // Avisa que a transferÃªncia de pokemon ocorreu
    }

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

    /* Approve and then comunicate the approved contract in a single tx */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
        tokenRecipient spender = tokenRecipient(_spender);
        if (approve(_spender, _value)) {
            spender.receiveApproval(msg.sender, _value, this, _extraData);
            return true;
        }
    }

    /* A contract attempts to get the coins */
    function transferFrom(address _from, address _to, uint256 _pokemonID) returns (bool success) {
        Pokemon p = pokemons[_pokemonID];
        if (p.pokeOwner != _from) throw;
        // Construir controle de acesso somente para o owner
        p.pokeOwner = _to;
        pokemonMaster[_pokemonID] = _to;
        updateMasterPokemons(_from, _pokemonID, false);
        updateMasterPokemons(_to, _pokemonID, true);
        Transfer(_from, _to, _pokemonID);
        return true;
    }

    function updateMasterPokemons(address _pokemonOwner, uint256 _pokemonID, bool _add) returns (bool success) {
		uint ownerID = pokeOwnerIndex[_pokemonOwner];
        PokemonOwner o = pokeOwners[ownerID];
        uint[] pokeList = o.pokemons;
		uint newID = pokeList.length++;

        if (_add) {
			o.pokemons.push(_pokemonID);
			Log1(pokeList[newID]);
        } else {
            for (uint i=0; i < newID; i++){
				if (uint(pokeList[i]) == _pokemonID){
					delete pokeList[i];
					Log2("delete item");
					Log1(_pokemonID);
            	}
        	}
        }
        UpdateMasterPokemons("ok");
        return true;
    }

    /* This unnamed function is called whenever someone tries to send ether to it */
    function () {
        throw;     // Prevents accidental sending of ether
    }
}


checking the size of proof for files

checking the size of proof for files

pragma solidity ^0.4.16;

contract Onchain {

   uint debug;

    struct Roots {
        bytes32 code;
        bytes32 stack;
        bytes32 mem;
        bytes32 globals;
        bytes32 calltable;
        bytes32 calltypes;
        bytes32 call_stack;
        bytes32 input_size;
        bytes32 input_name;
        bytes32 input_data;
    }

    struct VM {
        uint pc;
        uint stack_ptr;
        uint call_ptr;
        uint memsize;
    }

    struct Machine {
        bytes32 vm;
        bytes32 op;
        uint reg1;
        uint reg2;
        uint reg3;
        uint ireg;
    }

    VM vm;
    Roots vm_r;
    Machine m;
    bytes32[] proof;
    bytes32[] proof2;

    bytes32 state;

    function setVM(bytes32[10] roots, uint[4] pointers) internal {
        vm_r.code = roots[0];
        vm_r.stack = roots[1];
        vm_r.mem = roots[2];
        vm_r.call_stack = roots[3];
        vm_r.globals = roots[4];
        vm_r.calltable = roots[5];
        vm_r.calltypes = roots[6];
        vm_r.input_size = roots[7];
        vm_r.input_name = roots[8];
        vm_r.input_data = roots[9];

        vm.pc = pointers[0];
        vm.stack_ptr = pointers[1];
        vm.call_ptr = pointers[2];
        vm.memsize = pointers[3];
    }

    function hashVM() internal view returns (bytes32) {
        bytes32[] memory arr = new bytes32[](14);
        arr[0] = vm_r.code;
        arr[1] = vm_r.mem;
        arr[2] = vm_r.stack;
        arr[3] = vm_r.globals;
        arr[4] = vm_r.call_stack;
        arr[5] = vm_r.calltable;
        arr[6] = vm_r.calltypes;
        arr[7] = vm_r.input_size;
        arr[8] = vm_r.input_name;
        arr[9] = vm_r.input_data;
        arr[10] = bytes32(vm.pc);
        arr[11] = bytes32(vm.stack_ptr);
        arr[12] = bytes32(vm.call_ptr);
        arr[13] = bytes32(vm.memsize);
        return keccak256(arr);
    }

    function setMachine(
        bytes32 vm_,
        bytes32 op,
        uint reg1,
        uint reg2,
        uint reg3,
        uint ireg) internal {
        m.vm = vm_;
        m.op = op;
        m.reg1 = reg1;
        m.reg2 = reg2;
        m.reg3 = reg3;
        m.ireg = ireg;
    }

    function hashMachine() internal view returns (bytes32) {
        return keccak256(m.vm, m.op, m.reg1, m.reg2, m.reg3, m.ireg);
    }

    function getLeaf(uint loc) internal view returns (uint) {
        require(proof.length >= 2);
        if (loc%2 == 0) return uint(proof[0]);
        else return uint(proof[1]);
    }

    function setLeaf(uint loc, uint v) internal {
        require(proof.length >= 2);
        if (loc%2 == 0) proof[0] = bytes32(v);
        else proof[1] = bytes32(v);
    }

    function getRoot(uint loc) internal view returns (bytes32) {
        require(proof.length >= 2);
        bytes32 res = keccak256(proof[0], proof[1]);
        for (uint i = 2; i < proof.length; i++) {
            loc = loc/2;
            if (loc%2 == 0) res = keccak256(res, proof[i]);
            else res = keccak256(proof[i], res);
        }
        require(loc < 2);
        return res;
    }

    function getLeaf2(uint loc) internal view returns (uint) {
        require(proof2.length >= 2);
        if (loc%2 == 0) return uint(proof2[0]);
        else return uint(proof2[1]);
    }

    function setLeaf2(uint loc, uint v) internal {
        require(proof2.length >= 2);
        if (loc%2 == 0) proof2[0] = bytes32(v);
        else proof2[1] = bytes32(v);
    }

    function getRoot2(uint loc) internal view returns (bytes32) {
        require(proof2.length >= 2);
        bytes32 res = keccak256(proof2[0], proof2[1]);
        for (uint i = 2; i < proof2.length; i++) {
            loc = loc/2;
            if (loc%2 == 0) res = keccak256(res, proof2[i]);
            else res = keccak256(proof2[i], res);
        }
        require(loc < 2);
        return res;
    }

    function getCode(uint loc) internal view returns (bytes32) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.code);
        return bytes32(getLeaf(loc));
    }

    function getStack(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.stack);
        return getLeaf(loc);
    }

    function getCallStack(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.call_stack);
        return getLeaf(loc);
    }

    function getCallTable(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltable);
        return getLeaf(loc);
    }

    function getCallTypes(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltypes);
        return getLeaf(loc);
    }

    function getMemory(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.mem);
        return getLeaf(loc);
    }

    function getGlobal(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.globals);
        return getLeaf(loc);
    }

    uint INPUT_FILES = 10;

    function getInputSize(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_size && proof.length == 10);
        return getLeaf(loc);
    }

    function getInputName(uint loc, uint loc2) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_name && proof.length == 10);
        require(getRoot2(loc2) == bytes32(getLeaf2(loc)));
        return getLeaf2(loc2);
    }

    function setInputName(uint loc, uint loc2, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_name && proof.length == 10);
        require(getRoot2(loc2) == bytes32(getLeaf2(loc)));
        setLeaf2(loc2, v);
        setLeaf(loc, getLeaf2(loc));
        vm_r.input_name = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setInputSize(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_size && proof.length == 10);
        setLeaf(loc, v);
        vm_r.input_size = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setInputFile(uint loc, bytes32 v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data && proof.length == 10);
        setLeaf(loc, uint(v));
        vm_r.input_data = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setNthByte(uint a, uint n, uint8 bte) pure internal returns (uint) {
       uint mask = uint(-1)*(2**(8*(32-n))) | uint(-1)/(2**(8*(n+1)));
       return (a&mask) | (2**(8*(32-n)))*uint256(bte);
    }

    function setInputData(uint loc, uint loc2, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data && proof.length == 10);
        require(getRoot2(loc2/16) == bytes32(getLeaf2(loc)));
        uint leaf = getLeaf2(loc2/16);
        uint idx = loc2 % 16;

        uint nleaf = setNthByte(leaf, idx, uint8(v));

        setLeaf2(loc2/16, nleaf);
        setLeaf(loc, getLeaf2(loc));
        vm_r.input_data = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function getInputData(uint loc, uint loc2) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data && proof.length == 10);
        require(getRoot2(loc2/16) == bytes32(getLeaf2(loc)));
        uint leaf = getLeaf2(loc2/16);
        uint idx = loc2 % 16;
        return (leaf / 2**(idx*8)) & 0xff;
    }

    function createInputData(uint loc, uint sz) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data && proof.length == 10);
        sz = sz/16;
        bytes32 zero = keccak256(bytes32(0), bytes32(0));
        while (sz > 1) {
            sz = sz/2;
            zero = keccak256(zero, zero);
        }
        setLeaf(loc, uint(zero));
        vm_r.input_data = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallStack(uint loc, uint v) internal  {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.call_stack);
        setLeaf(loc, v);
        vm_r.call_stack = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setMemory(uint loc, uint v) internal  {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.mem);
        setLeaf(loc, v);
        vm_r.mem = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setStack(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.stack);
        setLeaf(loc, v);
        vm_r.stack = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setGlobal(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.globals);
        setLeaf(loc, v);
        vm_r.globals = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallTable(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltable);
        setLeaf(loc, v);
        vm_r.calltable = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallType(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltypes);
        setLeaf(loc, v);
        vm_r.calltypes = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function getPC() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.pc;
    }

    function getMemsize() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.memsize;
    }

    function getStackPtr() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.stack_ptr;
    }

    function getCallPtr() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.call_ptr;
    }

    function getReg1() internal view returns (uint) {
        require(hashMachine() == state);
        return m.reg1;
    }

    function getReg2() internal view returns (uint) {
        require(hashMachine() == state);
        return m.reg2;
    }

    function getReg3() internal view returns (uint) {
        require(hashMachine() == state);
        return m.reg3;
    }

    function getIreg() internal view returns (uint) {
        require(hashMachine() == state);
        return m.ireg;
    }

    function getOp() internal view returns (bytes32) {
        require(hashMachine() == state);
        return m.op;
    }

    function setMemsize(uint v) internal {
        vm.memsize = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setIreg(uint v) internal  {
        m.ireg = v;
        state = hashMachine();
    }

    function setReg1(uint v) internal  {
        m.reg1 = v;
        debug = v;
        state = hashMachine();
    }

    function setReg2(uint v) internal  {
        m.reg2 = v;
        state = hashMachine();
    }

    function setReg3(uint v) internal  {
        m.reg3 = v;
        state = hashMachine();
    }

    function setPC(uint v) internal {
        vm.pc = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setStackPtr(uint v) internal {
        vm.stack_ptr = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallPtr(uint v) internal {
        vm.call_ptr = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setOp(bytes32 op) internal {
        m.op = op;
        m.vm = hashVM();
        state = hashMachine();
    }

    function makeZero(uint n) internal pure returns (bytes32) {
       bytes32 res = 0;
       for (uint i = 0; i < n; i++) res = keccak256(res, res);
       return res;
    }

    function setStackSize(uint sz) internal {
        vm_r.stack = makeZero(sz);
    }

    function setCallStackSize(uint sz) internal {
        vm_r.call_stack = makeZero(sz);
    }

    function setGlobalsSize(uint sz) internal {
        vm_r.globals = makeZero(sz);
    }

    function setMemorySize(uint sz) internal {
        vm_r.mem = makeZero(sz);
    }

    function setTableSize(uint sz) internal {
        vm_r.calltable = makeZero(sz);
    }

    function setTableTypesSize(uint sz) internal {
        vm_r.calltypes = makeZero(sz);
    }

}

pragma solidity ^0.4.16;

contract Onchain {

   uint debug;

    struct Roots {
        bytes32 code;
        bytes32 stack;
        bytes32 mem;
        bytes32 globals;
        bytes32 calltable;
        bytes32 calltypes;
        bytes32 call_stack;
        bytes32 input_size;
        bytes32 input_name;
        bytes32 input_data;
    }

    struct VM {
        uint pc;
        uint stack_ptr;
        uint call_ptr;
        uint memsize;
    }

    struct Machine {
        bytes32 vm;
        bytes32 op;
        uint reg1;
        uint reg2;
        uint reg3;
        uint ireg;
    }

    VM vm;
    Roots vm_r;
    Machine m;
    bytes32[] proof;
    bytes32[] proof2;

    bytes32 state;

    function setVM(bytes32[10] roots, uint[4] pointers) internal {
        vm_r.code = roots[0];
        vm_r.stack = roots[1];
        vm_r.mem = roots[2];
        vm_r.call_stack = roots[3];
        vm_r.globals = roots[4];
        vm_r.calltable = roots[5];
        vm_r.calltypes = roots[6];
        vm_r.input_size = roots[7];
        vm_r.input_name = roots[8];
        vm_r.input_data = roots[9];

        vm.pc = pointers[0];
        vm.stack_ptr = pointers[1];
        vm.call_ptr = pointers[2];
        vm.memsize = pointers[3];
    }

    function hashVM() internal view returns (bytes32) {
        bytes32[] memory arr = new bytes32[](14);
        arr[0] = vm_r.code;
        arr[1] = vm_r.mem;
        arr[2] = vm_r.stack;
        arr[3] = vm_r.globals;
        arr[4] = vm_r.call_stack;
        arr[5] = vm_r.calltable;
        arr[6] = vm_r.calltypes;
        arr[7] = vm_r.input_size;
        arr[8] = vm_r.input_name;
        arr[9] = vm_r.input_data;
        arr[10] = bytes32(vm.pc);
        arr[11] = bytes32(vm.stack_ptr);
        arr[12] = bytes32(vm.call_ptr);
        arr[13] = bytes32(vm.memsize);
        return keccak256(arr);
    }

    function setMachine(
        bytes32 vm_,
        bytes32 op,
        uint reg1,
        uint reg2,
        uint reg3,
        uint ireg) internal {
        m.vm = vm_;
        m.op = op;
        m.reg1 = reg1;
        m.reg2 = reg2;
        m.reg3 = reg3;
        m.ireg = ireg;
    }

    function hashMachine() internal view returns (bytes32) {
        return keccak256(m.vm, m.op, m.reg1, m.reg2, m.reg3, m.ireg);
    }

    function getLeaf(uint loc) internal view returns (uint) {
        require(proof.length >= 2);
        if (loc%2 == 0) return uint(proof[0]);
        else return uint(proof[1]);
    }

    function setLeaf(uint loc, uint v) internal {
        require(proof.length >= 2);
        if (loc%2 == 0) proof[0] = bytes32(v);
        else proof[1] = bytes32(v);
    }

    function getRoot(uint loc) internal view returns (bytes32) {
        require(proof.length >= 2);
        bytes32 res = keccak256(proof[0], proof[1]);
        for (uint i = 2; i < proof.length; i++) {
            loc = loc/2;
            if (loc%2 == 0) res = keccak256(res, proof[i]);
            else res = keccak256(proof[i], res);
        }
        require(loc < 2);
        return res;
    }

    function getLeaf2(uint loc) internal view returns (uint) {
        require(proof2.length >= 2);
        if (loc%2 == 0) return uint(proof2[0]);
        else return uint(proof2[1]);
    }

    function setLeaf2(uint loc, uint v) internal {
        require(proof2.length >= 2);
        if (loc%2 == 0) proof2[0] = bytes32(v);
        else proof2[1] = bytes32(v);
    }

    function getRoot2(uint loc) internal view returns (bytes32) {
        require(proof2.length >= 2);
        bytes32 res = keccak256(proof2[0], proof2[1]);
        for (uint i = 2; i < proof2.length; i++) {
            loc = loc/2;
            if (loc%2 == 0) res = keccak256(res, proof2[i]);
            else res = keccak256(proof2[i], res);
        }
        require(loc < 2);
        return res;
    }

    function getCode(uint loc) internal view returns (bytes32) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.code);
        return bytes32(getLeaf(loc));
    }

    function getStack(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.stack);
        return getLeaf(loc);
    }

    function getCallStack(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.call_stack);
        return getLeaf(loc);
    }

    function getCallTable(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltable);
        return getLeaf(loc);
    }

    function getCallTypes(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltypes);
        return getLeaf(loc);
    }

    function getMemory(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.mem);
        return getLeaf(loc);
    }

    function getGlobal(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.globals);
        return getLeaf(loc);
    }

    function getInputSize(uint loc) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_size);
        return getLeaf(loc);
    }

    function getInputName(uint loc, uint loc2) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_name);
        require(getRoot2(loc2) == bytes32(getLeaf2(loc)));
        return getLeaf2(loc2);
    }

    function setInputName(uint loc, uint loc2, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_name);
        require(getRoot2(loc2) == bytes32(getLeaf2(loc)));
        setLeaf2(loc2, v);
        setLeaf(loc, getLeaf2(loc));
        vm_r.input_name = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setInputSize(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_size);
        setLeaf(loc, v);
        vm_r.input_size = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setInputFile(uint loc, bytes32 v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data);
        setLeaf(loc, uint(v));
        vm_r.input_data = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setNthByte(uint a, uint n, uint8 bte) pure internal returns (uint) {
       uint mask = uint(-1)*(2**(8*(32-n))) | uint(-1)/(2**(8*(n+1)));
       return (a&mask) | (2**(8*(32-n)))*uint256(bte);
    }

    function setInputData(uint loc, uint loc2, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data);
        require(getRoot2(loc2/16) == bytes32(getLeaf2(loc)));
        uint leaf = getLeaf2(loc2/16);
        uint idx = loc2 % 16;

        uint nleaf = setNthByte(leaf, idx, uint8(v));

        setLeaf2(loc2/16, nleaf);
        setLeaf(loc, getLeaf2(loc));
        vm_r.input_data = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function getInputData(uint loc, uint loc2) internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data);
        require(getRoot2(loc2/16) == bytes32(getLeaf2(loc)));
        uint leaf = getLeaf2(loc2/16);
        uint idx = loc2 % 16;
        return (leaf / 2**(idx*8)) & 0xff;
    }

    function createInputData(uint loc, uint sz) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.input_data);
        sz = sz/16;
        bytes32 zero = keccak256(bytes32(0), bytes32(0));
        while (sz > 1) {
            sz = sz/2;
            zero = keccak256(zero, zero);
        }
        setLeaf(loc, uint(zero));
        vm_r.input_data = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallStack(uint loc, uint v) internal  {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.call_stack);
        setLeaf(loc, v);
        vm_r.call_stack = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setMemory(uint loc, uint v) internal  {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.mem);
        setLeaf(loc, v);
        vm_r.mem = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setStack(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.stack);
        setLeaf(loc, v);
        vm_r.stack = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setGlobal(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.globals);
        setLeaf(loc, v);
        vm_r.globals = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallTable(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltable);
        setLeaf(loc, v);
        vm_r.calltable = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallType(uint loc, uint v) internal {
        require(hashMachine() == state && hashVM() == m.vm);
        require(getRoot(loc) == vm_r.calltypes);
        setLeaf(loc, v);
        vm_r.calltypes = getRoot(loc);
        m.vm = hashVM();
        state = hashMachine();
    }

    function getPC() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.pc;
    }

    function getMemsize() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.memsize;
    }

    function getStackPtr() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.stack_ptr;
    }

    function getCallPtr() internal view returns (uint) {
        require(hashMachine() == state && hashVM() == m.vm);
        return vm.call_ptr;
    }

    function getReg1() internal view returns (uint) {
        require(hashMachine() == state);
        return m.reg1;
    }

    function getReg2() internal view returns (uint) {
        require(hashMachine() == state);
        return m.reg2;
    }

    function getReg3() internal view returns (uint) {
        require(hashMachine() == state);
        return m.reg3;
    }

    function getIreg() internal view returns (uint) {
        require(hashMachine() == state);
        return m.ireg;
    }

    function getOp() internal view returns (bytes32) {
        require(hashMachine() == state);
        return m.op;
    }

    function setMemsize(uint v) internal {
        vm.memsize = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setIreg(uint v) internal  {
        m.ireg = v;
        state = hashMachine();
    }

    function setReg1(uint v) internal  {
        m.reg1 = v;
        debug = v;
        state = hashMachine();
    }

    function setReg2(uint v) internal  {
        m.reg2 = v;
        state = hashMachine();
    }

    function setReg3(uint v) internal  {
        m.reg3 = v;
        state = hashMachine();
    }

    function setPC(uint v) internal {
        vm.pc = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setStackPtr(uint v) internal {
        vm.stack_ptr = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setCallPtr(uint v) internal {
        vm.call_ptr = v;
        m.vm = hashVM();
        state = hashMachine();
    }

    function setOp(bytes32 op) internal {
        m.op = op;
        m.vm = hashVM();
        state = hashMachine();
    }

    function makeZero(uint n) internal pure returns (bytes32) {
       bytes32 res = 0;
       for (uint i = 0; i < n; i++) res = keccak256(res, res);
       return res;
    }

    function setStackSize(uint sz) internal {
        vm_r.stack = makeZero(sz);
    }

    function setCallStackSize(uint sz) internal {
        vm_r.call_stack = makeZero(sz);
    }

    function setGlobalsSize(uint sz) internal {
        vm_r.globals = makeZero(sz);
    }

    function setMemorySize(uint sz) internal {
        vm_r.mem = makeZero(sz);
    }

    function setTableSize(uint sz) internal {
        vm_r.calltable = makeZero(sz);
    }

    function setTableTypesSize(uint sz) internal {
        vm_r.calltypes = makeZero(sz);
    }

}


The constructor of 005.sol seems to be working

contract auction
  (address _beneficiary
  ,uint _bidding_time
,bool[address] _bids
	,uint _highest_bid)
{
}

contract auction
  (address _beneficiary
  ,uint _bidding_time
)
{
}


add functions market

add functions market

contract token {
    address public creator;
    string public symbol;
    string public name;
    uint public baseUnit;
    uint totalSupply;
    mapping (address => uint) public 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(string _s, string _n, uint _unit) {
        creator = msg.sender;
        symbol = _s;
        name = _n;
        baseUnit = _unit;
    }

    /* Creator functions */
    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[creator] + _amount < balanceOf[creator]) {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 result) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

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

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

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

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

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, string _abi, string _helper) creatorCheck returns(uint agentContractID) {
        agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _agentContractAddr;
        a.abi = _abi;
        a.helper = _helper;
        return (agentContractID);
    }
}

contract marketAgent {
    address creator;
    market Market;

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

    function marketAgent(address _marketAddr, string _marketAbi, string _marketHelper) {
        creator = msg.sender;
        Market = market(_marketAddr);
        Market.credit().approve(_marketAddr);
    }

    function approveSupply(token _asset, uint _maxValue) creatorCheck returns(bool result) {
        token asset = token(_asset);
        result = asset.approveOnce(Market, _maxValue);
        return result;
    }

    function addSell(token _assetAddr, uint _total, uint _unitPrice, uint _min, uint _step) returns(uint) {
        if (token(_assetAddr).myBalance() >= _total) {
            approveSupply(_assetAddr, _total);
            return Market.addSell(_assetAddr, _total, _unitPrice, _min, _step);
        }
    }

    function addBuy(address _assetAddr, uint _total, uint _unitPrice, uint _min, uint _step) returns(uint) {
        if (Market.credit().myBalance() >= (_total * _unitPrice)) {
            return Market.addBuy(_assetAddr, _total, _unitPrice, _min, _step);
        }
    }

    function removeSell(address _assetAddr, uint _orderID) returns(bool) {
        return Market.removeSell(_assetAddr, _orderID);
    }

    function removeBuy(address _assetAddr, uint _orderID) returns(bool) {
        return Market.removeBuy(_assetAddr, _orderID);
    }

    function buyDeal(address _assetAddr, uint _amount, uint _orderID) returns(bool) {
        return Market.buyDeal(_assetAddr, _amount, _orderID);
    }

    function sellDeal(token _assetAddr, uint _amount, uint _orderID) returns(bool) {
        if (token(_assetAddr).myBalance() >= _amount) {
            approveSupply(_assetAddr, _amount);
            return Market.sellDeal(_assetAddr, _amount, _orderID);
        }
    }
}

contract market {
    address creator;
    token public credit;

    struct Order {
        uint orderID;
        address owner;
        uint total;
        uint unitPrice;
        uint min;
        uint step;
        bool active;
    }

    struct SaleAssetList {
        address assetAddr;
        Order[] sellOrderList;
    }

    struct BuyAssetList {
        address assetAddr;
        Order[] buyOrderList;
    }

    SaleAssetList[] public sellAssetList;
    mapping (address => bool) public sellExistOf;
    mapping (address => uint) public sellDataOf;

    BuyAssetList[] public buyAssetList;
    mapping (address => bool) public buyExistOf;
    mapping (address => uint) public buyDataOf;

    function market(address _credit) {
        creator = msg.sender;
        credit = token(_credit);
    }

    function addSell(address _assetAddr, uint _total, uint _unitPrice, uint _min, uint _step) returns(uint sellID) {
        uint assetID;
        if (sellExistOf[_assetAddr]) {
            assetID = sellDataOf[_assetAddr];
            SaleAssetList sellAssetOrders = sellAssetList[assetID];
        } else {
            assetID = sellAssetList.length++;
            sellExistOf[_assetAddr] = true;
            sellAssetOrders = sellAssetList[assetID];
            sellAssetOrders.assetAddr = _assetAddr;
        }
        sellID = sellAssetOrders.sellOrderList.length++;

        Order order = sellAssetOrders.sellOrderList[sellID];
        order.orderID = sellID;
        order.owner = msg.sender;
        order.total = _total;
        order.unitPrice = _unitPrice;
        order.min = _min;
        order.step = _step;
        order.active = true;

        return sellID;
    }

    function addBuy(address _assetAddr, uint _total, uint _unitPrice, uint _min, uint _step) returns(uint buyID) {
        uint assetID;
        if (buyExistOf[_assetAddr]) {
            assetID = buyDataOf[_assetAddr];
            BuyAssetList buyAssetOrders = buyAssetList[assetID];
        } else {
            assetID = buyAssetList.length++;
            buyExistOf[_assetAddr] = true;
            buyAssetOrders = buyAssetList[assetID];
            buyAssetOrders.assetAddr = _assetAddr;
        }
        buyID = buyAssetOrders.buyOrderList.length++;

        Order order = buyAssetOrders.buyOrderList[buyID];
        order.orderID = buyID;
        order.owner = msg.sender;
        order.total = _total;
        order.unitPrice = _unitPrice;
        order.min = _min;
        order.step = _step;
        order.active = true;

        return buyID;
    }

    function removeSell(address _assetAddr, uint _orderID) returns(bool) {
        if (sellExistOf[_assetAddr]) {
            uint assetID = sellDataOf[_assetAddr];
            Order order = sellAssetList[assetID].sellOrderList[_orderID];
            if (order.owner == msg.sender) {
                order.active = false;
                return true;
            }
        }
        return false;
    }

    function removeBuy(address _assetAddr, uint _orderID) returns(bool) {
        if (buyExistOf[_assetAddr]) {
            uint assetID = buyDataOf[_assetAddr];
            Order order = buyAssetList[assetID].buyOrderList[_orderID];
            if (order.owner == msg.sender) {
                order.active = false;
                return true;
            }
        }
        return false;
    }

    function getSell(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (sellExistOf[_assetAddr]) {
            uint assetID = sellDataOf[_assetAddr];
            Order order = sellAssetList[assetID].sellOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }

    function getBuy(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (buyExistOf[_assetAddr]) {
            uint assetID = buyDataOf[_assetAddr];
            Order order = buyAssetList[assetID].buyOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }

    function buyDeal(address _assetAddr, uint _amount, uint _orderID) returns(bool) {
        if (sellExistOf[_assetAddr]) {
            uint assetID = sellDataOf[_assetAddr];
            Order order = sellAssetList[assetID].sellOrderList[_orderID];
            if (order.total > 0 && order.active == true && _amount >= order.min && _amount <= order.total && ((_amount / order.step) * order.step) == _amount) {
                marketAgent agentBuy = marketAgent(msg.sender);
                marketAgent agentSell = marketAgent(order.owner);
                token asset = token(sellAssetList[assetID].assetAddr);
                uint totalCredit = order.unitPrice * _amount;
                if (credit.isApprovedFor(agentBuy, this) &&
                    credit.isApprovedOnceFor(agentBuy, this) >= totalCredit &&
                    credit.balanceOf(agentBuy) >= totalCredit &&
                    asset.isApprovedFor(agentSell, this) &&
                    asset.isApprovedOnceFor(agentSell, this) >= _amount &&
                    asset.balanceOf(agentSell) >= _amount)
                {
                    credit.transferFrom(agentBuy, agentSell, totalCredit);
                    asset.transferFrom(agentSell, agentBuy, _amount);
                    order.total = order.total - _amount;
                    if (order.total == 0) {
                        order.active = false;
                    }
                    return true;
                }
            }
        }
        return false;
    }

    function sellDeal(address _assetAddr, uint _amount, uint _orderID) returns(bool) {
        if (buyExistOf[_assetAddr]) {
            uint assetID = buyDataOf[_assetAddr];
            Order order = buyAssetList[assetID].buyOrderList[_orderID];
            if (order.total > 0 && order.active == true && _amount >= order.min && _amount <= order.total && ((_amount / order.step) * order.step) == _amount) {
                marketAgent agentSell = marketAgent(msg.sender);
                marketAgent agentBuy = marketAgent(order.owner);
                token asset = token(buyAssetList[assetID].assetAddr);
                uint totalCredit = order.unitPrice * _amount;
                if (credit.isApprovedFor(agentBuy, this) &&
                    credit.isApprovedOnceFor(agentBuy, this) >= totalCredit &&
                    credit.balanceOf(agentBuy) >= totalCredit &&
                    asset.isApprovedFor(agentSell, this) &&
                    asset.isApprovedOnceFor(agentSell, this) >= _amount &&
                    asset.balanceOf(agentSell) >= _amount)
                {
                    credit.transferFrom(agentBuy, agentSell, totalCredit);
                    asset.transferFrom(agentSell, agentBuy, _amount);
                    order.total = order.total - _amount;
                    if (order.total == 0) {
                        order.active = false;
                    }
                    return true;
                }
            }
        }
        return false;
    }
}

contract goverment {
    address creator;
    token shares;
    token credits;

    /* info for market */
    mapping (address => bool) public banAssetOf;
    mapping (address => bool) public banAgentOf;

    struct MarketDeal {
        address asset;
        address seller;
        address buyer;
        uint amount;
        uint price;
    }

    struct Rule {
        address creator;
        address asset;
        uint percentEmmision;
        uint percentBurn;
        uint positive;
        uint negative;
    }

    Rule[] proposals;

    function goverment(string _s, string _n, uint _unit) {
        creator = msg.sender;
        shares = new token(_s, _n, _unit);
        credits = new token(_s, _n, _unit);
    }

    function getDaoEfficiently() returns(uint daoEfficiently) {

    }

    function setProposal(address _asset, uint _percentEmmision, uint _percentBurn) {
        if(shares.isApprovedFor(msg.sender, this)) {
            uint proposalID = proposals.length++;
            Rule r = proposals[proposalID];

        }
    }

}

contract creditControl is goverment {

    /* info for goverment */
    mapping (address => bool) public existRuleAssetOf;
    mapping (address => bool) public existRuleBuyerOf;
    mapping (address => bool) public existRuleSellerOf;
    mapping (address => uint) public ruleIdAssetOf;
    mapping (address => uint) public ruleIdBuyerOf;
    mapping (address => uint) public ruleIdSellerOf;

    function creditControl()   {}

    function newMarketDeal(address _asset, address _seller, address _buyer, uint _amount, uint _price) {
        if(existRuleAssetOf[_asset]) {
            uint ruleID;
            ruleID = ruleIdAssetOf[_asset];
            Rule assetRule = proposals[ruleID];
            credits.emmision(assetRule.percentEmmision*_price);
            credits.burn(assetRule.percentBurn*_price);
        }
    }
}

contract institute {

}

contract DAO {
    address public creator;
    token public shares;
    token public credits;
    market public daoMarket;
    address public daoGoverment;

    modifier govermentCheck { if (msg.sender == daoGoverment) _ }

    function DAO() {

    }

    function creditEmmision(uint _amount) govermentCheck returns(bool result) {
            result = credits.emmision(_amount);
            return result;
    }

    function creditBurn(uint _amount) govermentCheck returns(bool result) {
            result = credits.burn(_amount);
            return result;
    }

    function shareEmmision(uint _amount) govermentCheck returns(bool result) {
            result = shares.emmision(_amount);
            return result;
    }

    function shareBurn(uint _amount) govermentCheck returns(bool result) {
            result = shares.burn(_amount);
            return result;
    }

}

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(string _s, string _n, uint _unit) {
        creator = msg.sender;
        symbol = _s;
        name = _n;
        baseUnit = _unit;
    }

    /* Creator functions */
    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[creator] + _amount < balanceOf[creator]) {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 result) {
        approveOf[msg.sender][_address] = false;
        return true;
    }

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

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

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

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

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, string _abi, string _helper) creatorCheck returns(uint agentContractID) {
        agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _agentContractAddr;
        a.abi = _abi;
        a.helper = _helper;
        return (agentContractID);
    }
}

contract marketAgent is agent {
    market agentMarket;
    token credit;

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

    function marketAgent(address _marketAddr, string _marketAbi, string _marketHelper) {
        creator = msg.sender;
        agentMarket = market(_marketAddr);
        credit.approve(agentMarket);

        uint agentContractID = agentContracts.length++;
        AgentContract a = agentContracts[agentContractID];
        a.agentContractAddr = _marketAddr;
        a.abi = _marketAbi;
        a.helper = _marketHelper;
    }

    function approveSupply(token _asset, uint _maxValue) creatorCheck returns(bool result) {
        token asset = token(_asset);
        result = asset.approveOnce(agentMarket, _maxValue);
        return result;
    }
}

contract market {
    address creator;
    token credit;

    struct Order {
        uint orderID;
        address owner;
        uint total;
        uint unitPrice;
        uint min;
        uint step;
        bool active;
    }

    struct SaleAssetList {
        address assetAddr;
        Order[] sellOrderList;
    }

    struct BuyAssetList {
        address assetAddr;
        Order[] buyOrderList;
    }

    SaleAssetList[] public sellAssetList;
    Order[] public sellOrderList;
    mapping (address => bool) public sellExistOf;
    mapping (address => uint) public sellDataOf;

    BuyAssetList[] public buyAssetList;
    Order[] public buyOrderList;
    mapping (address => bool) public buyExistOf;
    mapping (address => uint) public buyDataOf;

    function market(address _credit) {
        creator = msg.sender;
        credit = token(_credit);
    }

    function getSell(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (sellExistOf[_assetAddr]) {
            uint assetID = sellDataOf[_assetAddr];
            Order order = sellAssetList[assetID].sellOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }

    function getBuy(address _assetAddr, uint _orderID) returns(address owner, uint total, uint unitPrice, uint min, uint step, bool active) {
        if (buyExistOf[_assetAddr]) {
            uint assetID = buyDataOf[_assetAddr];
            Order order = buyAssetList[assetID].buyOrderList[_orderID];
            return (order.owner, order.total, order.unitPrice, order.min, order.step, order.active);
        }
    }
}

contract goverment {
    address creator;
    token shares;
    token credits;

    /* info for market */
    mapping (address => bool) public banAssetOf;
    mapping (address => bool) public banAgentOf;

    struct MarketDeal {
        address asset;
        address seller;
        address buyer;
        uint amount;
        uint price;
    }

    struct Rule {
        address creator;
        address asset;
        uint percentEmmision;
        uint percentBurn;
        uint positive;
        uint negative;
    }

    Rule[] proposals;

    function goverment(string _s, string _n, uint _unit) {
        creator = msg.sender;
        shares = new token(_s, _n, _unit);
        credits = new token(_s, _n, _unit);
    }

    function getDaoEfficiently() returns(uint daoEfficiently) {

    }

    function setProposal(address _asset, uint _percentEmmision, uint _percentBurn) {
        if(shares.isApprovedFor(msg.sender, this)) {
            uint proposalID = proposals.length++;
            Rule r = proposals[proposalID];

        }
    }

}

contract creditControl is goverment {

    /* info for goverment */
    mapping (address => bool) public existRuleAssetOf;
    mapping (address => bool) public existRuleBuyerOf;
    mapping (address => bool) public existRuleSellerOf;
    mapping (address => uint) public ruleIdAssetOf;
    mapping (address => uint) public ruleIdBuyerOf;
    mapping (address => uint) public ruleIdSellerOf;

    function creditControl()   {}

    function newMarketDeal(address _asset, address _seller, address _buyer, uint _amount, uint _price) {
        if(existRuleAssetOf[_asset]) {
            uint ruleID;
            ruleID = ruleIdAssetOf[_asset];
            Rule assetRule = proposals[ruleID];
            credits.emmision(assetRule.percentEmmision*_price);
            credits.burn(assetRule.percentBurn*_price);
        }
    }
}

contract institute {

}

contract DAO {
    address public creator;
    token public shares;
    token public credits;
    market public daoMarket;
    address public daoGoverment;

    modifier govermentCheck { if (msg.sender == daoGoverment) _ }

    function DAO() {

    }

    function creditEmmision(uint _amount) govermentCheck returns(bool result) {
            result = credits.emmision(_amount);
            return result;
    }

    function creditBurn(uint _amount) govermentCheck returns(bool result) {
            result = credits.burn(_amount);
            return result;
    }

    function shareEmmision(uint _amount) govermentCheck returns(bool result) {
            result = shares.emmision(_amount);
            return result;
    }

    function shareBurn(uint _amount) govermentCheck returns(bool result) {
            result = shares.burn(_amount);
            return result;
    }

}


updated initial balance

updated initial balance

/*
    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.18;

import "../Creatable.sol";
import "zeppelin-solidity/contracts/token/StandardToken.sol";

/// @title Market Token
/// @notice Our membership token.  Users must lock tokens to enable trading for a given Market Contract
/// as well as have a minimum balance of tokens to create new Market Contracts.
/// @author Phil Elsasser <phil@marketprotcol.io>
contract MarketToken is StandardToken, Creatable {

    string public constant name = "Market Token";
    string public constant symbol = "MKT";
    uint8 public constant decimals = 18;

    uint public constant INITIAL_SUPPLY = 10**27; // 1 billion w. 18 decimals

    uint public lockQtyToAllowTrading;
    uint public minBalanceToAllowContractCreation;

    mapping(address => mapping(address => uint)) contractAddressToUserAddressToQtyLocked;

    event UpdatedUserLockedBalance(address indexed contractAddress, address indexed userAddress, uint balance);

    function MarketToken(uint qtyToLockForTrading, uint minBalanceForCreation) public {
        lockQtyToAllowTrading = qtyToLockForTrading;
        minBalanceToAllowContractCreation = minBalanceForCreation;
        totalSupply = INITIAL_SUPPLY;

        balances[msg.sender] = INITIAL_SUPPLY; // for now allocate all tokens to creator
    }

    /*
    // EXTERNAL METHODS
    */

    /// @notice checks if a user address has locked the needed qty to allow trading to a given contract address
    /// @param marketContractAddress address of the MarketContract
    /// @param userAddress address of the user
    /// @return true if user has locked tokens to trade the supplied marketContractAddress
    function isUserEnabledForContract(address marketContractAddress, address userAddress) external view returns (bool) {
        return contractAddressToUserAddressToQtyLocked[marketContractAddress][userAddress] >= lockQtyToAllowTrading;
    }

    /// @notice checks if a user address has enough token balance to be eligible to create a contract
    /// @param userAddress address of the user
    /// @return true if user has sufficient balance of tokens
    function isBalanceSufficientForContractCreation(address userAddress) external view returns (bool) {
        return balances[userAddress] >= minBalanceToAllowContractCreation;
    }

    /// @notice allows user to lock tokens to enable trading for a given market contract
    /// @param marketContractAddress address of the MarketContract
    /// @param qtyToLock desired qty of tokens to lock
    function lockTokensForTradingMarketContract(address marketContractAddress, uint qtyToLock) external {
        uint256 lockedBalance = contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender].add(
            qtyToLock
        );
        transfer(this, qtyToLock);
        contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender] = lockedBalance;
        UpdatedUserLockedBalance(marketContractAddress, msg.sender, lockedBalance);
    }

    /// @notice allows user to unlock tokens previously allocated to trading a MarketContract
    /// @param marketContractAddress address of the MarketContract
    /// @param qtyToUnlock desired qty of tokens to unlock
    function unlockTokens(address marketContractAddress, uint qtyToUnlock) external {
        uint256 balanceAfterUnLock = contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender].sub(
            qtyToUnlock
        );  // no need to check balance, sub() will ensure sufficient balance to unlock!
        contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender] = balanceAfterUnLock;        // update balance before external call!
        transferLockedTokensBackToUser(qtyToUnlock);
        UpdatedUserLockedBalance(marketContractAddress, msg.sender, balanceAfterUnLock);
    }

    /// @notice get the currently locked balance for a user given the specific contract address
    /// @param marketContractAddress address of the MarketContract
    /// @param userAddress address of the user
    /// @return the locked balance
    function getLockedBalanceForUser(address marketContractAddress, address userAddress) external view returns (uint) {
        return contractAddressToUserAddressToQtyLocked[marketContractAddress][userAddress];
    }

    /*
    // EXTERNAL - ONLY CREATOR  METHODS
    */

    /// @notice allows the creator to set the qty each user address needs to lock in
    /// order to trade a given MarketContract
    /// @param qtyToLock qty needed to enable trading
    function setLockQtyToAllowTrading(uint qtyToLock) external onlyCreator {
        lockQtyToAllowTrading = qtyToLock;
    }

    /// @notice allows the creator to set minimum balance a user must have in order to create MarketContracts
    /// @param minBalance balance to enable contract creation
    function setMinBalanceForContractCreation(uint minBalance) external onlyCreator {
        minBalanceToAllowContractCreation = minBalance;
    }

    /*
    // PRIVATE METHODS
    */

    /// @dev returns locked balance from this contract to the user's balance
    /// @param qtyToUnlock qty to return to user's balance
    function transferLockedTokensBackToUser(uint qtyToUnlock) private {
        balances[this] = balances[this].sub(qtyToUnlock);
        balances[msg.sender] = balances[msg.sender].add(qtyToUnlock);
        Transfer(this, msg.sender, qtyToUnlock);
    }

}

/*
    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.18;

import "../Creatable.sol";
import "zeppelin-solidity/contracts/token/StandardToken.sol";

/// @title Market Token
/// @notice Our membership token.  Users must lock tokens to enable trading for a given Market Contract
/// as well as have a minimum balance of tokens to create new Market Contracts.
/// @author Phil Elsasser <phil@marketprotcol.io>
contract MarketToken is StandardToken, Creatable {

    string public constant name = "Market Token";
    string public constant symbol = "MKT";
    uint8 public constant decimals = 18;

    uint public constant INITIAL_SUPPLY = 100000000 * uint(10)**decimals;

    uint public lockQtyToAllowTrading;
    uint public minBalanceToAllowContractCreation;

    mapping(address => mapping(address => uint)) contractAddressToUserAddressToQtyLocked;

    event UpdatedUserLockedBalance(address indexed contractAddress, address indexed userAddress, uint balance);

    function MarketToken(uint qtyToLockForTrading, uint minBalanceForCreation) public {
        lockQtyToAllowTrading = qtyToLockForTrading;
        minBalanceToAllowContractCreation = minBalanceForCreation;
        totalSupply = INITIAL_SUPPLY;

        balances[msg.sender] = INITIAL_SUPPLY; // for now allocate all tokens to creator
    }

    /*
    // EXTERNAL METHODS
    */

    /// @notice checks if a user address has locked the needed qty to allow trading to a given contract address
    /// @param marketContractAddress address of the MarketContract
    /// @param userAddress address of the user
    /// @return true if user has locked tokens to trade the supplied marketContractAddress
    function isUserEnabledForContract(address marketContractAddress, address userAddress) external view returns (bool) {
        return contractAddressToUserAddressToQtyLocked[marketContractAddress][userAddress] >= lockQtyToAllowTrading;
    }

    /// @notice checks if a user address has enough token balance to be eligible to create a contract
    /// @param userAddress address of the user
    /// @return true if user has sufficient balance of tokens
    function isBalanceSufficientForContractCreation(address userAddress) external view returns (bool) {
        return balances[userAddress] >= minBalanceToAllowContractCreation;
    }

    /// @notice allows user to lock tokens to enable trading for a given market contract
    /// @param marketContractAddress address of the MarketContract
    /// @param qtyToLock desired qty of tokens to lock
    function lockTokensForTradingMarketContract(address marketContractAddress, uint qtyToLock) external {
        uint256 lockedBalance = contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender].add(
            qtyToLock
        );
        transfer(this, qtyToLock);
        contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender] = lockedBalance;
        UpdatedUserLockedBalance(marketContractAddress, msg.sender, lockedBalance);
    }

    /// @notice allows user to unlock tokens previously allocated to trading a MarketContract
    /// @param marketContractAddress address of the MarketContract
    /// @param qtyToUnlock desired qty of tokens to unlock
    function unlockTokens(address marketContractAddress, uint qtyToUnlock) external {
        uint256 balanceAfterUnLock = contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender].sub(
            qtyToUnlock
        );  // no need to check balance, sub() will ensure sufficient balance to unlock!
        contractAddressToUserAddressToQtyLocked[marketContractAddress][msg.sender] = balanceAfterUnLock;        // update balance before external call!
        transferLockedTokensBackToUser(qtyToUnlock);
        UpdatedUserLockedBalance(marketContractAddress, msg.sender, balanceAfterUnLock);
    }

    /// @notice get the currently locked balance for a user given the specific contract address
    /// @param marketContractAddress address of the MarketContract
    /// @param userAddress address of the user
    /// @return the locked balance
    function getLockedBalanceForUser(address marketContractAddress, address userAddress) external view returns (uint) {
        return contractAddressToUserAddressToQtyLocked[marketContractAddress][userAddress];
    }

    /*
    // EXTERNAL - ONLY CREATOR  METHODS
    */

    /// @notice allows the creator to set the qty each user address needs to lock in
    /// order to trade a given MarketContract
    /// @param qtyToLock qty needed to enable trading
    function setLockQtyToAllowTrading(uint qtyToLock) external onlyCreator {
        lockQtyToAllowTrading = qtyToLock;
    }

    /// @notice allows the creator to set minimum balance a user must have in order to create MarketContracts
    /// @param minBalance balance to enable contract creation
    function setMinBalanceForContractCreation(uint minBalance) external onlyCreator {
        minBalanceToAllowContractCreation = minBalance;
    }

    /*
    // PRIVATE METHODS
    */

    /// @dev returns locked balance from this contract to the user's balance
    /// @param qtyToUnlock qty to return to user's balance
    function transferLockedTokensBackToUser(uint qtyToUnlock) private {
        balances[this] = balances[this].sub(qtyToUnlock);
        balances[msg.sender] = balances[msg.sender].add(qtyToUnlock);
        Transfer(this, msg.sender, qtyToUnlock);
    }

}


Clean up new contract

Clean up new contract

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;
		}
	}
}

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) returns(bool) {
        bytes32 hash = sha3(hashes);
        if (ecrecover(hash, v, r, s) != signer) return false;
        unanimousConsent.consent(hashes);
        return true;
    }
}


--Adding the meta contract which will create the Escrow contracts between users

contract Escrow {
    struct Buyer {
        address account;
    }
    struct Seller {
        address account;
    }
    Buyer buyer;
    Seller seller;
    uint amount;
    uint dispute_resolution_fee = 5; //Percentage

    function setBuyer(uint _amount) {
        buyer.account = msg.sender;
        amount = _amount;
    }

    function setSeller(uint _amount) {
        seller.account = msg.sender;
        amount = _amount;
    }

    function getBuyer() constant returns (address buyerAccount) {
        return buyer.account;
    }

    function getSeller() constant returns (address sellerAccount) {
        return seller.account;
    }

    function complete() {
        seller.account.send(amount);
    }

    function cancel() {
        suicide(buyer.account);
    }
}

//This contract will create the Escrow contract for the users
contract EscrowCreator {
    function createEscrowBySeller(address seller, uint amount) returns (address tokenAddress) {
        Escrow contract = new Escrow();
        contract.setSeller(seller, amount)
        return address(contract);
    }

    function createEscrowByBuyer(address buyer, uint amount) returns (address tokenAddress) {
        Escrow contract = new Escrow();
        contract.setBuyer(buyer, amount)
        return address(contract);
    }

    function setArbitratorI(address arbitrator) {
    }
}