remove vars

remove vars

pragma solidity ^0.4.8;

import "./SafeMath.sol";
import "./ERC20.sol";
import "./PeaceRelay.sol";
import "./RLP.sol";
import "./Ownable.sol";

contract ETCToken is ERC20, SafeMath, Ownable {
  using RLP for RLP.RLPItem;
  using RLP for RLP.Iterator;
  using RLP for bytes;

  // Public variables of the token
  string public name;
  string public symbol;
  uint8 public decimals;    //How many decimals to show.
  string public version = 'v0.1';
  uint public totalSupply;
  uint public DEPOSIT_GAS_MINIMUM=100000; //should be constant
  bytes4 public LOCK_FUNCTION_SIG=0xf435f5a7;

  mapping(address => uint) balances;
  mapping (address => mapping (address => uint)) allowed;
  PeaceRelay public ETCRelay;
  address etcLockingAddr; //maybe rename to EthLockingContract

  struct Transaction {
    uint nonce;
    uint gasPrice;
    uint gasLimit;
    address to;
    uint value;
    bytes data;
  }

  event Burn(address indexed from, address indexed etcAddr, uint indexed value);
  event Mint(address indexed to, uint value);

  function ETCToken(address peaceRelayAddr)
  {
    totalSupply = 0;
    name = 'ETCToken';        // Set the name for display purposes
    symbol = 'ETC';                       // Set the symbol for display purposes
    decimals = 9;                        // Amount of decimals for display purposes
    ETCRelay = PeaceRelay(peaceRelayAddr);
  }

  function setETCLockingAddr(address _etcLockingAddr) onlyOwner returns (bool) {
  	etcLockingAddr = _etcLockingAddr;
  	return true;
  }

  function ownerCredit(address addr, uint _amount) onlyOwner returns (bool){
  	balances[addr] = safeAdd(balances[addr], _amount);
  	totalSupply = safeAdd(totalSupply, _amount);
  	return true;
  }

  function mint(bytes rlpTxStack, uint[] txIndex, bytes prefix, bytes rlpTransaction, bytes32 blockHash) returns (bool success) {
  	if (ETCRelay.checkTxProof(blockHash, rlpTxStack, txIndex, prefix, rlpTransaction)) {
      //  checkTxProof(bytes32 blockHash, bytes rlpStack, uint[] indexes, bytes rlpTransaction)
      Transaction memory tx = getTransactionDetails(rlpTransaction);
      bytes4 functionSig = getSig(tx.data);

      if (functionSig != LOCK_FUNCTION_SIG) throw;
      if (tx.to != etcLockingAddr) throw;
      if (tx.gasLimit < DEPOSIT_GAS_MINIMUM) throw;

      address newAddress = getAddress(tx.data);

      totalSupply = safeAdd(totalSupply, tx.value);
      balances[newAddress] = safeAdd(balances[newAddress], tx.value);
      Mint(newAddress, tx.value);
      return true;
    }
    return false;
  }

  function burn(uint256 _value, address etcAddr) returns (bool success) {
    // safeSub already has throw, so no need to throw
    balances[msg.sender] = safeSub(balances[msg.sender], _value) ;
    totalSupply = safeSub(totalSupply, _value);
    Burn(msg.sender, etcAddr, _value);
    return true;
  }

  function transfer(address _to, uint _value) returns (bool success) {
    // safeSub already has throw, so no need to throw
    balances[msg.sender] = safeSub(balances[msg.sender], _value);
    balances[_to] = safeAdd(balances[_to], _value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

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

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

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

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

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

	// Non-payable unnamed function prevents Ether from being sent accidentally
	function () {}

  // HELPER FUNCTIONS
  function getSig(bytes b) internal returns (bytes4 functionSig) {
    if (b.length < 32) throw;
    uint tmp = 0;
    for (uint i=0; i < 4; i++)
       tmp = tmp*(2**8)+uint8(b[i]);
    return bytes4(tmp);
  }

  //grabs the first input from some function data
  //and implies that it is an address
  function getAddress(bytes b) constant returns (address a) {
    if (b.length < 36) return address(0);
    assembly {
      let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
      a := and(mask, mload(add(b, 36)))
      //36 is the offset of the first param of the data, if encoded properly.
      //4 bytes for the function signature, and 32 for the address.
    }
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function getTransactionDetails(bytes rlpTransaction) constant internal returns (Transaction memory tx) {
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(36);
    for (uint i = 0; i < 36; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 103 + i];
    }
    return tx;
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function testGetTransactionDetails(bytes rlpTransaction) constant returns (uint, uint, address, bytes) {
    Transaction memory tx;
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(36);
    for (uint i = 0; i < 36; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 103 + i];
    }
    return (tx.gasPrice, tx.gasLimit, tx.to, tx.data);
  }
}

pragma solidity ^0.4.8;

import "./SafeMath.sol";
import "./ERC20.sol";
import "./PeaceRelay.sol";
import "./RLP.sol";
import "./Ownable.sol";

contract ETCToken is ERC20, SafeMath, Ownable {
  using RLP for RLP.RLPItem;
  using RLP for RLP.Iterator;
  using RLP for bytes;

  // Public variables of the token
  string public name;
  string public symbol;
  uint8 public decimals;    //How many decimals to show.
  string public version = 'v0.1';
  uint public totalSupply;
  uint public DEPOSIT_GAS_MINIMUM=100000; //should be constant
  bytes4 public LOCK_FUNCTION_SIG=0xf435f5a7;

  mapping(address => uint) balances;
  mapping (address => mapping (address => uint)) allowed;
  PeaceRelay public ETCRelay;
  address etcLockingAddr; //maybe rename to EthLockingContract

  struct Transaction {
    uint nonce;
    uint gasPrice;
    uint gasLimit;
    address to;
    uint value;
    bytes data;
  }

  event Burn(address indexed from, address indexed etcAddr, uint indexed value);
  event Mint(address indexed to, uint value);

  function ETCToken(address peaceRelayAddr, uint depositGasMinimum)
  {
    totalSupply = 0;
    name = 'ETCToken';        // Set the name for display purposes
    symbol = 'ETC';                       // Set the symbol for display purposes
    decimals = 9;                        // Amount of decimals for display purposes
    ETCRelay = PeaceRelay(peaceRelayAddr);
    DEPOSIT_GAS_MINIMUM = depositGasMinimum;
  }

  function setETCLockingAddr(address _etcLockingAddr) onlyOwner returns (bool) {
  	etcLockingAddr = _etcLockingAddr;
  	return true;
  }

  function ownerCredit(address addr, uint _amount) onlyOwner returns (bool){
  	balances[addr] = safeAdd(balances[addr], _amount);
  	totalSupply = safeAdd(totalSupply, _amount);
  	return true;
  }

  function mint(bytes rlpTxStack, uint[] txIndex, bytes prefix, bytes rlpTransaction, bytes32 blockHash) returns (bool success) {
  	if (ETCRelay.checkTxProof(blockHash, rlpTxStack, txIndex, prefix, rlpTransaction)) {
      //  checkTxProof(bytes32 blockHash, bytes rlpStack, uint[] indexes, bytes rlpTransaction)
      Transaction memory tx = getTransactionDetails(rlpTransaction);
      bytes4 functionSig = getSig(tx.data);

      if (functionSig != LOCK_FUNCTION_SIG) throw;
      if (tx.to != etcLockingAddr) throw;
      if (tx.gasLimit < DEPOSIT_GAS_MINIMUM) throw;

      address newAddress = getAddress(tx.data);

      totalSupply = safeAdd(totalSupply, tx.value);
      balances[newAddress] = safeAdd(balances[newAddress], tx.value);
      Mint(newAddress, tx.value);
      return true;
    }
    return false;
  }

  function burn(uint256 _value, address etcAddr) returns (bool success) {
    // safeSub already has throw, so no need to throw
    balances[msg.sender] = safeSub(balances[msg.sender], _value) ;
    totalSupply = safeSub(totalSupply, _value);
    Burn(msg.sender, etcAddr, _value);
    return true;
  }

  function transfer(address _to, uint _value) returns (bool success) {
    // safeSub already has throw, so no need to throw
    balances[msg.sender] = safeSub(balances[msg.sender], _value);
    balances[_to] = safeAdd(balances[_to], _value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

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

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

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

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

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

	// Non-payable unnamed function prevents Ether from being sent accidentally
	function () {}

  // HELPER FUNCTIONS
  function getSig(bytes b) internal returns (bytes4 functionSig) {
    if (b.length < 32) throw;
    uint tmp = 0;
    for (uint i=0; i < 4; i++)
       tmp = tmp*(2**8)+uint8(b[i]);
    return bytes4(tmp);
  }

  //grabs the first input from some function data
  //and implies that it is an address
  function getAddress(bytes b) constant returns (address a) {
    if (b.length < 36) return address(0);
    assembly {
      let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
      a := and(mask, mload(add(b, 36)))
      //36 is the offset of the first param of the data, if encoded properly.
      //4 bytes for the function signature, and 32 for the address.
    }
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function getTransactionDetails(bytes rlpTransaction) constant internal returns (Transaction memory tx) {
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(36);
    for (uint i = 0; i < 36; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 103 + i];
    }
    return tx;
  }

  //rlpTransaction is a value at the bottom of the transaction trie.
  function testGetTransactionDetails(bytes rlpTransaction) constant returns (uint, uint, address, bytes) {
    Transaction memory tx;
    RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList();
    tx.gasPrice = list[1].toUint();
    tx.gasLimit = list[2].toUint();
    tx.to = address(list[3].toUint());
    //Ugly hard coding for now. Can only parse burn transactions.
    tx.data = new bytes(36);
    for (uint i = 0; i < 36; i++) {
      tx.data[i] = rlpTransaction[rlpTransaction.length - 103 + i];
    }
    return (tx.gasPrice, tx.gasLimit, tx.to, tx.data);
  }
}


added events

added events

pragma solidity ^0.4.4;

contract Market {
  // Participant addresses
  address[] public participants;

  // Last energy balance per participant [kWh]
  mapping (address => uint) energy_balance;

  // Total production [kWh]
  uint total_production = 0;

  // Total consumption [kWh]
  uint total_consumption = 0;

  // Total number of participants
  uint number_of_participant = 10;

  // Number of participation during a round
  uint number_of_participation = 0;

  // Retail price [$/kWh]
  uint retail_price = 100;

  // Retail price upper limit [%]
  uint upper_ratio = 166;

  // Retail price lower limit [%]
  uint lower_ratio = 50;

  // Buying price [$/kWh]
  uint buying_price = 0;

  // Selling price [$/kWh]
  uint selling_price = 0;

  // Maximum / minimum local selling price
  uint maximum_local_selling_price = (3 * retail_price) / 2;
  uint minimum_local_selling_price = retail_price / 2;

  // Minimum local buying price
  uint minimum_local_buying_price = retail_price / 2;

  // Bill per participant [$]
  mapping (address => uint) bill;

  /* **********
      Event
  *********** */

  // NOT IMPLEMENTED YET
  event energy_posted_event(address _target, uint _value);
  event market_cleared_event(uint _sell, uint _buy, uint _prod, uint _gen);
  event bill_sent_event(address _target, uint _value);

  /* **********
    Function
  *********** */

  // Add a participant to the market
  function add_participant(){
    // Add the address of the participant to the "phone book"
    participants.push(msg.sender);

    // Set participant bill to zero
    bill[msg.sender] = 0;
  }

  // Remove a participant from the market
  function remove_participant() {
    // NOT IMPLEMENTED YET
  }

  // Broadcast energy balance
  function post_energy_balance(uint amount) {
    // Set participant last energy balance
    energy_balance[msg.sender] = amount;
    energy_posted_event(msg.sender, amount);

    // Increase total production or consumption
    if (amount > 0)
      // ratio need to be a positive number, so we ABS(amount)
      total_production += - amount;
    else
      total_consumption += amount;

    // Increase number of participant for the market round
    number_of_participation += 1;
  }

  // Clear the market (set the prices and send bills)
  function clear_market() {
    // Only trigger the market when everybody has participated
    require(number_of_participation == number_of_participant);

    // Reset the market participation
    number_of_participation = 0;

    // Calculate the ratio between production and consumption
    uint ratio = total_consumption * 100 / total_production;

    // The network need more local production
    if (ratio >= upper_ratio) {
      // Local energy is at its maximum price
      selling_price = maximum_local_selling_price;

      // Buying price depends on the portion of local energy
      // Local energy price * ratio + retail price for the remaining energy
      buying_price = selling_price * 100 / ratio + retail_price - retail_price * 100 / ratio;
    }

    // The network is slowly approaching 100% local production
    // The price of buying local generation goes down to avoid back feeding
    if (ratio < upper_ratio && ratio >= lower_ratio) {
      // Linear equation joining the maximum selling price to the minimum selling price
      uint a = (maximum_local_selling_price - minimum_local_selling_price) / (upper_ratio - lower_ratio);
      uint b = minimum_local_selling_price - a * lower_ratio;
      selling_price = a * ratio + b;

      // Buying price depends on the portion of local energy and its price
      // Same equatio as previous section
      buying_price = selling_price * 100 / ratio + retail_price - retail_price * 100 / ratio;
    }

    // Local generatio is back feeding to the main grid
    if (ratio < lower_ratio) {
      // Buying and selling happen at the minimum price
      // Since retail price for generation is higher than minimum selling price
      // the market generate value for itself
      selling_price = minimum_local_selling_price;
      buying_price = minimum_local_buying_price;
    }

    // Event marked cleared
    market_cleared_event(selling_price, buying_price, total_consumption, total_production);

    // Reset total production and total consumption for this round
    total_consumption = 0;
    total_production = 0;

    // Send a bill to all the participants
    _bill_all_participants();
  }

  function _bill_all_participants() {
    // Loop over all the participants
    for (uint i = 0; i < participants.length; i++) {

      // Bill participant differently if they are prosumers or consumers
      if (energy_balance[participants[i]] > 0) {
        // Participant consumed power (energy_balance is positive)
        bill[participants[i]] += buying_price * energy_balance[participants[i]];
        bill_sent_event(participants[i], buying_price * energy_balance[participants[i]]);

      } else {
        // Participant produced energy (energy_balance is negative)
        bill[participants[i]] += selling_price * energy_balance[participants[i]];
        bill_sent_event(participants[i], buying_price * energy_balance[participants[i]]);
      }
    }
  }

  // End of the contract
}

pragma solidity ^0.4.4;

contract Market {
  // Participant addresses
  address[] public participants;

  // Last energy balance per participant [kWh]
  mapping (address => uint) energy_balance;

  // Total production [kWh]
  uint total_production = 0;

  // Total consumption [kWh]
  uint total_consumption = 0;

  // Total number of participants
  uint number_of_participant = 10;

  // Number of participation during a round
  uint number_of_participation = 0;

  // Retail price [$/kWh]
  uint retail_price = 100;

  // Retail price upper limit [%]
  uint upper_ratio = 166;

  // Retail price lower limit [%]
  uint lower_ratio = 50;

  // Buying price [$/kWh]
  uint buying_price = 0;

  // Selling price [$/kWh]
  uint selling_price = 0;

  // Maximum / minimum local selling price
  uint maximum_local_selling_price = (3 * retail_price) / 2;
  uint minimum_local_selling_price = retail_price / 2;

  // Minimum local buying price
  uint minimum_local_buying_price = retail_price / 2;

  // Bill per participant [$]
  mapping (address => uint) bill;

  /* **********
      Event
  *********** */

  // NOT IMPLEMENTED YET

  /* **********
    Function
  *********** */

  // Add a participant to the market
  function add_participant(){
    // Add the address of the participant to the "phone book"
    participants.push(msg.sender);

    // Set participant bill to zero
    bill[msg.sender] = 0;
  }

  // Remove a participant from the market
  function remove_participant() {
    // NOT IMPLEMENTED YET
  }

  // Broadcast energy balance
  function post_energy_balance(uint amount) {
    // Set participant last energy balance
    energy_balance[msg.sender] = amount;

    // Increase total production or consumption
    if (amount > 0)
      // ratio need to be a positive number, so we ABS(amount)
      total_production += - amount;
    else
      total_consumption += amount;

    // Increase number of participant for the market round
    number_of_participation += 1;
  }

  // Clear the market (set the prices and send bills)
  function clear_market() {
    // Only trigger the market when everybody has participated
    require(number_of_participation == number_of_participant);

    // Reset the market participation
    number_of_participation = 0;

    // Calculate the ratio between production and consumption
    uint ratio = total_consumption * 100 / total_production;

    // The network need more local production
    if (ratio >= upper_ratio) {
      // Local energy is at its maximum price
      selling_price = maximum_local_selling_price;

      // Buying price depends on the portion of local energy
      // Local energy price * ratio + retail price for the remaining energy
      buying_price = selling_price * 100 / ratio + retail_price - retail_price * 100 / ratio;
    }

    // The network is slowly approaching 100% local production
    // The price of buying local generation goes down to avoid back feeding
    if (ratio < upper_ratio && ratio >= lower_ratio) {
      // Linear equation joining the maximum selling price to the minimum selling price
      uint a = (maximum_local_selling_price - minimum_local_selling_price) / (upper_ratio - lower_ratio);
      uint b = minimum_local_selling_price - a * lower_ratio;
      selling_price = a * ratio + b;

      // Buying price depends on the portion of local energy and its price
      // Same equatio as previous section
      buying_price = selling_price * 100 / ratio + retail_price - retail_price * 100 / ratio;
    }

    // Local generatio is back feeding to the main grid
    if (ratio < lower_ratio) {
      // Buying and selling happen at the minimum price
      // Since retail price for generation is higher than minimum selling price
      // the market generate value for itself
      selling_price = minimum_local_selling_price;
      buying_price = minimum_local_buying_price;
    }

    // Reset total production and total consumption for this round
    total_consumption = 0;
    total_production = 0;

    // Send a bill to all the participants
    bill_all_participants();
  }

  function bill_all_participants() {
    // Loop over all the participants
    for (uint i = 0; i < participants.length; i++) {

      // Bill participant differently if they are prosumers or consumers
      if (energy_balance[participants[i]] > 0) {
        // Participant consumed power (energy_balance is positive)
        bill[participants[i]] += buying_price * energy_balance[participants[i]];
      } else {
        // Participant produced energy (energy_balance is negative)
        bill[participants[i]] += selling_price * energy_balance[participants[i]];
      }
    }
  }

  // End of the contract
}


Add event declaration

Add event declaration

import "ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {
	mapping (address => uint) balances;

	function MetaCoin() {
		balances[tx.origin] = 10000;
	}

	function sendCoin(address receiver, uint amount) returns(bool sufficient) {
		if (balances[msg.sender] < amount) return false;
		balances[msg.sender] -= amount;
		balances[receiver] += amount;
		return true;
	}
	function getBalanceInEth(address addr) returns(uint){
		return ConvertLib.convert(getBalance(addr),2);
	}
	function getBalance(address addr) returns(uint) {
		return balances[addr];
	}
	event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

import "ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {
	mapping (address => uint) balances;

	function MetaCoin() {
		balances[tx.origin] = 10000;
	}

	function sendCoin(address receiver, uint amount) returns(bool sufficient) {
		if (balances[msg.sender] < amount) return false;
		balances[msg.sender] -= amount;
		balances[receiver] += amount;
		return true;
	}
	function getBalanceInEth(address addr) returns(uint){
		return ConvertLib.convert(getBalance(addr),2);
	}
  	function getBalance(address addr) returns(uint) {
    	return balances[addr];
  	}
}


submit

submit

from Tan

pragma solidity ^0.4.10;
contract Bew2Venue
{

 enum beewType {lager,stout,porter,ipa}

  struct bottle{
  string batch;
  uint256 date;
  int cost;
  int abvv;
}

function add (string _batch,int _cost ,int _abv) {
  bottle memory _bottle = bottle (_batch,block.timestamp,_cost,_abv);
  bottles.push(_bottle);
}

bottle[] public bottles;

}

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


Removed Ade: all dead warriors are left on the battlefield and can't be redeemed;

pragma solidity ^0.4.15;

import "./TokenERC20.sol";
import "./Timed.sol";
import "./SafeMathLib.sol";

contract Battle is Timed {
    using SafeMathLib for uint;

    string  public constant VERSION                 = "1.0.0";

    uint    public constant MAX_PERSIANS            = 300000 * 10**18;  // 300.000
    uint    public constant MAX_SPARTANS            = 300 * 10**18;     // 300
    uint    public constant MAX_IMMORTALS           = 100;              // 100
    uint    public constant MAX_ATHENIANS           = 100 * 10**18;     // 100

    uint    public constant WAD                     = 10**18;           // Common decimal positions
    uint8   public constant BP_PERSIAN              = 1;                // Each Persian worths 1 Battle Point
    uint8   public constant BP_IMMORTAL             = 100;              // Each Immortal worths 100 Battle Points
    uint16  public constant BP_SPARTAN              = 1000;             // Each Spartan worths 1000 Battle Points
    uint8   public constant BP_ATHENIAN             = 100;              // Each Athenians worths 100 Battle Points

    uint8   public constant BATTLE_POINT_DECIMALS   = 18;
    uint8   public constant BATTLE_CASUALTIES       = 10;               //Percentage of Persian and Spartan casualties

    address public persians;
    address public immortals;
    address public spartans;
    address public athenians;

    mapping (address => mapping (address => uint))   public  warriorsByPlayer;               // Troops currently allocated by each player
    mapping (address => uint)                        public  warriorsOnTheBattlefield;       // Total troops fighting in the battle

    event WarriorsAssignedToBattlefield (address indexed _from, address _faction, uint _battlePointsIncrementForecast);
    event WarriorsBackToHome            (address indexed _to, address _faction, uint _survivedWarriors);

    /*******************************************************************************************
    When the battle ends in a draw:
        (*) 10% of main troops of both sides lie on the ground
        (*) 90% of them can be retrieved by each former owner
        (*) No slaves are assigned

    When the battle ends with a winning factions:
        (*) 10% of main troops of both sides lie on the ground
        (*) 90% of them can be retrieved by each former owner
        (*) Surviving warriors of the loosing faction are assigned as slaves to winners
        (*) Slaves are computed based on the BP contributed by each sender

    Persians and Spartans are main troops.

    Immortals and Athenians are support troops: there will be no casualties in their row, and they can
    be retrieved without losses by original senders.

    Only Persians and Spartans can be slaves. Immortals and Athenians WILL NOT be sent back as slaves to winners.

    Main Net Addresses
    Persians            = 0xaEc98A708810414878c3BCDF46Aad31dEd4a4557;
    Immortals           = 0x22E5F62D0FA19974749faa194e3d3eF6d89c08d7;
    Spartans            = 0x163733bcc28dbf26B41a8CfA83e369b5B3af741b;
    Athenians           = 0x17052d51E954592C1046320c2371AbaB6C73Ef10;
    *******************************************************************************************/
    function Battle(uint _startTime, uint _life, uint8 _avarageBlockTime, address _persians, address _immortals, address _spartans, address _athenians) Timed(_startTime, _life, _avarageBlockTime) {
        persians = _persians;
        immortals = _immortals;
        spartans = _spartans;
        athenians = _athenians;
    }

    /**** PHASE #1 ******/

    function assignPersiansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, persians, _warriors, MAX_PERSIANS);
        // Persians are divisible with 18 decimals and their value is 1 BP
        WarriorsAssignedToBattlefield(msg.sender, persians, _warriors / WAD);
        return true;
    }

    function assignSpartansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, spartans, _warriors, MAX_SPARTANS);
        // Spartans are divisible with 18 decimals and their value is 1.000 BP
        WarriorsAssignedToBattlefield(msg.sender, spartans, (_warriors / WAD).mul(BP_SPARTAN));
        return true;
    }

    function assignImmortalsToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, immortals, _warriors, MAX_IMMORTALS);
        // Immortals are not divisible and their value is 100 BP
        WarriorsAssignedToBattlefield(msg.sender, immortals, _warriors.mul(BP_IMMORTAL));
        return true;
    }

    function assignAtheniansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, athenians, _warriors, MAX_ATHENIANS);
        // Athenians are divisible with 18 decimals and their value is 100 BP
        WarriorsAssignedToBattlefield(msg.sender, athenians, (_warriors / WAD).mul(BP_ATHENIAN));
        return true;
    }

    /**** PHASE #2 ******/

    function redeemWarriors() onlyIfTimePassed external returns (bool success) {
        if (getPersiansBattlePoints() > getGreeksBattlePoints()) {
            // Persians won, compute slaves
            uint spartanSlaves = computeSlaves(msg.sender, spartans);
            if (spartanSlaves > 0) {
                // Send back Spartan slaves
                sendWarriors(msg.sender, spartans, spartanSlaves);
            }
            // Send back Persians but casualties
            retrieveWarriors(msg.sender, persians, BATTLE_CASUALTIES);
        } else if (getPersiansBattlePoints() < getGreeksBattlePoints()) {
            //Greeks won, send back Persian slaves
            uint persianSlaves = computeSlaves(msg.sender, persians);
            if (persianSlaves > 0) {
                // Send back Persians slaves
                sendWarriors(msg.sender, persians, persianSlaves);

            }
            // Send back Spartans but casualties
            retrieveWarriors(msg.sender, spartans, BATTLE_CASUALTIES);
        }
        // Send back Immortals untouched
        retrieveWarriors(msg.sender, immortals, 0);
        // Send back Athenians untouched
        retrieveWarriors(msg.sender, athenians, 0);
        return true;
    }

    /*** PRIVATE FUNCTIONS ***/

    function assignWarriorsToBattle(address _player, address _faction, uint _warriors, uint _maxWarriors) private {
        require(warriorsOnTheBattlefield[_faction].add(_warriors) <= _maxWarriors);
        assert(TokenERC20(_faction).transferFrom(_player, address(this), _warriors));
        warriorsByPlayer[_player][_faction] = warriorsByPlayer[_player][_faction].add(_warriors);
        warriorsOnTheBattlefield[_faction] = warriorsOnTheBattlefield[_faction].add(_warriors);
    }

    function retrieveWarriors(address _player, address _faction, uint8 _deadPercentage) private {
        if (warriorsByPlayer[_player][_faction] > 0) {
            uint _warriors = warriorsByPlayer[_player][_faction];
            if (_deadPercentage > 0) {
                _warriors = _warriors.sub(_warriors.wper(_deadPercentage));
            }
            warriorsByPlayer[_player][_faction] = 0;
            sendWarriors(_player, _faction, _warriors);
            WarriorsBackToHome(_player, _faction, _warriors);
        }
    }

    function sendWarriors(address _player, address _faction, uint _warriors) private {
        assert(TokenERC20(_faction).transfer(_player, _warriors));
    }

    /*** CONSTANT FUNCTIONS AND DAPP HELPERS ***/

    function getPersiansOnTheBattlefield(address _player) constant returns (uint persiansOnTheBattlefield) {
        return warriorsByPlayer[_player][persians];
    }

    function getImmortalsOnTheBattlefield(address _player) constant returns (uint immortalsOnTheBattlefield) {
        return warriorsByPlayer[_player][immortals];
    }

    function getSpartansOnTheBattlefield(address _player) constant returns (uint spartansOnTheBattlefield) {
        return warriorsByPlayer[_player][spartans];
    }

    function getAtheniansOnTheBattlefield(address _player) constant returns (uint atheniansOnTheBattlefield) {
        return warriorsByPlayer[_player][athenians];
    }

    function getPersiansBattlePoints() constant returns (uint persiansBattlePoints) {
        return (warriorsOnTheBattlefield[persians].mul(BP_PERSIAN) + warriorsOnTheBattlefield[immortals].mul(WAD).mul(BP_IMMORTAL));
    }

    function getGreeksBattlePoints() constant returns (uint greeksBattlePoints) {
        return (warriorsOnTheBattlefield[spartans].mul(BP_SPARTAN) + warriorsOnTheBattlefield[athenians].mul(BP_ATHENIAN));
    }

    function getPersiansBattlePointsBy(address _player) constant returns (uint playerBattlePoints) {
        return (getPersiansOnTheBattlefield(_player).mul(BP_PERSIAN) + getImmortalsOnTheBattlefield(_player).mul(WAD).mul(BP_IMMORTAL));
    }

    function getGreeksBattlePointsBy(address _player) constant returns (uint playerBattlePoints) {
        return (getSpartansOnTheBattlefield(_player).mul(BP_SPARTAN) + getAtheniansOnTheBattlefield(_player).mul(BP_ATHENIAN));
    }

    function computeSlaves(address _player, address _loosingMainTroops) constant returns (uint slaves) {
        if (_loosingMainTroops == spartans) {
            return getPersiansBattlePointsBy(_player).wdiv(getPersiansBattlePoints()).wmul(getTotalSlaves(spartans));
        } else {
            return getGreeksBattlePointsBy(_player).wdiv(getGreeksBattlePoints()).wmul(getTotalSlaves(persians));
        }
    }

    function getTotalSlaves(address _faction) constant returns (uint slaves) {
        return warriorsOnTheBattlefield[_faction].sub(warriorsOnTheBattlefield[_faction].wper(BATTLE_CASUALTIES));
    }

    function isInProgress() constant returns (bool inProgress) {
        return !isTimeExpired();
    }

    function isEnded() constant returns (bool ended) {
        return isTimeExpired();
    }

    function isDraw() constant returns (bool draw) {
        return (getPersiansBattlePoints() == getGreeksBattlePoints());
    }

    function getWinningFaction() constant returns (string winningFaction) {
        if (isInProgress()) {
            return "The battle is still in progress";
        }
        if (isDraw()) {
            return "The battle ended in a draw!";
        }
        return getPersiansBattlePoints() > getGreeksBattlePoints() ? "Persians" : "Greeks";
    }

    /****           DEV FUNCTIONS               *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /****             REALLY!                   *******/

    function setTime(uint _startTime, uint life, uint8 _avarageBlockTime) {
        startTime = _startTime;
        endTime = _startTime + life;
        avarageBlockTime = _avarageBlockTime;
    }

    function setPersiansWin() {
        warriorsOnTheBattlefield[persians] = 3000 * 10**18;  //3000
        warriorsOnTheBattlefield[immortals] = 2; //200
        warriorsOnTheBattlefield[spartans] = 2 * 10**18; //2000
        warriorsOnTheBattlefield[athenians] = 3 * 10**18; //300
    }

    function setGreeksWin() {
        warriorsOnTheBattlefield[persians] = 300 * 10**18;  //300
        warriorsOnTheBattlefield[immortals] = 2; //200
        warriorsOnTheBattlefield[spartans] = 27003 * 10**14; //2700.3
        warriorsOnTheBattlefield[athenians] = 3 * 10**18; //300
    }

    function setDraw() {
        warriorsOnTheBattlefield[persians] = 2200 * 10**18;  //2200
        warriorsOnTheBattlefield[immortals] = 2; //200
        warriorsOnTheBattlefield[spartans] = 2 * 10**18; //2000
        warriorsOnTheBattlefield[athenians] = 4 * 10**18; //400
    }

    event Debug (uint value);
}

