Minor fixes.

Minor fixes.

//sol Registrar
// Simple global registrar.
// @authors:
//   Gav Wood <g@ethdev.com>

import "owned";

contract NameRegistrar {
	function addr(string _name) constant returns (address o_owner) {}
	function name(address _owner) constant returns (string o_name) {}
}

contract Registrar is NameRegistrar {
	event Changed(string indexed name);
	event PrimaryChanged(string indexed name, address indexed addr);

	function owner(string _name) constant returns (address o_owner) {}
	function addr(string _name) constant returns (address o_address) {}
	function subRegistrar(string _name) constant returns (address o_subRegistrar) {}
	function content(string _name) constant returns (bytes32 o_content) {}

	function name(address _owner) constant returns (bytes32 o_name) {}
}

contract OwnedRegistrar is Registrar, owned {
	struct Record {
		address primary;
		address subRegistrar;
		bytes32 content;
	}

	function currentOwner() returns (address) {
		return owner;
	}

	function disown(string _name) onlyowner {
		if (m_toName[m_toRecord[_name].primary] == _name)
		{
			PrimaryChanged(_name, m_toRecord[_name].primary);
			m_toName[m_toRecord[_name].primary] = "";
		}
		delete m_toRecord[_name];
		Changed(_name);
	}

	function setAddress(string _name, address _a, bool _primary) onlyowner {
		m_toRecord[_name].primary = _a;
		if (_primary)
		{
			PrimaryChanged(_name, _a);
			m_toName[_a] = _name;
		}
		else
			Changed(_name);
	}
	function setSubRegistrar(string _name, address _registrar) onlyowner {
		m_toRecord[_name].subRegistrar = _registrar;
		Changed(_name);
	}
	function setContent(string _name, bytes32 _content) onlyowner {
		m_toRecord[_name].content = _content;
		Changed(_name);
	}
	function record(string _name) constant returns (address o_primary, address o_subRegistrar, bytes32 o_content) {
		o_primary = m_toRecord[_name].primary;
		o_subRegistrar = m_toRecord[_name].subRegistrar;
		o_content = m_toRecord[_name].content;
	}
	function addr(string _name) constant returns (address) { return m_toRecord[_name].primary; }
	function subRegistrar(string _name) constant returns (address) { return m_toRecord[_name].subRegistrar; }
	function content(string _name) constant returns (bytes32) { return m_toRecord[_name].content; }

	function name(address _owner) constant returns (string o_name) { return m_toName[_owner]; }

	mapping (address => string) m_toName;
	mapping (string => Record) m_toRecord;
}

contract FixedFeeRegistrar is Registrar {
	struct Record {
		address primary;
		address subRegistrar;
		bytes32 content;
		address owner;
	}

	modifier onlyrecordowner(string _name) { if (m_toRecord[_name].owner == msg.sender) _ }

	function reserve(string _name) {
		if (m_toRecord[_name].owner == 0 && msg.value == c_fee) {
			m_toRecord[_name].owner = msg.sender;
			Changed(_name);
		}
	}

	function transfer(string _name, address _newOwner) onlyrecordowner(_name) {
		m_toRecord[_name].owner = _newOwner;
		Changed(_name);
	}

	function disown(string _name, address _refund) onlyrecordowner(_name) {
		if (m_toName[m_toRecord[_name].primary] == _name)
		{
			PrimaryChanged(_name, m_toRecord[_name].primary);
			delete m_toName[m_toRecord[_name].primary];
		}
		delete m_toRecord[_name];
		_refund.send(c_fee);
		Changed(_name);
	}

	function setAddress(string _name, address _a, bool _primary) onlyrecordowner(_name) {
		m_toRecord[_name].primary = _a;
		if (_primary)
		{
			PrimaryChanged(_name, _a);
			m_toName[_a] = _name;
		}
		else
			Changed(_name);
	}
	function setSubRegistrar(string _name, address _registrar) onlyrecordowner(_name) {
		m_toRecord[_name].subRegistrar = _registrar;
		Changed(_name);
	}
	function setContent(string _name, bytes32 _content) onlyrecordowner(_name) {
		m_toRecord[_name].content = _content;
		Changed(_name);
	}

	function record(string _name) constant returns (address o_primary, address o_subRegistrar, bytes32 o_content) {
		o_primary = m_toRecord[_name].primary;
		o_subRegistrar = m_toRecord[_name].subRegistrar;
		o_content = m_toRecord[_name].content;
	}
	function addr(string _name) constant returns (address) { return m_toRecord[_name].primary; }
	function subRegistrar(string _name) constant returns (address) { return m_toRecord[_name].subRegistrar; }
	function content(string _name) constant returns (bytes32) { return m_toRecord[_name].content; }
	function owner(string _name) constant returns (address) { return m_toRecord[_name].owner; }

	function name(address _owner) constant returns (string o_name) { return m_toName[_owner]; }

	mapping (address => string) m_toName;
	mapping (string => Record) m_toRecord;
	int c_fee = 69 ether;
}

//sol Registrar
// Simple global registrar.
// @authors:
//   Gav Wood <g@ethdev.com>

import "owned";

contract NameRegistrar {
	function addr(string _name) constant returns (address o_owner) {}
	function name(address _owner) constant returns (string o_name) {}
}

contract Registrar is NameRegistrar {
	event Changed(string indexed name);
	event PrimaryChanged(string indexed name, address indexed addr);

	function owner(string _name) constant returns (address o_owner) {}
	function addr(string _name) constant returns (address o_address) {}
	function subRegistrar(string _name) constant returns (address o_subRegistrar) {}
	function content(string _name) constant returns (bytes32 o_content) {}

	function name(address _owner) constant returns (bytes32 o_name) {}
}

contract OwnedRegistrar is Registrar, owned {
	struct Record {
		address primary;
		address subRegistrar;
		bytes32 content;
	}

	function currentOwner() returns (address) {
		return owner;
	}

	function disown(string _name) onlyowner {
		if (m_toName[m_toRecord[_name].primary] == _name)
		{
			PrimaryChanged(_name, m_toRecord[_name].primary);
			m_toName[m_toRecord[_name].primary] = "";
		}
		delete m_toRecord[_name];
		Changed(_name);
	}

	function setAddress(string _name, address _a, bool _primary) onlyowner {
		m_toRecord[_name].primary = _a;
		if (_primary)
		{
			PrimaryChanged(_name, _a);
			m_toName[_a] = _name;
		}
		else
			Changed(_name);
	}
	function setSubRegistrar(string _name, address _registrar) onlyowner {
		m_toRecord[_name].subRegistrar = _registrar;
		Changed(_name);
	}
	function setContent(string _name, bytes32 _content) onlyowner {
		m_toRecord[_name].content = _content;
		Changed(_name);
	}
	function record(string _name) constant returns (address o_primary, address o_subRegistrar, bytes32 o_content) {
		o_primary = m_toRecord[_name].primary;
		o_subRegistrar = m_toRecord[_name].subRegistrar;
		o_content = m_toRecord[_name].content;
	}
	function addr(string _name) constant returns (address) { return m_toRecord[_name].primary; }
	function subRegistrar(string _name) constant returns (address) { return m_toRecord[_name].subRegistrar; }
	function content(string _name) constant returns (bytes32) { return m_toRecord[_name].content; }

	function name(address _owner) constant returns (string o_name) { return m_toName[_owner]; }

	mapping (address => string) m_toName;
	mapping (string => Record) m_toRecord;
}

contract FixedFeeRegistrar is Registrar, owned {
	struct Record {
		address primary;
		address subRegistrar;
		bytes32 content;
		address owner;
	}

	modifier onlyrecordowner(bytes32 _name) { if (m_toRecord[_name].owner == msg.sender) _ }

	function reserve(string _name) {
		if (m_toRecord[_name].owner == 0 && msg.value == c_fee) {
			m_toRecord[_name].owner = msg.sender;
			Changed(_name);
		}
	}

	function transfer(string _name, address _newOwner) onlyrecordowner(_name) {
		m_toRecord[_name].owner = _newOwner;
		Changed(_name);
	}

	function disown(string _name, address _refund) onlyrecordowner(_name) {
		if (m_toName[m_toRecord[_name].primary] == _name)
		{
			PrimaryChanged(_name, m_toRecord[_name].primary);
			delete m_toName[m_toRecord[_name].primary];
		}
		delete m_toRecord[_name];
		_refund.send(c_fee);
		Changed(_name);
	}

	function setAddress(string _name, address _a, bool _primary) onlyrecordowner(_name) {
		m_toRecord[_name].primary = _a;
		if (_primary)
		{
			PrimaryChanged(_name, _a);
			m_toName[_a] = _name;
		}
		else
			Changed(_name);
	}
	function setSubRegistrar(string _name, address _registrar) onlyrecordowner(_name) {
		m_toRecord[_name].subRegistrar = _registrar;
		Changed(_name);
	}
	function setContent(string _name, bytes32 _content) onlyrecordowner(_name) {
		m_toRecord[_name].content = _content;
		Changed(_name);
	}

	function record(string _name) constant returns (address o_primary, address o_subRegistrar, bytes32 o_content) {
		o_primary = m_toRecord[_name].primary;
		o_subRegistrar = m_toRecord[_name].subRegistrar;
		o_content = m_toRecord[_name].content;
	}
	function addr(string _name) constant returns (address) { return m_toRecord[_name].primary; }
	function subRegistrar(string _name) constant returns (address) { return m_toRecord[_name].subRegistrar; }
	function content(string _name) constant returns (bytes32) { return m_toRecord[_name].content; }
	function owner(string _name) constant returns (address) { return m_toRecord[_name].owner; }

	function name(address _owner) constant returns (string o_name) { return m_toName[_owner]; }

	mapping (address => string) m_toName;
	mapping (string => Record) m_toRecord;
	int c_fee = 69 ether;
}