pragma solidity ^0.4.15;

import "./TokenERC20.sol";
import "./Timed.sol";
import "./SafeMathLib.sol";

contract Battle is Timed {
    using SafeMathLib for uint;

    string  public constant VERSION                 = "1.0.0";

    uint    public constant MAX_PERSIANS            = 300000 * 10**18;  // 300.000
    uint    public constant MAX_SPARTANS            = 300 * 10**18;     // 300
    uint    public constant MAX_IMMORTALS           = 100;              // 100
    uint    public constant MAX_ATHENIANS           = 100 * 10**18;     // 100

    uint    public constant WAD                     = 10**18;           // Common decimal positions
    uint8   public constant BP_PERSIAN              = 1;                // Each Persian worths 1 Battle Point
    uint8   public constant BP_IMMORTAL             = 100;              // Each Immortal worths 100 Battle Points
    uint16  public constant BP_SPARTAN              = 1000;             // Each Spartan worths 1000 Battle Points
    uint8   public constant BP_ATHENIAN             = 100;              // Each Athenians worths 100 Battle Points

    uint8   public constant BATTLE_POINT_DECIMALS   = 18;
    uint8   public constant BATTLE_CASUALTIES       = 10;               //Percentage of Persian and Spartan casualties

    address public persians;
    address public immortals;
    address public spartans;
    address public athenians;

    mapping (address => mapping (address => uint))   public  warriorsByPlayer;               // Troops currently allocated by each player
    mapping (address => uint)                        public  warriorsOnTheBattlefield;       // Total troops fighting in the battle
    mapping (address => uint)                        public  warriorsIntoAde;                // Total casualties, increased after each warriors redeem

    event WarriorsAssignedToBattlefield (address indexed _from, address _faction, uint _battlePointsIncrementForecast);
    event WarriorsBackToHome            (address indexed _to, address _faction, uint _survivedWarriors);

    /*******************************************************************************************
    When the battle ends in a draw:
        (*) 10% of main troops of both sides lie on the ground
        (*) 90% of them can be retrieved by each former owner
        (*) No slaves are assigned

    When the battle ends with a winning factions:
        (*) 10% of main troops of both sides lie on the ground
        (*) 90% of them can be retrieved by each former owner
        (*) Surviving warriors of the loosing faction are assigned as slaves to winners
        (*) Slaves are computed based on the BP contributed by each sender

    Persians and Spartans are main troops.

    Immortals and Athenians are support troops: there will be no casualties in their row, and they can
    be retrieved without losses by original senders.

    Only Persians and Spartans can be slaves. Immortals and Athenians WILL NOT be sent back as slaves to winners.

    Main Net Addresses
    Persians            = 0xaEc98A708810414878c3BCDF46Aad31dEd4a4557;
    Immortals           = 0x22E5F62D0FA19974749faa194e3d3eF6d89c08d7;
    Spartans            = 0x163733bcc28dbf26B41a8CfA83e369b5B3af741b;
    Athenians           = 0x17052d51E954592C1046320c2371AbaB6C73Ef10;
    *******************************************************************************************/
    function Battle(uint _startTime, uint _life, uint8 _avarageBlockTime, address _persians, address _immortals, address _spartans, address _athenians) Timed(_startTime, _life, _avarageBlockTime) {
        persians = _persians;
        immortals = _immortals;
        spartans = _spartans;
        athenians = _athenians;
    }

    /**** PHASE #1 ******/

    function assignPersiansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, persians, _warriors, MAX_PERSIANS);
        // Persians are divisible with 18 decimals and their value is 1 BP
        WarriorsAssignedToBattlefield(msg.sender, persians, _warriors / WAD);
        return true;
    }

    function assignSpartansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, spartans, _warriors, MAX_SPARTANS);
        // Spartans are divisible with 18 decimals and their value is 1.000 BP
        WarriorsAssignedToBattlefield(msg.sender, spartans, (_warriors / WAD).mul(BP_SPARTAN));
        return true;
    }

    function assignImmortalsToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, immortals, _warriors, MAX_IMMORTALS);
        // Immortals are not divisible and their value is 100 BP
        WarriorsAssignedToBattlefield(msg.sender, immortals, _warriors.mul(BP_IMMORTAL));
        return true;
    }

    function assignAtheniansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
        assignWarriorsToBattle(msg.sender, athenians, _warriors, MAX_ATHENIANS);
        // Athenians are divisible with 18 decimals and their value is 100 BP
        WarriorsAssignedToBattlefield(msg.sender, athenians, (_warriors / WAD).mul(BP_ATHENIAN));
        return true;
    }

    /**** PHASE #2 ******/

    function redeemWarriors() onlyIfTimePassed external returns (bool success) {
        if (getPersiansBattlePoints() > getGreeksBattlePoints()) {
            // Persians won, compute slaves
            uint spartanSlaves = computeSlaves(msg.sender, spartans);
            if (spartanSlaves > 0) {
                // Send back Spartan slaves
                sendWarriors(msg.sender, spartans, spartanSlaves);
            }
            // Send back Persians but casualties
            retrieveWarriors(msg.sender, persians, BATTLE_CASUALTIES);
        } else if (getPersiansBattlePoints() < getGreeksBattlePoints()) {
            //Greeks won, send back Persian slaves
            uint persianSlaves = computeSlaves(msg.sender, persians);
            if (persianSlaves > 0) {
                // Send back Spartan slaves
                sendWarriors(msg.sender, persians, persianSlaves);
            }
            // Send back Spartans but casualties
            retrieveWarriors(msg.sender, spartans, BATTLE_CASUALTIES);
        }
        // Send back Immortals untouched
        retrieveWarriors(msg.sender, immortals, 0);
        // Send back Athenians untouched
        retrieveWarriors(msg.sender, athenians, 0);
        return true;
    }

    /*** PRIVATE FUNCTIONS ***/

    function assignWarriorsToBattle(address _player, address _faction, uint _warriors, uint _maxWarriors) private {
        require(warriorsOnTheBattlefield[_faction].add(_warriors) <= _maxWarriors);
        assert(TokenERC20(_faction).transferFrom(_player, address(this), _warriors));
        warriorsByPlayer[_player][_faction] = warriorsByPlayer[_player][_faction].add(_warriors);
        warriorsOnTheBattlefield[_faction] = warriorsOnTheBattlefield[_faction].add(_warriors);
    }

    function retrieveWarriors(address _player, address _faction, uint8 _deadPercentage) private {
        if (warriorsByPlayer[_player][_faction] > 0) {
            uint _warriors = warriorsByPlayer[_player][_faction];
            if (_deadPercentage > 0) {
                uint _deadWarriors = _warriors.wper(_deadPercentage);
                warriorsIntoAde[_faction] = warriorsIntoAde[_faction].add(_deadWarriors);
                _warriors = _warriors.sub(_deadWarriors);
            }
            warriorsByPlayer[_player][_faction] = 0;
            sendWarriors(_player, _faction, _warriors);
            WarriorsBackToHome(_player, _faction, _warriors);
        }
    }

    function sendWarriors(address _player, address _faction, uint _warriors) private {
        assert(TokenERC20(_faction).transfer(_player, _warriors));
    }

    /*** CONSTANT FUNCTIONS AND DAPP HELPERS ***/

    function getPersiansOnTheBattlefield(address _player) constant returns (uint persiansOnTheBattlefield) {
        return warriorsByPlayer[_player][persians];
    }

    function getImmortalsOnTheBattlefield(address _player) constant returns (uint immortalsOnTheBattlefield) {
        return warriorsByPlayer[_player][immortals];
    }

    function getSpartansOnTheBattlefield(address _player) constant returns (uint spartansOnTheBattlefield) {
        return warriorsByPlayer[_player][spartans];
    }

    function getAtheniansOnTheBattlefield(address _player) constant returns (uint atheniansOnTheBattlefield) {
        return warriorsByPlayer[_player][athenians];
    }

    function getPersiansBattlePoints() constant returns (uint persiansBattlePoints) {
        return (warriorsOnTheBattlefield[persians].mul(BP_PERSIAN) + warriorsOnTheBattlefield[immortals].mul(WAD).mul(BP_IMMORTAL));
    }

    function getGreeksBattlePoints() constant returns (uint greeksBattlePoints) {
        return (warriorsOnTheBattlefield[spartans].mul(BP_SPARTAN) + warriorsOnTheBattlefield[athenians].mul(BP_ATHENIAN));
    }

    function getPersiansBattlePointsBy(address _player) constant returns (uint playerBattlePoints) {
        return (getPersiansOnTheBattlefield(_player).mul(BP_PERSIAN) + getImmortalsOnTheBattlefield(_player).mul(WAD).mul(BP_IMMORTAL));
    }

    function getGreeksBattlePointsBy(address _player) constant returns (uint playerBattlePoints) {
        return (getSpartansOnTheBattlefield(_player).mul(BP_SPARTAN) + getAtheniansOnTheBattlefield(_player).mul(BP_ATHENIAN));
    }

    function computeSlaves(address _player, address _loosingMainTroops) constant returns (uint slaves) {
        if (_loosingMainTroops == spartans) {
            return getPersiansBattlePointsBy(_player).wdiv(getPersiansBattlePoints()).wmul(getTotalSlaves(spartans));
        } else {
            return getGreeksBattlePointsBy(_player).wdiv(getGreeksBattlePoints()).wmul(getTotalSlaves(persians));
        }
    }

    function getTotalSlaves(address _faction) constant returns (uint slaves) {
        return warriorsOnTheBattlefield[_faction].sub(warriorsOnTheBattlefield[_faction].wper(BATTLE_CASUALTIES));
    }

    function getDeadWarriors(address _faction) constant returns (uint deadWarriors) {
        return warriorsIntoAde[_faction];
    }

    function isInProgress() constant returns (bool inProgress) {
        return !isTimeExpired();
    }

    function isEnded() constant returns (bool ended) {
        return isTimeExpired();
    }

    function isDraw() constant returns (bool draw) {
        return (getPersiansBattlePoints() == getGreeksBattlePoints());
    }

    function getWinningFaction() constant returns (string winningFaction) {
        if (isInProgress()) {
            return "The battle is still in progress";
        }
        if (isDraw()) {
            return "The battle ended in a draw!";
        }
        return getPersiansBattlePoints() > getGreeksBattlePoints() ? "Persians" : "Greeks";
    }

    /****           DEV FUNCTIONS               *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /**** REMOVE THESE FUNCTIONS BEFORE DEPLOY  *******/
    /****             REALLY!                   *******/

    function setTime(uint _startTime, uint life, uint8 _avarageBlockTime) {
        startTime = _startTime;
        endTime = _startTime + life;
        avarageBlockTime = _avarageBlockTime;
    }

    function setPersiansWin() {
        warriorsOnTheBattlefield[persians] = 3000 * 10**18;  //3000
        warriorsOnTheBattlefield[immortals] = 2; //200
        warriorsOnTheBattlefield[spartans] = 2 * 10**18; //2000
        warriorsOnTheBattlefield[athenians] = 3 * 10**18; //300
    }

    function setGreeksWin() {
        warriorsOnTheBattlefield[persians] = 300 * 10**18;  //300
        warriorsOnTheBattlefield[immortals] = 2; //200
        warriorsOnTheBattlefield[spartans] = 27003 * 10**14; //2700.3
        warriorsOnTheBattlefield[athenians] = 3 * 10**18; //300
    }

    function setDraw() {
        warriorsOnTheBattlefield[persians] = 2200 * 10**18;  //2200
        warriorsOnTheBattlefield[immortals] = 2; //200
        warriorsOnTheBattlefield[spartans] = 2 * 10**18; //2000
        warriorsOnTheBattlefield[athenians] = 4 * 10**18; //400
    }

    event Debug (uint value);
}