Ensure createShortId always finds a free shortId.

pragma solidity ^0.4.23;

/**
 * @title ItemStoreShortId
 * @author Jonathan Brown <jbrown@mix-blockchain.org>
 * @dev Maintain bidirectional mapping between 32 byte itemIds and 4 byte shortIds.
 */
contract ItemStoreShortId {

    /**
     * @dev Mapping of itemId to shortId.
     */
    mapping (bytes32 => bytes4) itemIdShortId;

    /**
     * @dev Mapping of shortId to itemId.
     */
    mapping (bytes4 => bytes32) shortIdItemId;

    /**
     * @dev Revert if the itemId already has a shortId.
     * @param itemId itemId of the item.
     */
    modifier noShortId(bytes32 itemId) {
        require (itemIdShortId[itemId] == 0);
        _;
    }

    /**
     * @dev Create a 4 byte shortId for a 32 byte itemId.
     * @param itemId itemId of the item.
     * @return shortId New 4 byte shortId.
     */
    function createShortId(bytes32 itemId) external noShortId(itemId) returns (bytes4 shortId) {
        // Caluculate the shortId.
        bytes32 hash = keccak256(itemId);
        shortId = bytes4(hash);
        // Make sure it hasn't been used before.
        while(shortIdItemId[shortId] != 0) {
            hash = keccak256(hash);
            shortId = bytes4(hash);
        }
        // Store the mappings.
        itemIdShortId[itemId] = shortId;
        shortIdItemId[shortId] = itemId;
    }

    /**
     * @dev Get itemId for shortId.
     * @param shortId to get the itemId for.
     * @return The itemId.
     */
    function getItemId(bytes4 shortId) external view returns (bytes32) {
        return shortIdItemId[shortId];
    }

    /**
     * @dev Get shortId for itemId.
     * @param itemId to get the shortId for.
     * @return The shortId.
     */
    function getShortId(bytes32 itemId) external view returns (bytes4) {
        return itemIdShortId[itemId];
    }

}

pragma solidity ^0.4.23;

/**
 * @title ItemStoreShortId
 * @author Jonathan Brown <jbrown@mix-blockchain.org>
 * @dev Maintain bidirectional mapping between 32 byte itemIds and 4 byte shortIds.
 */
contract ItemStoreShortId {

    /**
     * @dev Mapping of itemId to shortId.
     */
    mapping (bytes32 => bytes4) itemIdShortId;

    /**
     * @dev Mapping of shortId to itemId.
     */
    mapping (bytes4 => bytes32) shortIdItemId;

    /**
     * @dev
     * @param itemId itemId of the item.
     * @param nonce Extra parameter to change the shortId if it is already taken.
     * @return shortId
     */
    function createShortId(bytes32 itemId, bytes32 nonce) external returns (bytes4 shortId) {
        // Caluculate the shortId.
        shortId = bytes4(keccak256(itemId, nonce));
        // Make sure it hasn't been used before.
        assert(shortIdItemId[shortId] == 0);
        // Store the mappings.
        itemIdShortId[itemId] = shortId;
        shortIdItemId[shortId] = itemId;
    }

    /**
     * @dev Get itemId for shortId.
     * @param shortId to get the itemId for.
     * @return The itemId.
     */
    function getItemId(bytes4 shortId) external view returns (bytes32) {
        return shortIdItemId[shortId];
    }

    /**
     * @dev Get shortId for itemId.
     * @param itemId to get the shortId for.
     * @return The shortId.
     */
    function getShortId(bytes32 itemId) external view returns (bytes4) {
        return itemIdShortId[itemId];
    }

}


more constant return values

more constant return values

pragma solidity ^0.4.8;

// This contract implements a simple store that can interact with
// registered customers. Every customer has its own shopping cart.
contract Store {

    /* Store internals */
    address owner;      // store owner's address
    string public name; // store name
    uint balance;       // store's balance

    mapping (address => Customer) customers;
    mapping (uint => Product) products;

    /* Store Events */
    event CustomerRegistered(address customer);
    event CustomerDeregistered(address customer);

    event ProductRegistered(uint productId);
    event ProductDeregistered(uint productId);
    event ProductRegistrationFailed(uint productId);
    event ProductDeregistrationFaled(uint productId);

    event CartProductInserted(address customer, uint prodId);
    event CartProductRemoved(address customer, uint prodId);
    event CartCheckoutCompleted(address customer, uint paymentSum);
    event CartCheckoutFailed(address customer, uint paymentSum);

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

    // every customer has an address, name,
    // balance and a shopping cart
    struct Customer {
        address adr;
        string name;
        uint balance;
        Cart cart;
    }
    // A shopping cart contains an array of product ids: @products
    // and a sum of product prices: @completeSum
    // The @completeSum gets automatically updated when customer
    // adds or removes products.
    struct Cart {
      uint[] products;
      uint completeSum;
    }
    // Represents a product:
    // Product id: @id
    // Product name: @name
    // Decription: @description
    // Amount of items in a single product: @default_amount
    struct Product {
        uint id;
        string name;
        string description;
        uint price;
        uint default_amount;
    }
    // Represents a receipt [NOT IN USE]
    struct Receipt {
        InvoiceLine[] lines;
        address customer_address;
    }
    // Represents a single entry describing a single product [NOT IN USE]
    struct InvoiceLine {
        string product_id;
        uint amount;
        uint product_price;
        uint total_price;
    }
    // Default constructor
    function Store() {
        owner = msg.sender;
        name = "retailtest";
    }
    // Register a single product (only store owners)
    function registerProduct(uint id, string name, string description,
                           uint price, uint default_amount) onlyStoreOwner returns (bool success) {
        var product = Product(id, name, description, price, default_amount);
        if (checkProductValidity(product)) {
            products[id] = product;
            ProductRegistered(id);
            return true;
        }
        ProductRegistrationFailed(id);
        return false;
    }
    // Removes a product from the list (only store owners)
    function deregisterProduct(uint productId) onlyStoreOwner returns (bool success) {
      delete products[productId];
      ProductDeregistered(productId);
      return true;
    }
    // Registers a new customer (only store owners)
    function registerCustomer(address _address, string _name, uint _balance) onlyStoreOwner returns (bool success) {
      customers[_address] = Customer(_address, _name, _balance, Cart(new uint[](0), 0));
      CustomerRegistered(_address);
      return true;
    }
    // Removes a customer (only store owners)
    function deregisterCustomer(address customerAddress) onlyStoreOwner returns (bool success) {
      delete customers[customerAddress];
      CustomerDeregistered(customerAddress);
      return true;
    }
    // Returns a elements describing a product
    function getProduct(uint id) constant returns (string prod_name, string prod_desc,
                                          uint prod_price, uint prod_default_amount) {
       return (products[id].name,
               products[id].description,
               products[id].price,
               products[id].default_amount);
    }
    // Inserts a product into the shopping cart (caller address must be a registered customer)
    // This function returns a boolean and the position of the inserted product.
    // The positional information can later be used to directly reference the product
    // within the mapping. Solidity mappings aren't interable.
    function insertProductIntoCart(uint prodId) returns (bool success, uint position) {
      customers[msg.sender].cart.products.push(prodId);
      customers[msg.sender].cart.completeSum += products[prodId].price;
      CartProductInserted(msg.sender, prodId);
      return (true, customers[msg.sender].cart.products.length -1);
    }
    // Removes a product entry from the shopping cart (caller address must be a registered customer)
    function removeProductFromCart(uint prodPosition) {
      uint[] memory new_product_list = new uint[](customers[msg.sender].cart.products.length - 1);
      var customerProds = customers[msg.sender].cart.products;
      for (uint i = 0; i < customerProds.length; i++) {
        if (i != prodPosition) {
          new_product_list[i] = customerProds[i];
        } else {
          customers[msg.sender].cart.completeSum -= products[customerProds[i]].price;
          CartProductRemoved(msg.sender, customerProds[i]);
        }
      }
      customers[msg.sender].cart.products = new_product_list;
    }
    // Returns a list of product ids and a complete sum belonging to the current customer
    // The caller address must be a registered customer
    function getCart() constant returns (uint[] productIds, uint completeSum) {
      Customer customer = customers[msg.sender];
      uint len = customer.cart.products.length;
      uint[] memory ids = new uint[](len);
      for (uint i = 0; i < len; i++) {
        ids[i] = products[i].id;
      }
      return (ids, customer.cart.completeSum);
    }
    // Returns customer's balance
    function getBalance() constant returns (uint _balance) {
      return customers[msg.sender].balance;
    }
    // Invokes a checkout process that'll use the current shopping cart to
    // transfer balances between the current customer and the store
    function checkoutCart() returns (bool success) {
      if (msg.sender != owner) {
        Customer customer = customers[msg.sender];
        uint paymentSum = customer.cart.completeSum;
        if ((customer.balance >= paymentSum) &&
            customer.cart.products.length > 0) {
            customer.balance -= paymentSum;
            customer.cart = Cart(new uint[](0), 0);
            balance += paymentSum;
            CartCheckoutCompleted(msg.sender, paymentSum);
            return true;
        }
      }
      CartCheckoutFailed(msg.sender, paymentSum);
      return false;
    }
    // Changes the name of the store (only store owners)
    function renameStoreTo(string new_store_name) onlyStoreOwner returns (bool success) {
        bytes memory a = bytes(new_store_name);
        if (a.length != 0) {
            name = new_store_name;
            return true;
        }
        return false;
    }
    // Checks product validity (private function)
    function checkProductValidity(Product product) private returns (bool valid) {
       return (product.price > 0);
    }
    // Payable fallback
    function() payable { }
}

pragma solidity ^0.4.8;

// This contract implements a simple store that can interact with
// registered customers. Every customer has its own shopping cart.
contract Store {

    /* Store internals */
    address owner;      // store owner's address
    string public name; // store name
    uint balance;       // store's balance

    mapping (address => Customer) customers;
    mapping (uint => Product) products;

    /* Store Events */
    event CustomerRegistered(address customer);
    event CustomerDeregistered(address customer);

    event ProductRegistered(uint productId);
    event ProductDeregistered(uint productId);
    event ProductRegistrationFailed(uint productId);
    event ProductDeregistrationFaled(uint productId);

    event CartProductInserted(address customer, uint prodId);
    event CartProductRemoved(address customer, uint prodId);
    event CartCheckoutCompleted(address customer, uint paymentSum);
    event CartCheckoutFailed(address customer, uint paymentSum);

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

    // every customer has an address, name,
    // balance and a shopping cart
    struct Customer {
        address adr;
        string name;
        uint balance;
        Cart cart;
    }
    // A shopping cart contains an array of product ids: @products
    // and a sum of product prices: @completeSum
    // The @completeSum gets automatically updated when customer
    // adds or removes products.
    struct Cart {
      uint[] products;
      uint completeSum;
    }
    // Represents a product:
    // Product id: @id
    // Product name: @name
    // Decription: @description
    // Amount of items in a single product: @default_amount
    struct Product {
        uint id;
        string name;
        string description;
        uint price;
        uint default_amount;
    }
    // Represents a receipt [NOT IN USE]
    struct Receipt {
        InvoiceLine[] lines;
        address customer_address;
    }
    // Represents a single entry describing a single product [NOT IN USE]
    struct InvoiceLine {
        string product_id;
        uint amount;
        uint product_price;
        uint total_price;
    }
    // Default constructor
    function Store() {
        owner = msg.sender;
        name = "retailtest";
    }
    // Register a single product (only store owners)
    function registerProduct(uint id, string name, string description,
                           uint price, uint default_amount) onlyStoreOwner returns (bool success) {
        var product = Product(id, name, description, price, default_amount);
        if (checkProductValidity(product)) {
            products[id] = product;
            ProductRegistered(id);
            return true;
        }
        ProductRegistrationFailed(id);
        return false;
    }
    // Removes a product from the list (only store owners)
    function deregisterProduct(uint productId) onlyStoreOwner returns (bool success) {
      delete products[productId];
      ProductDeregistered(productId);
      return true;
    }
    // Registers a new customer (only store owners)
    function registerCustomer(address _address, string _name, uint _balance) onlyStoreOwner returns (bool success) {
      customers[_address] = Customer(_address, _name, _balance, Cart(new uint[](0), 0));
      CustomerRegistered(_address);
      return true;
    }
    // Removes a customer (only store owners)
    function deregisterCustomer(address customerAddress) onlyStoreOwner returns (bool success) {
      delete customers[customerAddress];
      CustomerDeregistered(customerAddress);
      return true;
    }
    // Returns a elements describing a product
    function getProduct(uint id) returns (string prod_name, string prod_desc,
                                          uint prod_price, uint prod_default_amount) {
       return (products[id].name,
               products[id].description,
               products[id].price,
               products[id].default_amount);
    }
    // Inserts a product into the shopping cart (caller address must be a registered customer)
    function insertProductIntoCart(uint prodId) returns (bool success, uint position) {
      customers[msg.sender].cart.products.push(prodId);
      customers[msg.sender].cart.completeSum += products[prodId].price;
      CartProductInserted(msg.sender, prodId);
      return (true, customers[msg.sender].cart.products.length -1);
    }
    // Removes a product entry from the shopping cart (caller address must be a registered customer)
    function removeProductFromCart(uint prodPosition) {
      uint[] memory new_product_list = new uint[](customers[msg.sender].cart.products.length - 1);
      var customerProds = customers[msg.sender].cart.products;
      for (uint i = 0; i < customerProds.length; i++) {
        if (i != prodPosition) {
          new_product_list[i] = customerProds[i];
        } else {
          customers[msg.sender].cart.completeSum -= products[customerProds[i]].price;
          CartProductRemoved(msg.sender, customerProds[i]);
        }
      }
      customers[msg.sender].cart.products = new_product_list;
    }
    // Returns a list of product ids and a complete sum belonging to the current customer
    // The caller address must be a registered customer
    function getCart() returns (uint[] productIds, uint completeSum) {
      Customer customer = customers[msg.sender];
      uint len = customer.cart.products.length;
      uint[] memory ids = new uint[](len);
      for (uint i = 0; i < len; i++) {
        ids[i] = products[i].id;
      }
      return (ids, customer.cart.completeSum);
    }
    // Returns customer's balance
    function getBalance() returns (uint _balance) {
      return customers[msg.sender].balance;
    }
    // Invokes a checkout process that'll use the current shopping cart to
    // transfer balances between the current customer and the store
    function checkoutCart() returns (bool success) {
      if (msg.sender != owner) {
        Customer customer = customers[msg.sender];
        uint paymentSum = customer.cart.completeSum;
        if ((customer.balance >= paymentSum) &&
            customer.cart.products.length > 0) {
            customer.balance -= paymentSum;
            customer.cart = Cart(new uint[](0), 0);
            balance += paymentSum;
            CartCheckoutCompleted(msg.sender, paymentSum);
            return true;
        }
      }
      CartCheckoutFailed(msg.sender, paymentSum);
      return false;
    }
    // Changes the name of the store (only store owners)
    function renameStoreTo(string new_store_name) onlyStoreOwner returns (bool success) {
        bytes memory a = bytes(new_store_name);
        if (a.length != 0) {
            name = new_store_name;
            return true;
        }
        return false;
    }
    // Checks product validity (private function)
    function checkProductValidity(Product product) private returns (bool valid) {
       return (product.price > 0);
    }
    // Payable fallback
    function() payable { }
}


Removed unnecessary codd in bounty creator

pragma solidity ^0.4.2;

contract GitBountyCreator {
    address[] bountiesAddressesArray;
    function createBounty(string issueUrl, address[] voters,uint256  expiresIn ) public payable returns(address) {
        GitBounty b = new GitBounty(issueUrl, voters, expiresIn, this);
        b.addToBounty.value(msg.value)();
        bountiesAddressesArray.push(b);
        return b;
    }
    function getAllBounties() public constant returns (address[]) {
      return bountiesAddressesArray;
    }
}