Added IERC721Receiver to supportsInterface


new version smart contract

new version smart contract

/* Part of this contract is from the solidity documentation
TODO: Set a license.
*/

pragma solidity ^0.4.8;

/// @title Voting with delegation.
contract AbieFund {

    uint membershipFee = 0.1 ether;
    uint nbMembers;
    uint registrationTime = 1 years;

    event Donated(address donor, uint amount);

    enum ProposalType {AddMember,FundProject} // Different types of proposals.
    enum VoteType {Abstain,Yes,No} // Different value of a vote.

    struct Proposal
    {
        bytes32 name;       // short name (up to 32 bytes).
        uint voteYes;     // number of YES votes.
        uint voteAbstain;     // number of abstention. Number of No can be deduced.
        address recipient;     // address the funds will be sent.
        uint value;         // quantity of wei to be sent.
        bytes32 data;       // data of the transaction.
        ProposalType proposalType;  // type of the proposal.
        mapping (address => VoteType) vote; // vote of the party.
    }

    struct Member
    {
        uint registration;  // date of registration, if 0 the member does not exist.
        address[2] delegate; // delegate[proposalType] gives the delegate for the type.
    }

    mapping (address => Member) public members;

    Proposal[] public proposals;

    /// Require at least price to be paid.
    modifier costs(uint price) {
        if (msg.value<price)
            throw;
        _;
    }

    /// Require the caller to be a member.
    modifier isMember() {
        if (members[msg.sender].registration==0) // Not a member.
            throw;
        if (members[msg.sender].registration+registrationTime<now) // Has expired.
            throw;
        _;
    }

    /// @param initialMembers First members of the organization.
    function AbieFund(address[] initialMembers) {
        for (uint i;i<initialMembers.length;++i)
            members[initialMembers[i]].registration=now;
        nbMembers=initialMembers.length;
    }

    /** Choose a delegate.
      * @param proposalType 0 for AddMember, 1 for FundProject.
      * @param target account to delegate to.
      */
    function setDelegate(uint8 proposalType, address target)
    {
        members[msg.sender].delegate[proposalType] = target;
    }

    /// Receive funds.
    function () payable {
        Donated(msg.sender, msg.value);
    }

    function askMembership () payable costs(membershipFee) {
        Donated(msg.sender,msg.value); // Register the donation.

        // Create a proposal to add the member.
        proposals.push(Proposal({
        name: 0x0,
        voteYes: 0,
        voteAbstain: 0,
        recipient: msg.sender,
        value: 0x0,
        data: 0x0,
        proposalType: ProposalType.AddMember
        }));
    }

    function vote (uint proposal, VoteType voteType) isMember {
        // TODO
    }

    /// GETTERS ///

    /** Return the delegate.
     *  @param member member to get the delegate from.
     *  @param proposalType 0 for AddMember, 1 for FundProject.
     */
    function getDelegate(address member, uint8 proposalType) constant returns (address){
        return members[member].delegate[proposalType];
    }

}

pragma solidity ^0.4.8;

/// @title Voting with delegation.
contract AbieFund {

    uint membershipFee=0.1 ether;

    event Donated(address indexed donor, uint amount);

    enum ProposalType {AddMember,FundProject} // Different types of proposals.

    struct Proposal
    {
        bytes32 name;       // short name (up to 32 bytes).
        uint voteCount;     // number of accumulated votes.
        address recipient;     // address the funds will be sent.
        uint value;         // quantity of wei to be sent.
        bytes32 data;       // data of the transaction.
        ProposalType proposalType;  // type of the proposal
    }

    struct Member
    {
        uint registration;  // date of registration, if 0 the member does not exist.
        address[2] delegate; // delegate[proposalType] gives the delegate for the type.
    }

    mapping (address => Member) public members;

    Proposal[] public proposals;

    /// Require at least price to be paid.
    modifier costs(uint price) {
        if (msg.value<price)
            throw;
        _;
    }

    /// @param initialMembers First members of the organization.
    function AbieFund(address[] initialMembers) {
        for (uint i;i<initialMembers.length;++i)
            members[initialMembers[i]].registration=now;
    }

    /** Choose a delegate.
      * @param proposalType 0 for AddMember, 1 for FundProject.
      * @param target account to delegate to.
      */
    function setDelegate(uint8 proposalType, address target)
    {
        members[msg.sender].delegate[proposalType] = target;
    }

    /// Receive funds.
    function () payable {
        Donated(msg.sender, msg.value);
    }

    function askMembership () payable costs(membershipFee) {
        Donated(msg.sender,msg.value);
        proposals.push(Proposal({
        name: 0x0,
        voteCount: 0,
        recipient: msg.sender,
        value: 0x0,
        data: 0x0,
        proposalType: ProposalType.AddMember
        }));
    }

    /// GETTERS ///

    /** Return the delegate.
     *  @param member member to get the delegate from.
     *  @param proposalType 0 for AddMember, 1 for FundProject.
     */
    function getDelegate(address member, uint8 proposalType) constant returns (address){
        return members[member].delegate[proposalType];
    }

}