contract GitBounty {
    GitBountyCreator public parent;
    string public key;
    address public owner;
    uint256 public totalBounty;
    uint256 public expiresAt;
    address[] public voterAddresses;
    uint256 public totalVotes;
    mapping (address => uint256) public contributions;
    mapping (address => bool) public eligibleVotersAddresses;
    mapping (address => uint256) public votes;
    address[] public PRS;
    uint256 public totalPRS;
    uint256 public requiredNumberOfVotes;
    bool public isBountyOpen;
    mapping (bytes32 => bool) private hasVotedToAddress;

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }
    modifier isEligibleVoter {
        require(eligibleVotersAddresses[msg.sender]);
        _;
    }
    modifier bountyOpen {
        require(isBountyOpen);
        _;
    }
    modifier votedOnce(address voter, address hunter) {
        require(!hasVoted(voter, hunter));
        _;
    }
    function GitBounty(string issueUrl, address[] voters,uint256  expiresIn, GitBountyCreator parentAddress ) public payable {
        parent = parentAddress;
        key = issueUrl;
        isBountyOpen = true;
        expiresAt += expiresIn + now;
        totalBounty += msg.value;
        owner = msg.sender;
        voterAddresses = voters;
        requiredNumberOfVotes = (voterAddresses.length / 2 )  + 1;
        for (uint256 i=0; i < voterAddresses.length; i++ ){
            eligibleVotersAddresses[voterAddresses[i]] = true;
        }
        contributions[msg.sender] += msg.value;
    }
    function addToBounty() public payable bountyOpen {
        contributions[msg.sender] += msg.value;
        totalBounty += msg.value;
    }
    function vote(address addr) public isEligibleVoter bountyOpen votedOnce(msg.sender, addr){
        votes[addr] += 1;
        if (votes[addr] == 1 ) {
          // New PR vote
          PRS.push(addr);
          totalPRS++;
        }
        addVotePair(msg.sender, addr);
        doCount(addr);
    }
    function doCount(address addr) private {
        if (votes[addr] >= requiredNumberOfVotes) {
            addr.transfer(totalBounty);
            isBountyOpen = false;
        }
    }
    function addVotePair(address voter, address hunter) private {
        hasVotedToAddress[keccak256(voter, hunter)] = true;
    }
    function hasVoted(address voter, address hunter) private constant returns (bool) {
        return hasVotedToAddress[keccak256(voter, hunter)];
    }
    function getAllPRS() public constant returns (address[]) {
      return PRS;
    }

}

pragma solidity ^0.4.2;

contract GitBountyCreator {
    struct Bounty {
        address addr;
        uint256 totalVotes;
        uint256 totalVoters;
        uint256 payoutAmount;
    }
    mapping (string => Bounty) private bounties;
    address[] bountiesAddressesArray;
    modifier isChild(string key) {
        require(bounties[key].addr == msg.sender);
        _;
    }
    function createBounty(string issueUrl, address[] voters,uint256  expiresIn ) public payable returns(address) {
        GitBounty b = new GitBounty(issueUrl, voters, expiresIn, this);
        bounties[issueUrl] = Bounty({
            addr: b,
            totalVotes: 0,
            totalVoters: voters.length,
            payoutAmount: 0
        });
        b.addToBounty.value(msg.value)();
        bountiesAddressesArray.push(b);
        return b;
    }
    function getBounty(string key) public constant returns (address, uint256, uint256, uint256) {
        return (bounties[key].addr, bounties[key].totalVotes, bounties[key].totalVoters, bounties[key].payoutAmount);
    }
    function updateBountyAmount(string key, uint256 newAmount) public isChild(key) {
        Bounty storage b = bounties[key];
        b.payoutAmount = newAmount;
        bounties[key] = b;
    }
    function updateVoteProgress(string key, uint256 newTotalVotes) public isChild(key) {
      Bounty storage b = bounties[key];
      b.totalVotes = newTotalVotes;
      bounties[key] = b;
    }
    function getAllBounties() public constant returns (address[]) {
      return bountiesAddressesArray;
    }
}

contract GitBounty {
    GitBountyCreator public parent;
    string public key;
    address public owner;
    uint256 public totalBounty;
    uint256 public expiresAt;
    address[] public voterAddresses;
    uint256 public totalVotes;
    mapping (address => uint256) public contributions;
    mapping (address => bool) public eligibleVotersAddresses;
    mapping (address => uint256) public votes;
    address[] public PRS;
    uint256 public totalPRS;
    uint256 public requiredNumberOfVotes;
    bool public isBountyOpen;
    mapping (bytes32 => bool) private hasVotedToAddress;

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }
    modifier isEligibleVoter {
        require(eligibleVotersAddresses[msg.sender]);
        _;
    }
    modifier bountyOpen {
        require(isBountyOpen);
        _;
    }
    modifier votedOnce(address voter, address hunter) {
        require(!hasVoted(voter, hunter));
        _;
    }
    function GitBounty(string issueUrl, address[] voters,uint256  expiresIn, GitBountyCreator parentAddress ) public payable {
        parent = parentAddress;
        key = issueUrl;
        isBountyOpen = true;
        expiresAt += expiresIn + now;
        totalBounty += msg.value;
        owner = msg.sender;
        voterAddresses = voters;
        requiredNumberOfVotes = (voterAddresses.length / 2 )  + 1;
        for (uint256 i=0; i < voterAddresses.length; i++ ){
            eligibleVotersAddresses[voterAddresses[i]] = true;
        }
        contributions[msg.sender] += msg.value;
    }
    function addToBounty() public payable bountyOpen {
        contributions[msg.sender] += msg.value;
        totalBounty += msg.value;
        parent.updateBountyAmount(key, totalBounty);
    }
    function vote(address addr) public isEligibleVoter bountyOpen votedOnce(msg.sender, addr){
        votes[addr] += 1;
        if (votes[addr] == 1 ) {
          // New PR vote
          PRS.push(addr);
          totalPRS++;
        }
        addVotePair(msg.sender, addr);
        doCount(addr);
    }
    function doCount(address addr) private {
        if (votes[addr] >= requiredNumberOfVotes) {
            addr.transfer(totalBounty);
            isBountyOpen = false;
        }
    }
    function addVotePair(address voter, address hunter) private {
        hasVotedToAddress[keccak256(voter, hunter)] = true;
    }
    function hasVoted(address voter, address hunter) private constant returns (bool) {
        return hasVotedToAddress[keccak256(voter, hunter)];
    }
    function getAllPRS() public constant returns (address[]) {
      return PRS;
    }

}