/*
    mapping(address => Voter) public voters;
    // This declares a new complex type which will
    // be used for variables later.
    // It will represent a single voter.
    struct Voter {
        uint weight; // weight is accumulated by delegation.
        bool voted;  // if true, that person already voted.
        address delegate; // person delegated to.
        uint vote;   // index of the voted proposal.
    }

    // This declares a state variable that.
    // stores a `Voter` struct for each possible address.
    mapping(address => Voter) public voters;

    // Give `voter` the right to vote on this ballot.
    // May only be called by `chairperson`.
    function giveRightToVote(address voter) {
        if (msg.sender != chairperson || voters[voter].voted) {
            // `throw` terminates and reverts all changes to
            // the state and to Ether balances. It is often
            // a good idea to use this if functions are
            // called incorrectly. But watch out, this
            // will also consume all provided gas.
            throw;
        }
        voters[voter].weight = 1;
    }

    /// Delegate your vote to the voter `to`.
    function delegate(address to) {
        // assigns reference
        Voter sender = voters[msg.sender];
        if (sender.voted)
            throw;

        // Forward the delegation as long as
        // `to` also delegated.
        // In general, such loops are very dangerous,
        // because if they run too long, they might
        // need more gas than is available in a block.
        // In this case, the delegation will not be executed,
        // but in other situations, such loops might
        // cause a contract to get "stuck" completely.
        while (
            voters[to].delegate != address(0) &&
            voters[to].delegate != msg.sender
        ) {
            to = voters[to].delegate;
        }

        // We found a loop in the delegation, not allowed.
        if (to == msg.sender) {
            throw;
        }

        // Since `sender` is a reference, this
        // modifies `voters[msg.sender].voted`
        sender.voted = true;
        sender.delegate = to;
        Voter delegate = voters[to];
        if (delegate.voted) {
            // If the delegate already voted,
            // directly add to the number of votes
            proposals[delegate.vote].voteCount += sender.weight;
        } else {
            // If the delegate did not vote yet,
            // add to her weight.
            delegate.weight += sender.weight;
        }
    }

    /// Give your vote (including votes delegated to you)
    /// to proposal `proposals[proposal].name`.
    function vote(uint proposal) {
        Voter sender = voters[msg.sender];
        if (sender.voted)
            throw;
        sender.voted = true;
        sender.vote = proposal;

        // If `proposal` is out of the range of the array,
        // this will throw automatically and revert all
        // changes.
        proposals[proposal].voteCount += sender.weight;
    }

    /// @dev Computes the winning proposal taking all
    /// previous votes into account.
    function winningProposal() constant
            returns (uint winningProposal)
    {
        uint winningVoteCount = 0;
        for (uint p = 0; p < proposals.length; p++) {
            if (proposals[p].voteCount > winningVoteCount) {
                winningVoteCount = proposals[p].voteCount;
                winningProposal = p;
            }
        }
    }

    // Calls winningProposal() function to get the index
    // of the winner contained in the proposals array and then
    // returns the name of the winner
    function winnerName() constant
            returns (bytes32 winnerName)
    {
        winnerName = proposals[winningProposal()].name;
    }

*/