Added Math.sol docstrings. (#1423)

Added Math.sol docstrings. (#1423)

(cherry picked from commit a3e312d133f9df1942b96b39cd007c883cd0331f)

pragma solidity ^0.4.24;

/**
 * @title Math
 * @dev Assorted math operations
 */
library Math {
  /**
  * @dev Returns the largest of two numbers.
  */
  function max(uint256 a, uint256 b) internal pure returns (uint256) {
    return a >= b ? a : b;
  }

  /**
  * @dev Returns the smallest of two numbers.
  */
  function min(uint256 a, uint256 b) internal pure returns (uint256) {
    return a < b ? a : b;
  }

  /**
  * @dev Calculates the average of two numbers. Since these are integers,
  * averages of an even and odd number cannot be represented, and will be
  * rounded down.
  */
  function average(uint256 a, uint256 b) internal pure returns (uint256) {
    // (a + b) / 2 can overflow, so we distribute
    return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
  }
}

pragma solidity ^0.4.24;

/**
 * @title Math
 * @dev Assorted math operations
 */
library Math {
  function max(uint256 a, uint256 b) internal pure returns (uint256) {
    return a >= b ? a : b;
  }

  function min(uint256 a, uint256 b) internal pure returns (uint256) {
    return a < b ? a : b;
  }

  function average(uint256 a, uint256 b) internal pure returns (uint256) {
    // (a + b) / 2 can overflow, so we distribute
    return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
  }
}


keeping contract in repo

keeping contract in repo

contract MicropaymentsNetwork
{

    enum ChannelStage
    {
        Empty,
        PartiallyConfirmed,
        Confirmed,
        Closing,
        Closed
    }

    struct MicropaymentsChannel
    {
        ChannelStage stage;

        address from;
        uint fromBalance;

        address to;
        uint toBalance;

        uint balanceTimestamp;
        uint closingBlockNumber;
    }

    uint public constant closingDelay = 10;

    mapping(uint => MicropaymentsChannel) channels;
    mapping(uint => bool) reserved;

    function MicropaymentsNetwork()
    {
    }

    function isAvailable(uint _cid)
        constant
        returns (bool)
    {
        return !reserved[_cid];
    }

    function assertAvailable(uint _cid)
        internal
    {
        if (!isAvailable(_cid))
        {
            throw;
        }
    }

    function assertOnlyFrom(uint _cid)
        internal
    {
        if (msg.sender != channels[_cid].from)
        {
            throw;
        }
    }

    function assertOnlyTo(uint _cid)
        internal
    {
        if (msg.sender != channels[_cid].to)
        {
            throw;
        }
    }

    function assertOnlyParticipants(uint _cid)
        internal
    {
        if ((msg.sender != channels[_cid].from) && (msg.sender != channels[_cid].to))
        {
            throw;
        }
    }

    function assertAtStage(uint _cid, ChannelStage _stage)
        internal
    {
        if (channels[_cid].stage != _stage)
        {
            throw;
        }
    }

    function assertAtOneOfStages(uint _cid, ChannelStage _stage1, ChannelStage _stage2)
    {
        if ((channels[_cid].stage != _stage1) && (channels[_cid].stage != _stage2))
        {
            throw;
        }
    }

    function assertReadyToClose(uint _cid)
    {
        if (block.number < channels[_cid].closingBlockNumber)
        {
            throw;
        }
    }

    function assertYoungerBalance(uint _cid, uint _balanceTimestamp)
        internal
    {
        if (_balanceTimestamp <= channels[_cid].balanceTimestamp)
        {
            throw;
        }
    }

    function assertMatchingBalance(uint _cid, uint _balanceTimestamp)
        internal
    {
        if (_balanceTimestamp != channels[_cid].balanceTimestamp)
        {
            throw;
        }
    }

    function assertSaneBalance(uint _cid, uint _fromBalance, uint _toBalance)
        internal
    {
        if (channels[_cid].fromBalance + channels[_cid].toBalance < _fromBalance + _toBalance)
        {
            throw;
        }
    }

    function assertStillValid(uint _timeout)
        internal
    {
        if (_timeout < now)
        {
            throw;
        }
    }

    function assertSaneHTLC(uint _cid, int _fromToDelta)
        internal
    {
        if ((int(channels[_cid].fromBalance) - _fromToDelta < 0) ||
            (int(channels[_cid].toBalance) + _fromToDelta < 0))
        {
            throw;
        }
    }

    function assertHash(bytes32 _data, bytes32 _hash)
        internal
    {
        if (getHash(_data) != _hash)
        {
            throw;
        }
    }

    function assertSignedByBoth(
        uint _cid,
        bytes32 _sigHash,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
        internal
    {
        address signer = getSigner(_sigHash, _sigV, _sigR, _sigS);
        if (!(((channels[_cid].from == msg.sender) && (channels[_cid].to == signer)) ||
              ((channels[_cid].from == signer) && (channels[_cid].to == msg.sender))))
        {
            throw;
        }
    }

    function getHash(bytes32 _data)
        constant
        returns (bytes32)
    {
        return sha3(_data);
    }

    function getUpdateHash(
        uint _cid,
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance)
        constant
        returns(bytes32)
    {
        return sha3(_cid, _balanceTimestamp, _fromBalance, _toBalance);
    }

    function getHTLCHash(
        uint _cid,
        uint _balanceTimestamp,
        uint _timeout,
        bytes32 _hash,
        int _fromToDelta)
        constant
        returns(bytes32)
    {
        return sha3(_cid, _timeout, _hash, _fromToDelta);
    }

    function getSigner(
        bytes32 _sigHash,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
        constant
        returns(address)
    {
        return ecrecover(_sigHash, _sigV, _sigR, _sigS);
    }

    function createChannel(uint _cid, address _from, address _to)
    {
        assertAvailable(_cid);

        reserved[_cid] = true;
        channels[_cid] = MicropaymentsChannel(ChannelStage.Empty, _from, 0, _to, 0, 0, 0);
    }

    function getStage(uint _cid)
        constant
        returns (uint8)
    {
        return uint8(channels[_cid].stage);
    }

    function getFrom(uint _cid)
        constant
        returns (address)
    {
        return channels[_cid].from;
    }

    function getFromBalance(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].fromBalance;
    }

    function getTo(uint _cid)
        constant
        returns (address)
    {
        return channels[_cid].to;
    }

    function getToBalance(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].toBalance;
    }

    function getBalanceTimestamp(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].balanceTimestamp;
    }

    function getClosingBlockNumber(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].closingBlockNumber;
    }

    function openChannel(uint _cid)
    {
        assertOnlyFrom(_cid);
        assertAtStage(_cid, ChannelStage.Empty);

        channels[_cid].stage = ChannelStage.PartiallyConfirmed;
        channels[_cid].fromBalance = msg.value;
    }

    function confirmChannel(uint _cid)
    {
        assertOnlyTo(_cid);
        assertAtStage(_cid, ChannelStage.PartiallyConfirmed);

        channels[_cid].stage = ChannelStage.Confirmed;
        channels[_cid].toBalance = msg.value;
    }

    function requestClosingChannel(uint _cid)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.PartiallyConfirmed, ChannelStage.Confirmed);

        if (channels[_cid].stage == ChannelStage.PartiallyConfirmed)
        {
            channels[_cid].stage = ChannelStage.Closed;
        }
        else
        {
            channels[_cid].stage = ChannelStage.Closing;
            channels[_cid].closingBlockNumber = block.number + closingDelay;
        }
    }

    function closeChannel(uint _cid)
    {
        assertOnlyParticipants(_cid);
        assertAtStage(_cid, ChannelStage.Closing);
        assertReadyToClose(_cid);

        channels[_cid].stage = ChannelStage.Closed;
    }

    function withdrawFrom(uint _cid)
    {
        assertOnlyFrom(_cid);
        assertAtStage(_cid, ChannelStage.Closed);

        uint balance = channels[_cid].fromBalance;
        channels[_cid].fromBalance = 0;
        channels[_cid].from.send(balance);
    }

    function withdrawTo(uint _cid)
    {
        assertOnlyTo(_cid);
        assertAtStage(_cid, ChannelStage.Closed);

        uint balance = channels[_cid].toBalance;
        channels[_cid].toBalance = 0;
        channels[_cid].to.send(balance);
    }

    function updateChannelState(
        uint _cid,
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.Confirmed, ChannelStage.Closing);
        assertYoungerBalance(_cid, _balanceTimestamp);
        assertSaneBalance(_cid, _fromBalance, _toBalance);
        assertSignedByBoth(_cid, getUpdateHash(_cid, _balanceTimestamp, _fromBalance, _toBalance), _sigV, _sigR, _sigS);

        channels[_cid].balanceTimestamp = _balanceTimestamp;
        channels[_cid].fromBalance = _fromBalance;
        channels[_cid].toBalance = _toBalance;
    }

    function resolveHTLC(
        uint _cid,
        uint _balanceTimestamp,
        uint _timeout,
        bytes32 _hash,
        int _fromToDelta,
        bytes32 _data,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.Confirmed, ChannelStage.Closing);
        assertMatchingBalance(_cid, _balanceTimestamp);
        assertStillValid(_timeout);
        assertSaneHTLC(_cid, _fromToDelta);
        assertHash(_data, _hash);
        assertSignedByBoth(_cid, getHTLCHash(_cid, _balanceTimestamp, _timeout, _hash, _fromToDelta), _sigV, _sigR, _sigS);

        channels[_cid].fromBalance = uint(int(channels[_cid].fromBalance) - _fromToDelta);
        channels[_cid].toBalance = uint(int(channels[_cid].toBalance) + _fromToDelta);
    }
}

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


fix quota check

fix quota check

pragma solidity ^0.4.18;

/// @title The interface of system config
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
interface SysConfigInterface {
    /// @notice Get delay block number before validate
    function getDelayBlockNumber() public view returns (uint);

    /// @notice Whether check permission in the system or not, true represents check and false represents don't check.
    function getPermissionCheck() public view returns (bool);

    /// @notice Whether check quota in the system or not, true represents check and false represents don't check.
    function getQuotaCheck() public view returns (bool);

    /// @notice The name of current chain
    function getChainName() public view returns (string);
    /// @notice Update current chain name
    function setChainName(string) public;

    /// @notice The id of current chain
    function getChainId() public view returns (uint32);

    /// @notice The operator of current chain
    function getOperator() public view returns (string);
    /// @notice Update current operator
    function setOperator(string) public;

    /// @notice Current operator's website URL
    function getWebsite() public view returns (string);
    /// @notice Update current operator's website URL
    function setWebsite(string) public;

    /// @notice The interval time for creating a block (milliseconds)
    function getBlockInterval() public view returns (uint64);
}

/// @title System config contract
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
contract SysConfig is SysConfigInterface {

    enum EconomicalModel { Quota, Charge }

    /// @notice only chain_name, operator, website can be updated
    uint delay_block_number;
    bool check_permission;
    bool check_quota;
    string chain_name;
    uint32 chain_id;
    string operator;
    string website;
    uint64 block_interval;
    EconomicalModel economicalModel;

    /// @notice Setup
    function SysConfig(
        uint _delayBlockNumber,
        bool _checkPermission,
        bool _checkQuota,
        string _chainName,
        uint32 _chainId,
        string _operator,
        string _website,
        uint64 _blockInterval,
        EconomicalModel _economical
    )
        public
    {
        delay_block_number = _delayBlockNumber;
        check_permission = _checkPermission;
        check_quota = _checkQuota;
        chain_name = _chainName;
        chain_id = _chainId;
        operator = _operator;
        website = _website;
        block_interval = _blockInterval;
        economicalModel = _economical;
    }

    function getDelayBlockNumber() public view returns (uint) {
        return delay_block_number;
    }

    function getPermissionCheck() public view returns (bool) {
        return check_permission && (economicalModel == EconomicalModel.Quota);
    }

    function getQuotaCheck() public view returns (bool) {
        return check_quota && (economicalModel == EconomicalModel.Quota);
    }

    function getChainName() public view returns (string) {
        return chain_name;
    }

    function getChainId() public view returns (uint32) {
        return chain_id;
    }

    function getOperator() public view returns (string) {
        return operator;
    }

    function getWebsite() public view returns (string) {
        return website;
    }

    function getBlockInterval() public view returns (uint64) {
        return block_interval;
    }

    function getEconomicalModel() public view returns (EconomicalModel) {
        return economicalModel;
    }

    function setOperator(string _operator) public {
        operator = _operator;
    }

    function setWebsite(string _website) public {
        website = _website;
    }

    function setChainName(string _chainName) public {
        chain_name = _chainName;
    }
}