send back challenge deposit

send back challenge deposit

pragma solidity 0.4.11;
import "./StandardToken.sol";

contract Registry {

	address public wallet;

	// this will later be the parameters from the parametrizer
	uint public expTime;
	uint public applyCost;
	uint public challengeTime;
	StandardToken public token;

	struct Publisher {
		address owner;
		uint time;
		uint status;  // is this publisher in the whitelist or applying or already challenged etc
	}

	// status description:
	// 0 = whitelisted, either expired or not based on time variable
	// 1 = new applicant waiting to be challenged
	// 2 = already been challenged
	// this can possibly just be a bool later

	mapping(bytes32 => Publisher) public domainMap;

	function Registry(address _token) {
		// set parameters somehow
		token = StandardToken(_token);
	}

	function add(bytes32 _domainHash) private {
		domainMap[_domainHash].time = now + expTime;
		domainMap[_domainHash].status = 0;
	}

	function isVerified(string _domain) returns (bool) {
		bytes32 domainHash = sha3(_domain);
		if (domainMap[domainHash].time < now && domainMap[domainHash].status != 0) {
			return false;
		}
		else {
			return true;
		}
	}

	function apply(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		// if success
		domainMap[domainHash].status = 1;
		domainMap[domainHash].time = now + challengeTime;
		// trigger an event
	}

	// save challenger somewhere
	function challenge(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].status != 2); // works for both unexpired whitelisted and new applicants
		require(domainMap[domainHash].time < now);
		domainMap[domainHash].status = 2;
		if (callVote(domainHash, domainMap[domainHash].time) == true) {
			add(_domain);
		}
		else {
			token.transferFrom(wallet, msg.sender, applyCost);
			// trigger event to notify applicant?
		}
	}

	function moveToRegistry(string _domain) {
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].time > now);
		require(domainMap[domainHash].status == 1);
		add(domainHash);
	}

	// claim tokens function

	function callVote(bytes32 _domainHash, uint _time) private returns (bool) {
		// event that vote has started
		// ??
	}

}

pragma solidity 0.4.11;
import "./StandardToken.sol";

contract Registry {

	address public wallet;

	// this will later be the parameters from the parametrizer
	uint public expTime;
	uint public applyCost;
	uint public challengeTime;
	StandardToken public token;

	struct Publisher {
		address owner;
		uint time;
		uint status;  // is this publisher in the whitelist or applying or already challenged etc
	}

	// status description:
	// 0 = whitelisted, either expired or not based on time variable
	// 1 = new applicant waiting to be challenged
	// 2 = already been challenged
	// this can possibly just be a bool later

	mapping(bytes32 => Publisher) public domainMap;

	function Registry(address _token) {
		// set parameters somehow
		token = StandardToken(_token);
	}

	function add(bytes32 _domainHash) private {
		domainMap[_domainHash].time = now + expTime;
		domainMap[_domainHash].status = 0;
	}

	function isVerified(string _domain) returns (bool) {
		bytes32 domainHash = sha3(_domain);
		if (domainMap[domainHash].time < now && domainMap[domainHash].status != 0) {
			return false;
		}
		else {
			return true;
		}
	}

	function apply(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		// if success
		domainMap[domainHash].status = 1;
		domainMap[domainHash].time = now + challengeTime;
		// trigger an event
	}

	// save challenger somewhere
	function challenge(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].status != 2); // works for both unexpired whitelisted and new applicants
		require(domainMap[domainHash].time < now);
		domainMap[domainHash].status = 2;
		if (callVote(domainHash, domainMap[domainHash].time) == true) {
			add(_domain);
		}
		else {
			token.transferFrom(mwallet, msg.sender, applyCost);
			// trigger event to notify applicant?
		}
	}

	function moveToRegistry(string _domain) {
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].time > now);
		require(domainMap[domainHash].status == 1);
		add(domainHash);
	}

	// claim tokens function

	function callVote(bytes32 _domainHash, uint _time) private returns (bool) {
		// event that vote has started
		// ??
	}

}


Minor refactoring

Minor refactoring

pragma solidity 0.4.18;

/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a * b;
        assert(a == 0 || c / a == b);
        return c;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // assert(b > 0); // Solidity automatically throws when dividing by 0
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        return c;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }
}

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
    address public owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
     * account.
     */
    function Ownable() public {
        owner = msg.sender;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function transferOwnership(address newOwner) onlyOwner public {
        require(newOwner != address(0));
        OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }
}

/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
    uint256 public totalSupply;
    function balanceOf(address who) public constant returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 is ERC20Basic {
    function allowance(address owner, address spender) public constant returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract ApprovalContract is ERC20 {
    using SafeMath for uint256;

    mapping (address => mapping (address => uint256)) public allowed;

    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     *
     * Beware that changing an allowance with this method brings the risk that someone may use both the old
     * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
     * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     */
    function approve(address _spender, uint256 _value) public returns (bool) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return A uint256 specifying the amount of tokens still available for the spender.
     */
    function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
    }

    /**
     * approve should be called when allowed[_spender] == 0. To increment
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     */
    function increaseApproval (address _spender, uint _addedValue) public
    returns (bool success) {
        allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }

    function decreaseApproval (address _spender, uint _subtractedValue) public
    returns (bool success) {
        uint oldValue = allowed[msg.sender][_spender];
        if (_subtractedValue > oldValue) {
            allowed[msg.sender][_spender] = 0;
        } else {
            allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
        }
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
}

/**
 * @title Mintable token
 * @dev Simple ERC20 Token example, with mintable token creation
 * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
 */
contract MintableToken is ApprovalContract, Ownable {

    uint256 public hardCap;
    mapping(address => uint256) public balances;

    event Mint(address indexed to, uint256 amount);

    modifier canMint() {
        require(totalSupply == 0);
        _;
    }

    /**
     * @dev Function to mint tokens
     * @param _to The address that will receive the minted tokens.
     * @param _amount The amount of tokens to mint.
     * @return A boolean that indicates if the operation was successful.
     */
    function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
        require(_amount < hardCap);
        totalSupply = totalSupply.add(_amount);
        balances[_to] = balances[_to].add(_amount);
        Mint(_to, _amount);
        Transfer(0x0, _to, _amount);
        return true;
    }
}

/**
 * @title Vesting token
 * @dev TODO.
 */
contract Vesting is MintableToken {

    event VestingMemberAdded(address indexed _address, uint256 _amount, uint _start, uint _end);

    struct _Vesting {
        uint256 totalSum;     //total amount
        uint256 start;        //start block
        uint256 end;          //end block
        uint256 usedAmount;   //the amount of paid payments
    }

    mapping (address => _Vesting ) public vestingMembers;

    function addVestingMember(
    address _address,
    uint256 _amount,
    uint256 _start,
    uint256 _end
    ) onlyOwner public returns (bool) {
        require(
        _address != address(0) &&
        _amount > 0 &&
        _start < _end &&
        vestingMembers[_address].totalSum == 0 &&
        balances[msg.sender] > _amount
        );

        balances[msg.sender] = balances[msg.sender].sub(_amount);

        vestingMembers[_address].totalSum = _amount;    //total amount
        vestingMembers[_address].start = _start;        //start block
        vestingMembers[_address].end = _end;            //end block
        vestingMembers[_address].usedAmount = 0;        //the amount of paid payments

        VestingMemberAdded(_address, _amount, _start, _end);

        return true;
    }

    function currentPart(address _address) private constant returns (uint256) {
        if (vestingMembers[_address].totalSum == 0) {
            return 0;
        }
        if (block.number >= vestingMembers[_address].end) {
            return vestingMembers[_address].totalSum.sub(vestingMembers[_address].usedAmount);
        }

        return vestingMembers[_address].totalSum
        .mul(block.number - vestingMembers[_address].start)
        .div(vestingMembers[_address].end - vestingMembers[_address].start)
        .sub(vestingMembers[_address].usedAmount);
    }

    function subFromBalance(address _address, uint256 _amount) private returns (uint256) {
        require(_address != address(0));

        if (vestingMembers[_address].totalSum == 0) {
            balances[_address] = balances[_address].sub(_amount);
            return balances[_address];
        }
        uint256 summary = balanceOf(_address);
        require(summary >= _amount);

        if (balances[_address] > _amount) {
            balances[_address] = balances[_address].sub(_amount);
        } else {
            uint256 part = currentPart(_address);
            if (block.number >= vestingMembers[_address].end) {
                vestingMembers[_address].totalSum = 0;          //total amount
                vestingMembers[_address].start = 0;             //start block
                vestingMembers[_address].end = 0;               //end block
                vestingMembers[_address].usedAmount = 0;        //the amount of paid payments
            } else {
                vestingMembers[_address].usedAmount = vestingMembers[_address].usedAmount.add(part);
            }
            balances[_address] = balances[_address].add(part).sub(_amount);
        }

        return balances[_address];
    }

    function balanceOf(address _owner) public constant returns (uint256 balance) {
        if (vestingMembers[_owner].totalSum == 0) {
            return balances[_owner];
        } else {
            return balances[_owner].add(currentPart(_owner));
        }
    }

    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balanceOf(msg.sender));

        subFromBalance(msg.sender, _value);

        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));

        uint256 _allowance = allowed[_from][msg.sender];

        subFromBalance(_from, _value);

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