pragma solidity ^0.4.18;

/// @title The interface of system config
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
interface SysConfigInterface {
    /// @notice Get delay block number before validate
    function getDelayBlockNumber() public view returns (uint);

    /// @notice Whether check permission in the system or not, true represents check and false represents don't check.
    function getPermissionCheck() public view returns (bool);

    /// @notice Whether check quota in the system or not, true represents check and false represents don't check.
    function getQuotaCheck() public view returns (bool);

    /// @notice The name of current chain
    function getChainName() public view returns (string);
    /// @notice Update current chain name
    function setChainName(string) public;

    /// @notice The id of current chain
    function getChainId() public view returns (uint32);

    /// @notice The operator of current chain
    function getOperator() public view returns (string);
    /// @notice Update current operator
    function setOperator(string) public;

    /// @notice Current operator's website URL
    function getWebsite() public view returns (string);
    /// @notice Update current operator's website URL
    function setWebsite(string) public;

    /// @notice The interval time for creating a block (milliseconds)
    function getBlockInterval() public view returns (uint64);
}

/// @title System config contract
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
contract SysConfig is SysConfigInterface {

    enum EconomicalModel { Quota, Charge }

    /// @notice only chain_name, operator, website can be updated
    uint delay_block_number;
    bool check_permission;
    bool check_quota;
    string chain_name;
    uint32 chain_id;
    string operator;
    string website;
    uint64 block_interval;
    EconomicalModel economicalModel;

    /// @notice Setup
    function SysConfig(
        uint _delayBlockNumber,
        bool _checkPermission,
        bool _checkQuota,
        string _chainName,
        uint32 _chainId,
        string _operator,
        string _website,
        uint64 _blockInterval,
        EconomicalModel _economical
    )
        public
    {
        delay_block_number = _delayBlockNumber;
        check_permission = _checkPermission;
        check_quota = _checkQuota;
        chain_name = _chainName;
        chain_id = _chainId;
        operator = _operator;
        website = _website;
        block_interval = _blockInterval;
        economicalModel = _economical;
    }

    function getDelayBlockNumber() public view returns (uint) {
        return delay_block_number;
    }

    function getPermissionCheck() public view returns (bool) {
        return check_permission;
    }

    function getQuotaCheck() public view returns (bool) {
        return check_quota;
    }

    function getChainName() public view returns (string) {
        return chain_name;
    }

    function getChainId() public view returns (uint32) {
        return chain_id;
    }

    function getOperator() public view returns (string) {
        return operator;
    }

    function getWebsite() public view returns (string) {
        return website;
    }

    function getBlockInterval() public view returns (uint64) {
        return block_interval;
    }

    function getEconomicalModel() public view returns (EconomicalModel) {
        return economicalModel;
    }

    function setOperator(string _operator) public {
        operator = _operator;
    }

    function setWebsite(string _website) public {
        website = _website;
    }

    function setChainName(string _chainName) public {
        chain_name = _chainName;
    }
}


solc > 0.4.24

solc > 0.4.24