contract DMToken is Vesting {

    string public name = "DMarket Token";
    string public symbol = "MARK";
    uint256 public decimals = 8;

    function DMToken() public {
        hardCap = 15644283100000000;
    }

    function multiTransfer(address[] recipients, uint256[] amounts) public onlyOwner {
        require(recipients.length == amounts.length);
        uint256 sum = 0;
        for (uint i = 0; i < amounts.length; i++) {
            require(recipients[i] != address(0));
            sum += amounts[i];
        }
        require(sum <= balances[msg.sender]);
        for (i = 0; i < recipients.length; i++) {
            transfer(recipients[i], amounts[i]);
        }
    }

    function multiVesting(
    address[] _address,
    uint256[] _amount,
    uint256[] _start,
    uint256[] _end
    ) public onlyOwner {
        require(
        _address.length == _amount.length &&
        _address.length == _start.length &&
        _address.length == _end.length
        );

        uint256 sum = 0;
        for (uint i = 0; i < _amount.length; i++) {
            require(_address[i] != address(0));
            sum += _amount[i];
        }
        require(sum <= balances[msg.sender]);

        for (i = 0; i < _address.length; i++) {
            addVestingMember(_address[i], _amount[i], _start[i], _end[i]);
        }
    }
}

pragma solidity 0.4.18;

/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a * b;
        assert(a == 0 || c / a == b);
        return c;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // assert(b > 0); // Solidity automatically throws when dividing by 0
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        return c;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }
}

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
    address public owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
     * account.
     */
    function Ownable() public {
        owner = msg.sender;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function transferOwnership(address newOwner) onlyOwner public {
        require(newOwner != address(0));
        OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }
}

/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
    uint256 public totalSupply;
    function balanceOf(address who) public constant returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 is ERC20Basic {
    function allowance(address owner, address spender) public constant returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract ApprovalContract is ERC20 {
    using SafeMath for uint256;

    mapping (address => mapping (address => uint256)) allowed;

    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     *
     * Beware that changing an allowance with this method brings the risk that someone may use both the old
     * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
     * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     */
    function approve(address _spender, uint256 _value) public returns (bool) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return A uint256 specifying the amount of tokens still available for the spender.
     */
    function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
    }

    /**
     * approve should be called when allowed[_spender] == 0. To increment
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     */
    function increaseApproval (address _spender, uint _addedValue) public
    returns (bool success) {
        allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }

    function decreaseApproval (address _spender, uint _subtractedValue) public
    returns (bool success) {
        uint oldValue = allowed[msg.sender][_spender];
        if (_subtractedValue > oldValue) {
            allowed[msg.sender][_spender] = 0;
        } else {
            allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
        }
        Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
}

contract MintableToken is ApprovalContract, Ownable {

    uint256 public hardCap;
    mapping(address => uint256) balances;

    event Mint(address indexed to, uint256 amount);

    modifier canMint() {
        require(totalSupply == 0);
        _;
    }

    /**
     * @dev Function to mint tokens
     * @param _to The address that will receive the minted tokens.
     * @param _amount The amount of tokens to mint.
     * @return A boolean that indicates if the operation was successful.
     */
    function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
        require(_amount < hardCap);
        totalSupply = totalSupply.add(_amount);
        balances[_to] = balances[_to].add(_amount);
        Mint(_to, _amount);
        Transfer(0x0, _to, _amount);
        return true;
    }
}

contract Vesting is MintableToken {

    event VestingMemberAdded(address _address, uint256 _amount, uint _start, uint _end);

    struct _Vesting {
    uint256 totalSum;
    uint256 start;
    uint256 end;
    uint256 usedAmount;
    }

    mapping (address => _Vesting ) public vestingMembers;

    function addVestingMember(
    address _address,
    uint256 _amount,
    uint256 _start,
    uint256 _end
    ) onlyOwner public returns (bool) {
        require(
        _address != address(0) &&
        _amount > 0 &&
        _start < _end &&
        vestingMembers[_address].totalSum == 0 &&
        balances[msg.sender] > _amount
        );

        balances[msg.sender] = balances[msg.sender].sub(_amount);

        vestingMembers[_address].totalSum = _amount;    //total amount
        vestingMembers[_address].start = _start;        //start block
        vestingMembers[_address].end = _end;            //end block
        vestingMembers[_address].usedAmount = 0;        //the amount of paid payments

        VestingMemberAdded(_address, _amount, _start, _end);

        return true;
    }

    function currentPart(address _address) private constant returns (uint256) {
        if (vestingMembers[_address].totalSum == 0) {
            return 0;
        }
        if (block.number >= vestingMembers[_address].end) {
            return vestingMembers[_address].totalSum.sub(vestingMembers[_address].usedAmount);
        }

        return vestingMembers[_address].totalSum
        .mul(block.number - vestingMembers[_address].start)
        .div(vestingMembers[_address].end - vestingMembers[_address].start)
        .sub(vestingMembers[_address].usedAmount);
    }

    function subFromBalance(address _address, uint256 _amount) private returns (uint256) {
        require(_address != address(0));

        if (vestingMembers[_address].totalSum == 0) {
            balances[_address] = balances[_address].sub(_amount);
            return balances[_address];
        }
        uint256 summary = balanceOf(_address);
        require(summary >= _amount);

        if (balances[_address] > _amount) {
            balances[_address] = balances[_address].sub(_amount);
        } else {
            uint256 part = currentPart(_address);
            if (block.number >= vestingMembers[_address].end) {
                vestingMembers[_address].totalSum = 0;          //total amount
                vestingMembers[_address].start = 0;             //start block
                vestingMembers[_address].end = 0;               //end block
                vestingMembers[_address].usedAmount = 0;        //the amount of paid payments
            } else {
                vestingMembers[_address].usedAmount = vestingMembers[_address].usedAmount.add(part);
            }
            balances[_address] = balances[_address].add(part).sub(_amount);
        }

        return balances[_address];
    }

    function balanceOf(address _owner) public constant returns (uint256 balance) {
        if (vestingMembers[_owner].totalSum == 0) {
            return balances[_owner];
        } else {
            return balances[_owner].add(currentPart(_owner));
        }
    }

    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balanceOf(msg.sender));

        subFromBalance(msg.sender, _value);

        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));

        uint256 _allowance = allowed[_from][msg.sender];

        subFromBalance(_from, _value);

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

contract DMToken is Vesting {

    string public name = "DMarket Token";
    string public symbol = "MARK";
    uint256 public decimals = 8;

    function DMToken() public {
        hardCap = 15644283100000000;
    }

    function multiTransfer(address[] recipients, uint256[] amounts) public onlyOwner {
        require(recipients.length == amounts.length);
        uint256 sum = 0;
        for (uint i = 0; i < amounts.length; i++) {
            require(recipients[i] != address(0));
            sum += amounts[i];
        }
        require(sum <= balances[msg.sender]);
        for (i = 0; i < recipients.length; i++) {
            transfer(recipients[i], amounts[i]);
        }
    }

    function multiVesting(
    address[] _address,
    uint256[] _amount,
    uint256[] _start,
    uint256[] _end
    ) public onlyOwner {
        require(
        _address.length == _amount.length &&
        _address.length == _start.length &&
        _address.length == _end.length
        );

        uint256 sum = 0;
        for (uint i = 0; i < _amount.length; i++) {
            require(_address[i] != address(0));
            sum += _amount[i];
        }
        require(sum <= balances[msg.sender]);

        for (i = 0; i < _address.length; i++) {
            addVestingMember(_address[i], _amount[i], _start[i], _end[i]);
        }
    }
}