pragma solidity >0.4.24;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  constructor() public {
    owner = msg.sender;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

pragma solidity >=0.5.0;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  constructor() public {
    owner = msg.sender;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}


Token burn() - add a Transfer event to 0x0

We want to see these events in Etherscan, so we will also add a Transfer event to 0x0.
Closes https://github.com/raiden-network/raiden-token/issues/71

pragma solidity ^0.4.11;

import './ERC223ReceivingContract.sol';

/// @title Base Token contract - Functions to be implemented by token contracts.
contract Token {
    /*
     * Implements ERC 20 standard.
     * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md
     * https://github.com/ethereum/EIPs/issues/20
     *
     *  Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
     *  https://github.com/ethereum/EIPs/issues/223
     */

    /*
     * This is a slight change to the ERC20 base standard.
     * function totalSupply() constant returns (uint256 supply);
     * is replaced with:
     * uint256 public totalSupply;
     * This automatically creates a getter function for the totalSupply.
     * This is moved to the base contract since public getter functions are not
     * currently recognised as an implementation of the matching abstract
     * function by the compiler.
     */
    uint256 public totalSupply;

    /*
     * ERC 20
     */
    function balanceOf(address _owner) constant returns (uint256 balance);
    function transfer(address _to, uint256 _value) returns (bool success);
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
    function approve(address _spender, uint256 _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint256 remaining);

    /*
     * ERC 223
     */
    function transfer(address _to, uint256 _value, bytes _data) returns (bool success);

    /*
     * Events
     */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

/// @title Standard token contract - Standard token implementation.
contract StandardToken is Token {

    /*
     * Data structures
     */
    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;

    /*
     * Public functions
     */
    /// @notice Send `_value` tokens to `_to` from `msg.sender`.
    /// @dev Transfers sender's tokens to a given address. Returns success.
    /// @param _to Address of token receiver.
    /// @param _value Number of tokens to transfer.
    /// @return Returns success of function call.
    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != 0x0);
        require(_to != address(this));
        require(balances[msg.sender] >= _value);
        require(balances[_to] + _value >= balances[_to]);

        balances[msg.sender] -= _value;
        balances[_to] += _value;

        Transfer(msg.sender, _to, _value);

        return true;
    }

    /// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger
    /// tokenFallback if sender is a contract.
    /// @dev Function that is called when a user or another contract wants to transfer funds.
    /// @param _to Address of token receiver.
    /// @param _value Number of tokens to transfer.
    /// @param _data Data to be sent to tokenFallback
    /// @return Returns success of function call.
    function transfer(
        address _to,
        uint256 _value,
        bytes _data)
        public
        returns (bool)
    {
        require(transfer(_to, _value));

        uint codeLength;

        assembly {
            // Retrieve the size of the code on target address, this needs assembly.
            codeLength := extcodesize(_to)
        }

        if (codeLength > 0) {
            ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
            receiver.tokenFallback(msg.sender, _value, _data);
        }

        return true;
    }

    /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed.
    /// @dev Allows for an approved third party to transfer tokens from one
    /// address to another. Returns success.
    /// @param _from Address from where tokens are withdrawn.
    /// @param _to Address to where tokens are sent.
    /// @param _value Number of tokens to transfer.
    /// @return Returns success of function call.
    function transferFrom(address _from, address _to, uint256 _value)
        public
        returns (bool)
    {
        require(_from != 0x0);
        require(_to != 0x0);
        require(_to != address(this));
        require(balances[_from] >= _value);
        require(allowed[_from][msg.sender] >= _value);
        require(balances[_to] + _value >= balances[_to]);

        balances[_to] += _value;
        balances[_from] -= _value;
        allowed[_from][msg.sender] -= _value;

        Transfer(_from, _to, _value);

        return true;
    }

    /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address.
    /// @dev Sets approved amount of tokens for spender. Returns success.
    /// @param _spender Address of allowed account.
    /// @param _value Number of approved tokens.
    /// @return Returns success of function call.
    function approve(address _spender, uint256 _value) public returns (bool) {
        require(_spender != 0x0);
        require(_value > 0);

        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /*
     * Read functions
     */
    /// @dev Returns number of allowed tokens that a spender can transfer in
    /// behalf of a token owner.
    /// @param _owner Address of token owner.
    /// @param _spender Address of token spender.
    /// @return Returns remaining allowance for spender.
    function allowance(address _owner, address _spender)
        constant
        public
        returns (uint256)
    {
        return allowed[_owner][_spender];
    }

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

/// @title Custom Token
contract CustomToken is StandardToken {

    /*
     *  Terminology:
     *  1 token unit = Tei
     *  1 token = TKN = Tei * multiplier
     *  multiplier set from token's number of decimals (i.e. 10**decimals)
     */

    /*
     *  Token metadata
     */
    string constant public name = "The Token";
    string constant public symbol = "TKN";
    uint8 constant public decimals = 18;
    uint constant multiplier = 10**uint(decimals);

    address public owner;
    address public auction_address;

    event Deployed(
        address indexed _auction,
        uint indexed _total_supply,
        uint indexed _auction_supply
    );
    event Burnt(
        address indexed _receiver,
        uint indexed _num,
        uint indexed _total_supply
    );

    /*
     *  Public functions
     */
    /// @dev Contract constructor function sets dutch auction contract address
    /// and assigns all tokens to dutch auction.
    /// @param auction Address of dutch auction contract.
    /// @param initial_supply Number of initially provided token units (Tei).
    /// @param owners Array of addresses receiving preassigned tokens.
    /// @param tokens Array of preassigned token units (Tei).
    function CustomToken(
        address auction,
        uint initial_supply,
        address[] owners,
        uint[] tokens)
        public
    {
        // Auction address should not be null.
        require(auction != 0x0);
        require(owners.length == tokens.length);
        // Initial supply is in Tei
        require(initial_supply > multiplier);

        owner = msg.sender;
        auction_address = auction;

        // Total supply of Tei at deployment
        totalSupply = initial_supply;

        // Preallocate tokens to beneficiaries
        uint prealloc_tokens;
        for (uint i = 0; i < owners.length; i++) {
            // Address should not be null.
            require(owners[i] != 0x0);
            require(tokens[i] > 0);
            require(balances[owners[i]] + tokens[i] > balances[owners[i]]);
            require(prealloc_tokens + tokens[i] > prealloc_tokens);

            balances[owners[i]] += tokens[i];
            prealloc_tokens += tokens[i];
            Transfer(0, owners[i], tokens[i]);
        }

        balances[auction_address] = totalSupply - prealloc_tokens;
        Transfer(0, auction_address, balances[auction]);

        Deployed(auction_address, totalSupply, balances[auction]);

        assert(balances[auction_address] > 0);
        assert(balances[auction_address] < totalSupply);
        assert(totalSupply == balances[auction_address] + prealloc_tokens);
    }

    /// @notice Allows `msg.sender` to simply destroy `num` token units (Tei),
    /// without receiving the corresponding amount of ether. This means the total
    /// token supply will decrease.
    /// @dev Allows to destroy token units (Tei) without receiving the
    /// corresponding amount of ether.
    /// @param num Number of token units (Tei) to burn.
    function burn(uint num) public {
        require(num > 0);
        require(balances[msg.sender] >= num);
        require(totalSupply >= num);

        uint pre_balance = balances[msg.sender];

        balances[msg.sender] -= num;
        totalSupply -= num;
        Burnt(msg.sender, num, totalSupply);
        Transfer(msg.sender, 0x0, num);

        assert(balances[msg.sender] == pre_balance - num);
    }

}

pragma solidity ^0.4.11;

import './ERC223ReceivingContract.sol';

/// @title Base Token contract - Functions to be implemented by token contracts.
contract Token {
    /*
     * Implements ERC 20 standard.
     * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md
     * https://github.com/ethereum/EIPs/issues/20
     *
     *  Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
     *  https://github.com/ethereum/EIPs/issues/223
     */

    /*
     * This is a slight change to the ERC20 base standard.
     * function totalSupply() constant returns (uint256 supply);
     * is replaced with:
     * uint256 public totalSupply;
     * This automatically creates a getter function for the totalSupply.
     * This is moved to the base contract since public getter functions are not
     * currently recognised as an implementation of the matching abstract
     * function by the compiler.
     */
    uint256 public totalSupply;

    /*
     * ERC 20
     */
    function balanceOf(address _owner) constant returns (uint256 balance);
    function transfer(address _to, uint256 _value) returns (bool success);
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
    function approve(address _spender, uint256 _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint256 remaining);

    /*
     * ERC 223
     */
    function transfer(address _to, uint256 _value, bytes _data) returns (bool success);

    /*
     * Events
     */
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

/// @title Standard token contract - Standard token implementation.
contract StandardToken is Token {

    /*
     * Data structures
     */
    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;

    /*
     * Public functions
     */
    /// @notice Send `_value` tokens to `_to` from `msg.sender`.
    /// @dev Transfers sender's tokens to a given address. Returns success.
    /// @param _to Address of token receiver.
    /// @param _value Number of tokens to transfer.
    /// @return Returns success of function call.
    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != 0x0);
        require(_to != address(this));
        require(balances[msg.sender] >= _value);
        require(balances[_to] + _value >= balances[_to]);

        balances[msg.sender] -= _value;
        balances[_to] += _value;

        Transfer(msg.sender, _to, _value);

        return true;
    }

    /// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger
    /// tokenFallback if sender is a contract.
    /// @dev Function that is called when a user or another contract wants to transfer funds.
    /// @param _to Address of token receiver.
    /// @param _value Number of tokens to transfer.
    /// @param _data Data to be sent to tokenFallback
    /// @return Returns success of function call.
    function transfer(
        address _to,
        uint256 _value,
        bytes _data)
        public
        returns (bool)
    {
        require(transfer(_to, _value));

        uint codeLength;

        assembly {
            // Retrieve the size of the code on target address, this needs assembly.
            codeLength := extcodesize(_to)
        }

        if (codeLength > 0) {
            ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
            receiver.tokenFallback(msg.sender, _value, _data);
        }

        return true;
    }

    /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed.
    /// @dev Allows for an approved third party to transfer tokens from one
    /// address to another. Returns success.
    /// @param _from Address from where tokens are withdrawn.
    /// @param _to Address to where tokens are sent.
    /// @param _value Number of tokens to transfer.
    /// @return Returns success of function call.
    function transferFrom(address _from, address _to, uint256 _value)
        public
        returns (bool)
    {
        require(_from != 0x0);
        require(_to != 0x0);
        require(_to != address(this));
        require(balances[_from] >= _value);
        require(allowed[_from][msg.sender] >= _value);
        require(balances[_to] + _value >= balances[_to]);

        balances[_to] += _value;
        balances[_from] -= _value;
        allowed[_from][msg.sender] -= _value;

        Transfer(_from, _to, _value);

        return true;
    }

    /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address.
    /// @dev Sets approved amount of tokens for spender. Returns success.
    /// @param _spender Address of allowed account.
    /// @param _value Number of approved tokens.
    /// @return Returns success of function call.
    function approve(address _spender, uint256 _value) public returns (bool) {
        require(_spender != 0x0);
        require(_value > 0);

        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /*
     * Read functions
     */
    /// @dev Returns number of allowed tokens that a spender can transfer in
    /// behalf of a token owner.
    /// @param _owner Address of token owner.
    /// @param _spender Address of token spender.
    /// @return Returns remaining allowance for spender.
    function allowance(address _owner, address _spender)
        constant
        public
        returns (uint256)
    {
        return allowed[_owner][_spender];
    }

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

/// @title Custom Token
contract CustomToken is StandardToken {

    /*
     *  Terminology:
     *  1 token unit = Tei
     *  1 token = TKN = Tei * multiplier
     *  multiplier set from token's number of decimals (i.e. 10**decimals)
     */

    /*
     *  Token metadata
     */
    string constant public name = "The Token";
    string constant public symbol = "TKN";
    uint8 constant public decimals = 18;
    uint constant multiplier = 10**uint(decimals);

    address public owner;
    address public auction_address;

    event Deployed(
        address indexed _auction,
        uint indexed _total_supply,
        uint indexed _auction_supply
    );
    event Burnt(
        address indexed _receiver,
        uint indexed _num,
        uint indexed _total_supply
    );

    /*
     *  Public functions
     */
    /// @dev Contract constructor function sets dutch auction contract address
    /// and assigns all tokens to dutch auction.
    /// @param auction Address of dutch auction contract.
    /// @param initial_supply Number of initially provided token units (Tei).
    /// @param owners Array of addresses receiving preassigned tokens.
    /// @param tokens Array of preassigned token units (Tei).
    function CustomToken(
        address auction,
        uint initial_supply,
        address[] owners,
        uint[] tokens)
        public
    {
        // Auction address should not be null.
        require(auction != 0x0);
        require(owners.length == tokens.length);
        // Initial supply is in Tei
        require(initial_supply > multiplier);

        owner = msg.sender;
        auction_address = auction;

        // Total supply of Tei at deployment
        totalSupply = initial_supply;

        // Preallocate tokens to beneficiaries
        uint prealloc_tokens;
        for (uint i = 0; i < owners.length; i++) {
            // Address should not be null.
            require(owners[i] != 0x0);
            require(tokens[i] > 0);
            require(balances[owners[i]] + tokens[i] > balances[owners[i]]);
            require(prealloc_tokens + tokens[i] > prealloc_tokens);

            balances[owners[i]] += tokens[i];
            prealloc_tokens += tokens[i];
            Transfer(0, owners[i], tokens[i]);
        }

        balances[auction_address] = totalSupply - prealloc_tokens;
        Transfer(0, auction_address, balances[auction]);

        Deployed(auction_address, totalSupply, balances[auction]);

        assert(balances[auction_address] > 0);
        assert(balances[auction_address] < totalSupply);
        assert(totalSupply == balances[auction_address] + prealloc_tokens);
    }

    /// @notice Allows `msg.sender` to simply destroy `num` token units (Tei),
    /// without receiving the corresponding amount of ether. This means the total
    /// token supply will decrease.
    /// @dev Allows to destroy token units (Tei) without receiving the
    /// corresponding amount of ether.
    /// @param num Number of token units (Tei) to burn.
    function burn(uint num) public {
        require(num > 0);
        require(balances[msg.sender] >= num);
        require(totalSupply >= num);

        uint pre_balance = balances[msg.sender];

        balances[msg.sender] -= num;
        totalSupply -= num;
        Burnt(msg.sender, num, totalSupply);

        assert(balances[msg.sender] == pre_balance - num);
    }

}


Added first empty order for liability market

pragma solidity ^0.4.4;
import 'dao/Liability.sol';
import 'common/Object.sol';
import 'token/ERC20.sol';
import './MarketHeap.sol';

/**
 * @title Liability marketplace
 */
contract LiabilityMarket is Object, MarketHeap {
    // Market name
    string public name;

    // Market token
    ERC20 public token;

    /**
     * @dev Market constructor
     * @param _name Market name
     * @param _token Makret token
     */
    function LiabilityMarket(string _name, address _token) {
        name  = _name;
        token = ERC20(_token);
        // Put empty oreder with zero index
        orders[orders.length++].closed = true;
    }

    struct Order {
        address[] beneficiary;
        address[] promisee;
        address   promisor;
        bool      closed;
    }

    Order[] orders;

    /**
     * @dev Get order by index
     * @param _i Order index
     * @return Order fields
     */
    function getOrder(uint256 _i) constant returns (address[], address[], address, bool) {
        var o = orders[_i];
        return (o.beneficiary, o.promisee, o.promisor, o.closed);
    }

    /**
     * @dev Get account order ids
     */
    mapping(address => uint[]) public ordersOf;

    event OpenAskOrder(uint256 indexed order);
    event OpenBidOrder(uint256 indexed order);
    event CloseAskOrder(uint256 indexed order);
    event CloseBidOrder(uint256 indexed order);

    event AskOrderCandidates(uint256 indexed order,
                             address indexed beneficiary,
                             address indexed promisee);

    event NewLiability(address indexed liability);

    /**
     * @dev Make a limit order to sell liability
     * @param _promisee Liability beneficiary
     * @param _price Liability price
     * @notice Sender is promisee of liability
     */
    function limitSell(address _promisee, uint256 _price) {
        var id = orders.length++;

        // Store price
        priceOf[id] = _price;
        // Append bid
        putBid(id);
        // Store template
        orders[id].beneficiary.push(msg.sender);
        orders[id].promisee.push(_promisee);

        ordersOf[msg.sender].push(id);
        OpenBidOrder(id);
    }

    /**
     * @dev Make a limit order to buy liability
     * @param _price Liability price
     * @notice Sender is promisor of liability
     */
    function limitBuy(uint256 _price) {
        var id = orders.length++;

        // Store price
        priceOf[id] = _price;
        // Append ask
        putAsk(id);
        // Store template
        orders[id].promisor = msg.sender;

        // Lock tokens
        if (!token.transferFrom(msg.sender, this, _price))
            throw;

        ordersOf[msg.sender].push(id);
        OpenAskOrder(id);
    }

    /**
     * @dev Sell liability
     * @param _id Order index
     * @param _promisee Promisee candidate
     */
    function sellAt(uint256 _id, address _promisee) {
        var order = orders[_id];
        if (_id >= orders.length || order.closed) throw;

        order.beneficiary.push(msg.sender);
        order.promisee.push(_promisee);

        AskOrderCandidates(_id, msg.sender, _promisee);
    }

    /**
     * @dev Confirm liability sell
     * @param _id Order index
     * @param _candidates Confirmed candidates
     */
    function sellConfirm(uint256 _id, uint256 _candidates) {
        var o = orders[_id];
        if (_id >= orders.length || o.closed) throw;

        getAsk(orderAskOf[_id]);

        if (o.promisor != msg.sender) throw;
        if (o.beneficiary[_candidates] == 0) throw;

        if (!runLiability(o.beneficiary[_candidates],
                          o.promisee[_candidates],
                          o.promisor,
                          priceOf[_id])) throw;

        CloseAskOrder(_id);
    }

    /**
     * @dev Buy liability
     * @param _id Order index
     */
    function buyAt(uint256 _id) {
        var o = orders[_id];
        if (_id >= orders.length || o.closed) throw;

        getBid(orderBidOf[_id]);
        o.promisor = msg.sender;

        if (!token.transferFrom(msg.sender, this, priceOf[_id]))
            throw;

        if (!runLiability(o.beneficiary[0],
                          o.promisee[0],
                          o.promisor,
                          priceOf[_id])) throw;

        CloseBidOrder(_id);
    }

    function runLiability(
        address _beneficiary,
        address _promisee,
        address _promisor,
        uint256 _price
    ) internal returns (bool) {
        var l = new Liability(_promisor, _promisee, token, _price);
        l.setOwner(_beneficiary);

        if (!token.transfer(l, _price)) throw;
        if (!l.call.value(l.gasbase() * tx.gasprice)()) throw;

        NewLiability(l);
        return true;
    }

    function () payable {}
}

pragma solidity ^0.4.4;
import 'dao/Liability.sol';
import 'common/Object.sol';
import 'token/ERC20.sol';
import './MarketHeap.sol';

/**
 * @title Liability marketplace
 */
contract LiabilityMarket is Object, MarketHeap {
    // Market name
    string public name;

    // Market token
    ERC20 public token;

    /**
     * @dev Market constructor
     * @param _name Market name
     * @param _token Makret token
     */
    function LiabilityMarket(string _name, address _token) {
        name  = _name;
        token = ERC20(_token);
    }

    struct Order {
        address[] beneficiary;
        address[] promisee;
        address   promisor;
        bool      closed;
    }

    Order[] orders;

    /**
     * @dev Get order by index
     * @param _i Order index
     * @return Order fields
     */
    function getOrder(uint256 _i) constant returns (address[], address[], address, bool) {
        var o = orders[_i];
        return (o.beneficiary, o.promisee, o.promisor, o.closed);
    }

    /**
     * @dev Get account order ids
     */
    mapping(address => uint[]) public ordersOf;

    event OpenAskOrder(uint256 indexed order);
    event OpenBidOrder(uint256 indexed order);
    event CloseAskOrder(uint256 indexed order);
    event CloseBidOrder(uint256 indexed order);

    event AskOrderCandidates(uint256 indexed order,
                             address indexed beneficiary,
                             address indexed promisee);

    event NewLiability(address indexed liability);

    /**
     * @dev Make a limit order to sell liability
     * @param _promisee Liability beneficiary
     * @param _price Liability price
     * @notice Sender is promisee of liability
     */
    function limitSell(address _promisee, uint256 _price) {
        var id = orders.length++;

        // Store price
        priceOf[id] = _price;
        // Append bid
        putBid(id);
        // Store template
        orders[id].beneficiary.push(msg.sender);
        orders[id].promisee.push(_promisee);

        ordersOf[msg.sender].push(id);
        OpenBidOrder(id);
    }

    /**
     * @dev Make a limit order to buy liability
     * @param _price Liability price
     * @notice Sender is promisor of liability
     */
    function limitBuy(uint256 _price) {
        var id = orders.length++;

        // Store price
        priceOf[id] = _price;
        // Append ask
        putAsk(id);
        // Store template
        orders[id].promisor = msg.sender;

        // Lock tokens
        if (!token.transferFrom(msg.sender, this, _price))
            throw;

        ordersOf[msg.sender].push(id);
        OpenAskOrder(id);
    }

    /**
     * @dev Sell liability
     * @param _id Order index
     * @param _promisee Promisee candidate
     */
    function sellAt(uint256 _id, address _promisee) {
        var order = orders[_id];
        if (_id >= orders.length || order.closed) throw;

        order.beneficiary.push(msg.sender);
        order.promisee.push(_promisee);

        AskOrderCandidates(_id, msg.sender, _promisee);
    }

    /**
     * @dev Confirm liability sell
     * @param _id Order index
     * @param _candidates Confirmed candidates
     */
    function sellConfirm(uint256 _id, uint256 _candidates) {
        var o = orders[_id];
        if (_id >= orders.length || o.closed) throw;

        getAsk(orderAskOf[_id]);

        if (o.promisor != msg.sender) throw;
        if (o.beneficiary[_candidates] == 0) throw;

        if (!runLiability(o.beneficiary[_candidates],
                          o.promisee[_candidates],
                          o.promisor,
                          priceOf[_id])) throw;

        CloseAskOrder(_id);
    }

    /**
     * @dev Buy liability
     * @param _id Order index
     */
    function buyAt(uint256 _id) {
        var o = orders[_id];
        if (_id >= orders.length || o.closed) throw;

        getBid(orderBidOf[_id]);
        o.promisor = msg.sender;

        if (!token.transferFrom(msg.sender, this, priceOf[_id]))
            throw;

        if (!runLiability(o.beneficiary[0],
                          o.promisee[0],
                          o.promisor,
                          priceOf[_id])) throw;

        CloseBidOrder(_id);
    }

    function runLiability(
        address _beneficiary,
        address _promisee,
        address _promisor,
        uint256 _price
    ) internal returns (bool) {
        var l = new Liability(_promisor, _promisee, token, _price);
        l.setOwner(_beneficiary);

        if (!token.transfer(l, _price)) throw;
        if (!l.call.value(l.gasbase() * tx.gasprice)()) throw;

        NewLiability(l);
        return true;
    }

    function () payable {}
}