ETH Price: $3,861.93 (-4.80%)

Transaction Decoder

Block:
4838568 at Jan-01-2018 11:50:13 PM +UTC
Transaction Fee:
0.0012517 ETH $4.83
Gas Used:
62,585 Gas / 20 Gwei

Emitted Events:

86 LLToken.Transfer( from=[Receiver] EtherDelta, to=[Sender] 0x1ed014aec47fae44c9e55bac7662c0b78ae61798, value=534668806 )
87 EtherDelta.Withdraw( token=LLToken, user=[Sender] 0x1ed014aec47fae44c9e55bac7662c0b78ae61798, amount=534668806, balance=4345015542 )

Account State Difference:

  Address   Before After State Difference Code
0x1ed014aE...78Ae61798
2.945138708414654939 Eth
Nonce: 2755
2.943887008414654939 Eth
Nonce: 2756
0.0012517
0x6D5caC36...A610ad9f2
696.914617647623468362 Eth696.915869347623468362 Eth0.0012517
0x8d12A197...2A5CC6819
(EtherDelta 2)

Execution Trace

EtherDelta.withdrawToken( token=0x6D5caC36c1AE39f41d52393b7a425d0A610ad9f2, amount=534668806 )
  • LLToken.transfer( _to=0x1ed014aEc47fAe44C9E55bAC7662c0b78Ae61798, _value=534668806 ) => ( True )
    File 1 of 2: EtherDelta
    pragma solidity ^0.4.9;
    
    contract SafeMath {
      function safeMul(uint a, uint b) internal returns (uint) {
        uint c = a * b;
        assert(a == 0 || c / a == b);
        return c;
      }
    
      function safeSub(uint a, uint b) internal returns (uint) {
        assert(b <= a);
        return a - b;
      }
    
      function safeAdd(uint a, uint b) internal returns (uint) {
        uint c = a + b;
        assert(c>=a && c>=b);
        return c;
      }
    
      function assert(bool assertion) internal {
        if (!assertion) throw;
      }
    }
    
    contract Token {
      /// @return total amount of tokens
      function totalSupply() constant returns (uint256 supply) {}
    
      /// @param _owner The address from which the balance will be retrieved
      /// @return The balance
      function balanceOf(address _owner) constant returns (uint256 balance) {}
    
      /// @notice send `_value` token to `_to` from `msg.sender`
      /// @param _to The address of the recipient
      /// @param _value The amount of token to be transferred
      /// @return Whether the transfer was successful or not
      function transfer(address _to, uint256 _value) returns (bool success) {}
    
      /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
      /// @param _from The address of the sender
      /// @param _to The address of the recipient
      /// @param _value The amount of token to be transferred
      /// @return Whether the transfer was successful or not
      function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
    
      /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
      /// @param _spender The address of the account able to transfer the tokens
      /// @param _value The amount of wei to be approved for transfer
      /// @return Whether the approval was successful or not
      function approve(address _spender, uint256 _value) returns (bool success) {}
    
      /// @param _owner The address of the account owning tokens
      /// @param _spender The address of the account able to transfer the tokens
      /// @return Amount of remaining tokens allowed to spent
      function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
    
      event Transfer(address indexed _from, address indexed _to, uint256 _value);
      event Approval(address indexed _owner, address indexed _spender, uint256 _value);
    
      uint public decimals;
      string public name;
    }
    
    contract StandardToken is Token {
    
      function transfer(address _to, uint256 _value) returns (bool success) {
        //Default assumes totalSupply can't be over max (2^256 - 1).
        //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
        //Replace the if with this one instead.
        if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
        //if (balances[msg.sender] >= _value && _value > 0) {
          balances[msg.sender] -= _value;
          balances[_to] += _value;
          Transfer(msg.sender, _to, _value);
          return true;
        } else { return false; }
      }
    
      function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        //same as above. Replace this line with the following if you want to protect against wrapping uints.
        if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
        //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
          balances[_to] += _value;
          balances[_from] -= _value;
          allowed[_from][msg.sender] -= _value;
          Transfer(_from, _to, _value);
          return true;
        } else { return false; }
      }
    
      function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
      }
    
      function approve(address _spender, uint256 _value) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
      }
    
      function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
      }
    
      mapping(address => uint256) balances;
    
      mapping (address => mapping (address => uint256)) allowed;
    
      uint256 public totalSupply;
    }
    
    contract ReserveToken is StandardToken, SafeMath {
      address public minter;
      function ReserveToken() {
        minter = msg.sender;
      }
      function create(address account, uint amount) {
        if (msg.sender != minter) throw;
        balances[account] = safeAdd(balances[account], amount);
        totalSupply = safeAdd(totalSupply, amount);
      }
      function destroy(address account, uint amount) {
        if (msg.sender != minter) throw;
        if (balances[account] < amount) throw;
        balances[account] = safeSub(balances[account], amount);
        totalSupply = safeSub(totalSupply, amount);
      }
    }
    
    contract AccountLevels {
      //given a user, returns an account level
      //0 = regular user (pays take fee and make fee)
      //1 = market maker silver (pays take fee, no make fee, gets rebate)
      //2 = market maker gold (pays take fee, no make fee, gets entire counterparty's take fee as rebate)
      function accountLevel(address user) constant returns(uint) {}
    }
    
    contract AccountLevelsTest is AccountLevels {
      mapping (address => uint) public accountLevels;
    
      function setAccountLevel(address user, uint level) {
        accountLevels[user] = level;
      }
    
      function accountLevel(address user) constant returns(uint) {
        return accountLevels[user];
      }
    }
    
    contract EtherDelta is SafeMath {
      address public admin; //the admin address
      address public feeAccount; //the account that will receive fees
      address public accountLevelsAddr; //the address of the AccountLevels contract
      uint public feeMake; //percentage times (1 ether)
      uint public feeTake; //percentage times (1 ether)
      uint public feeRebate; //percentage times (1 ether)
      mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
      mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
      mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
    
      event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
      event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
      event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
      event Deposit(address token, address user, uint amount, uint balance);
      event Withdraw(address token, address user, uint amount, uint balance);
    
      function EtherDelta(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) {
        admin = admin_;
        feeAccount = feeAccount_;
        accountLevelsAddr = accountLevelsAddr_;
        feeMake = feeMake_;
        feeTake = feeTake_;
        feeRebate = feeRebate_;
      }
    
      function() {
        throw;
      }
    
      function changeAdmin(address admin_) {
        if (msg.sender != admin) throw;
        admin = admin_;
      }
    
      function changeAccountLevelsAddr(address accountLevelsAddr_) {
        if (msg.sender != admin) throw;
        accountLevelsAddr = accountLevelsAddr_;
      }
    
      function changeFeeAccount(address feeAccount_) {
        if (msg.sender != admin) throw;
        feeAccount = feeAccount_;
      }
    
      function changeFeeMake(uint feeMake_) {
        if (msg.sender != admin) throw;
        if (feeMake_ > feeMake) throw;
        feeMake = feeMake_;
      }
    
      function changeFeeTake(uint feeTake_) {
        if (msg.sender != admin) throw;
        if (feeTake_ > feeTake || feeTake_ < feeRebate) throw;
        feeTake = feeTake_;
      }
    
      function changeFeeRebate(uint feeRebate_) {
        if (msg.sender != admin) throw;
        if (feeRebate_ < feeRebate || feeRebate_ > feeTake) throw;
        feeRebate = feeRebate_;
      }
    
      function deposit() payable {
        tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value);
        Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
      }
    
      function withdraw(uint amount) {
        if (tokens[0][msg.sender] < amount) throw;
        tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount);
        if (!msg.sender.call.value(amount)()) throw;
        Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
      }
    
      function depositToken(address token, uint amount) {
        //remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
        if (token==0) throw;
        if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
        tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
        Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
      }
    
      function withdrawToken(address token, uint amount) {
        if (token==0) throw;
        if (tokens[token][msg.sender] < amount) throw;
        tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
        if (!Token(token).transfer(msg.sender, amount)) throw;
        Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
      }
    
      function balanceOf(address token, address user) constant returns (uint) {
        return tokens[token][user];
      }
    
      function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) {
        bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
        orders[msg.sender][hash] = true;
        Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
      }
    
      function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) {
        //amount is in amountGet terms
        bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
        if (!(
          (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
          block.number <= expires &&
          safeAdd(orderFills[user][hash], amount) <= amountGet
        )) throw;
        tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
        orderFills[user][hash] = safeAdd(orderFills[user][hash], amount);
        Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
      }
    
      function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
        uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether);
        uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
        uint feeRebateXfer = 0;
        if (accountLevelsAddr != 0x0) {
          uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
          if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether);
          if (accountLevel==2) feeRebateXfer = feeTakeXfer;
        }
        tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
        tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer));
        tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));
        tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
        tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);
      }
    
      function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) {
        if (!(
          tokens[tokenGet][sender] >= amount &&
          availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
        )) return false;
        return true;
      }
    
      function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
        bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
        if (!(
          (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
          block.number <= expires
        )) return 0;
        uint available1 = safeSub(amountGet, orderFills[user][hash]);
        uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive;
        if (available1<available2) return available1;
        return available2;
      }
    
      function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
        bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
        return orderFills[user][hash];
      }
    
      function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) {
        bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
        if (!(orders[msg.sender][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == msg.sender)) throw;
        orderFills[msg.sender][hash] = amountGet;
        Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
      }
    }

    File 2 of 2: LLToken
    pragma solidity ^0.4.13;
    
    contract ERC20Basic {
      uint256 public totalSupply;
      function balanceOf(address who) constant returns (uint256);
      function transfer(address to, uint256 value) returns (bool);
      event Transfer(address indexed from, address indexed to, uint256 value);
    }
    
    contract ERC20 is ERC20Basic {
      function allowance(address owner, address spender) constant returns (uint256);
      function transferFrom(address from, address to, uint256 value) returns (bool);
      function approve(address spender, uint256 value) returns (bool);
      event Approval(address indexed owner, address indexed spender, uint256 value);
    }
    
    contract ReentrancyGuard {
    
      /**
       * @dev We use a single lock for the whole contract.
       */
      bool private rentrancy_lock = false;
    
      /**
       * @dev Prevents a contract from calling itself, directly or indirectly.
       * @notice If you mark a function `nonReentrant`, you should also
       * mark it `external`. Calling one nonReentrant function from
       * another is not supported. Instead, you can implement a
       * `private` function doing the actual work, and a `external`
       * wrapper marked as `nonReentrant`.
       */
      modifier nonReentrant() {
        require(!rentrancy_lock);
        rentrancy_lock = true;
        _;
        rentrancy_lock = false;
      }
    
    }
    
    contract Ownable {
      address public owner;
    
    
      /**
       * @dev The Ownable constructor sets the original `owner` of the contract to the sender
       * account.
       */
      function Ownable() {
        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 {
        require(newOwner != address(0));
        owner = newOwner;
      }
    
    }
    
    contract Claimable is Ownable {
      address public pendingOwner;
    
      /**
       * @dev Modifier throws if called by any account other than the pendingOwner.
       */
      modifier onlyPendingOwner() {
        require(msg.sender == pendingOwner);
        _;
      }
    
      /**
       * @dev Allows the current owner to set the pendingOwner address.
       * @param newOwner The address to transfer ownership to.
       */
      function transferOwnership(address newOwner) onlyOwner {
        pendingOwner = newOwner;
      }
    
      /**
       * @dev Allows the pendingOwner address to finalize the transfer.
       */
      function claimOwnership() onlyPendingOwner {
        owner = pendingOwner;
        pendingOwner = 0x0;
      }
    }
    
    contract Operational is Claimable {
        address public operator;
    
        function Operational(address _operator) {
          operator = _operator;
        }
    
        modifier onlyOperator() {
          require(msg.sender == operator);
          _;
        }
    
        function transferOperator(address newOperator) onlyOwner {
          require(newOperator != address(0));
          operator = newOperator;
        }
    
    }
    
    library SafeMath {
      function mul(uint256 a, uint256 b) internal constant returns (uint256) {
        uint256 c = a * b;
        assert(a == 0 || c / a == b);
        return c;
      }
    
      function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
        assert(b <= a);
        return a - b;
      }
    
      function add(uint256 a, uint256 b) internal constant returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
      }
    }
    
    contract BasicToken is ERC20Basic {
      using SafeMath for uint256;
    
      mapping(address => uint256) balances;
    
      /**
      * @dev transfer token for a specified address
      * @param _to The address to transfer to.
      * @param _value The amount to be transferred.
      */
      function transfer(address _to, uint256 _value) returns (bool) {
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        Transfer(msg.sender, _to, _value);
        return true;
      }
    
      /**
      * @dev Gets the balance of the specified address.
      * @param _owner The address to query the the balance of.
      * @return An uint256 representing the amount owned by the passed address.
      */
      function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
      }
    
    }
    
    contract StandardToken is ERC20, BasicToken {
    
      mapping (address => mapping (address => uint256)) allowed;
    
    
      /**
       * @dev Transfer tokens from one address to another
       * @param _from address The address which you want to send tokens from
       * @param _to address The address which you want to transfer to
       * @param _value uint256 the amout of tokens to be transfered
       */
      function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
        var _allowance = allowed[_from][msg.sender];
    
        // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
        // require (_value <= _allowance);
    
        balances[_to] = balances[_to].add(_value);
        balances[_from] = balances[_from].sub(_value);
        allowed[_from][msg.sender] = _allowance.sub(_value);
        Transfer(_from, _to, _value);
        return true;
      }
    
      /**
       * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
       * @param _spender The address which will spend the funds.
       * @param _value The amount of tokens to be spent.
       */
      function approve(address _spender, uint256 _value) returns (bool) {
    
        // To change the approve amount you first have to reduce the addresses`
        //  allowance to zero by calling `approve(_spender, 0)` if it is not
        //  already 0 to mitigate the race condition described here:
        //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
        require((_value == 0) || (allowed[msg.sender][_spender] == 0));
    
        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 specifing the amount of tokens still available for the spender.
       */
      function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
        return allowed[_owner][_spender];
      }
    
    }
    
    contract LockableToken is StandardToken, ReentrancyGuard {
    
        struct LockedBalance {
            address owner;
            uint256 value;
            uint256 releaseTime;
        }
    
        mapping (uint => LockedBalance) public lockedBalances;
        uint public lockedBalanceCount;
    
        event TransferLockedToken(address indexed from, address indexed to, uint256 value, uint256 releaseTime);
        event ReleaseLockedBalance(address indexed owner, uint256 value, uint256 releaseTime);
    
        // 给 _to 转移 _value 个锁定到 _releaseTime 的 token
        function transferLockedToken(address _to, uint256 _value, uint256 _releaseTime) nonReentrant returns (bool) {
            require(_releaseTime > now);
            require(_releaseTime.sub(1 years) < now);
            balances[msg.sender] = balances[msg.sender].sub(_value);
            lockedBalances[lockedBalanceCount] = LockedBalance({owner: _to, value: _value, releaseTime: _releaseTime});
            lockedBalanceCount++;
            TransferLockedToken(msg.sender, _to, _value, _releaseTime);
            return true;
        }
    
        // 查 address 的锁定余额
        function lockedBalanceOf(address _owner) constant returns (uint256 value) {
            for (uint i = 0; i < lockedBalanceCount; i++) {
                LockedBalance lockedBalance = lockedBalances[i];
                if (_owner == lockedBalance.owner) {
                    value = value.add(lockedBalance.value);
                }
            }
            return value;
        }
    
        // 解锁所有已到锁定时间的 token
        function releaseLockedBalance () returns (uint256 releaseAmount) {
            uint index = 0;
            while (index < lockedBalanceCount) {
                if (now >= lockedBalances[index].releaseTime) {
                    releaseAmount += lockedBalances[index].value;
                    unlockBalanceByIndex(index);
                } else {
                    index++;
                }
            }
            return releaseAmount;
        }
    
        function unlockBalanceByIndex (uint index) internal {
            LockedBalance lockedBalance = lockedBalances[index];
            balances[lockedBalance.owner] = balances[lockedBalance.owner].add(lockedBalance.value);
            ReleaseLockedBalance(lockedBalance.owner, lockedBalance.value, lockedBalance.releaseTime);
            lockedBalances[index] = lockedBalances[lockedBalanceCount - 1];
            delete lockedBalances[lockedBalanceCount - 1];
            lockedBalanceCount--;
        }
    
    }
    
    library DateTime {
            /*
             *  Date and Time utilities for ethereum contracts
             *
             */
            struct DateTime {
                    uint16 year;
                    uint8 month;
                    uint8 day;
                    uint8 hour;
                    uint8 minute;
                    uint8 second;
                    uint8 weekday;
            }
    
            uint constant DAY_IN_SECONDS = 86400;
            uint constant YEAR_IN_SECONDS = 31536000;
            uint constant LEAP_YEAR_IN_SECONDS = 31622400;
    
            uint constant HOUR_IN_SECONDS = 3600;
            uint constant MINUTE_IN_SECONDS = 60;
    
            uint16 constant ORIGIN_YEAR = 1970;
    
            function isLeapYear(uint16 year) constant returns (bool) {
                    if (year % 4 != 0) {
                            return false;
                    }
                    if (year % 100 != 0) {
                            return true;
                    }
                    if (year % 400 != 0) {
                            return false;
                    }
                    return true;
            }
    
            function leapYearsBefore(uint year) constant returns (uint) {
                    year -= 1;
                    return year / 4 - year / 100 + year / 400;
            }
    
            function getDaysInMonth(uint8 month, uint16 year) constant returns (uint8) {
                    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                            return 31;
                    }
                    else if (month == 4 || month == 6 || month == 9 || month == 11) {
                            return 30;
                    }
                    else if (isLeapYear(year)) {
                            return 29;
                    }
                    else {
                            return 28;
                    }
            }
    
            function parseTimestamp(uint timestamp) internal returns (DateTime dt) {
                    uint secondsAccountedFor = 0;
                    uint buf;
                    uint8 i;
    
                    // Year
                    dt.year = getYear(timestamp);
                    buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
    
                    secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
                    secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
    
                    // Month
                    uint secondsInMonth;
                    for (i = 1; i <= 12; i++) {
                            secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
                            if (secondsInMonth + secondsAccountedFor > timestamp) {
                                    dt.month = i;
                                    break;
                            }
                            secondsAccountedFor += secondsInMonth;
                    }
    
                    // Day
                    for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
                            if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
                                    dt.day = i;
                                    break;
                            }
                            secondsAccountedFor += DAY_IN_SECONDS;
                    }
    
                    // Hour
                    dt.hour = 0;//getHour(timestamp);
    
                    // Minute
                    dt.minute = 0;//getMinute(timestamp);
    
                    // Second
                    dt.second = 0;//getSecond(timestamp);
    
                    // Day of week.
                    dt.weekday = 0;//getWeekday(timestamp);
    
            }
    
            function getYear(uint timestamp) constant returns (uint16) {
                    uint secondsAccountedFor = 0;
                    uint16 year;
                    uint numLeapYears;
    
                    // Year
                    year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
                    numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
    
                    secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
                    secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
    
                    while (secondsAccountedFor > timestamp) {
                            if (isLeapYear(uint16(year - 1))) {
                                    secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
                            }
                            else {
                                    secondsAccountedFor -= YEAR_IN_SECONDS;
                            }
                            year -= 1;
                    }
                    return year;
            }
    
            function getMonth(uint timestamp) constant returns (uint8) {
                    return parseTimestamp(timestamp).month;
            }
    
            function getDay(uint timestamp) constant returns (uint8) {
                    return parseTimestamp(timestamp).day;
            }
    
            function getHour(uint timestamp) constant returns (uint8) {
                    return uint8((timestamp / 60 / 60) % 24);
            }
    
            function getMinute(uint timestamp) constant returns (uint8) {
                    return uint8((timestamp / 60) % 60);
            }
    
            function getSecond(uint timestamp) constant returns (uint8) {
                    return uint8(timestamp % 60);
            }
    
            function toTimestamp(uint16 year, uint8 month, uint8 day) constant returns (uint timestamp) {
                    return toTimestamp(year, month, day, 0, 0, 0);
            }
    
            function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) constant returns (uint timestamp) {
                    uint16 i;
    
                    // Year
                    for (i = ORIGIN_YEAR; i < year; i++) {
                            if (isLeapYear(i)) {
                                    timestamp += LEAP_YEAR_IN_SECONDS;
                            }
                            else {
                                    timestamp += YEAR_IN_SECONDS;
                            }
                    }
    
                    // Month
                    uint8[12] memory monthDayCounts;
                    monthDayCounts[0] = 31;
                    if (isLeapYear(year)) {
                            monthDayCounts[1] = 29;
                    }
                    else {
                            monthDayCounts[1] = 28;
                    }
                    monthDayCounts[2] = 31;
                    monthDayCounts[3] = 30;
                    monthDayCounts[4] = 31;
                    monthDayCounts[5] = 30;
                    monthDayCounts[6] = 31;
                    monthDayCounts[7] = 31;
                    monthDayCounts[8] = 30;
                    monthDayCounts[9] = 31;
                    monthDayCounts[10] = 30;
                    monthDayCounts[11] = 31;
    
                    for (i = 1; i < month; i++) {
                            timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];
                    }
    
                    // Day
                    timestamp += DAY_IN_SECONDS * (day - 1);
    
                    // Hour
                    timestamp += HOUR_IN_SECONDS * (hour);
    
                    // Minute
                    timestamp += MINUTE_IN_SECONDS * (minute);
    
                    // Second
                    timestamp += second;
    
                    return timestamp;
            }
    }
    
    contract ReleaseableToken is Operational, LockableToken {
        using SafeMath for uint;
        using DateTime for uint256;
        bool secondYearUpdate = false; // Limit 更新到第二年
        uint256 public releasedSupply; // 已释放的数量
        uint256 public createTime; // 合约创建时间
        uint256 standardDecimals = 100000000; // 由于有8位小数,传进来的参数都是不带后面的小数,要有乘100000000的操作才能保证数量级一致
        uint256 public totalSupply = standardDecimals.mul(1000000000); // 总量10亿
        uint256 public limitSupplyPerYear = standardDecimals.mul(60000000); // 每年释放的LLT的限额,第一年6000万
        uint256 public dailyLimit = standardDecimals.mul(1000000); // 每天释放的限额
    
        event ReleaseSupply(address receiver, uint256 value, uint256 releaseTime);
        event UnfreezeAmount(address receiver, uint256 amount, uint256 unfreezeTime);
    
        struct FrozenRecord {
            uint256 amount; // 冻结的数量
            uint256 unfreezeTime; // 解冻的时间
        }
    
        mapping (uint => FrozenRecord) public frozenRecords;
        uint public frozenRecordsCount = 0;
    
        function ReleaseableToken(
                        uint256 initialSupply,
                        uint256 initReleasedSupply,
                        address operator
                    ) Operational(operator) {
            totalSupply = initialSupply;
            releasedSupply = initReleasedSupply;
            createTime = now;
            balances[msg.sender] = initReleasedSupply;
        }
    
        // 在 timestamp 时间点释放 releaseAmount 的 token
        function releaseSupply(uint256 releaseAmount, uint256 timestamp) onlyOperator returns(uint256 _actualRelease) {
            require(timestamp >= createTime && timestamp <= now);
            require(!judgeReleaseRecordExist(timestamp));
            require(releaseAmount <= dailyLimit);
            updateLimit();
            require(limitSupplyPerYear > 0);
            if (releaseAmount > limitSupplyPerYear) {
                if (releasedSupply.add(limitSupplyPerYear) > totalSupply) {
                    releasedSupply = totalSupply;
                    releaseAmount = totalSupply.sub(releasedSupply);
                } else {
                    releasedSupply = releasedSupply.add(limitSupplyPerYear);
                    releaseAmount = limitSupplyPerYear;
                }
                limitSupplyPerYear = 0;
            } else {
                if (releasedSupply.add(releaseAmount) > totalSupply) {
                    releasedSupply = totalSupply;
                    releaseAmount = totalSupply.sub(releasedSupply);
                } else {
                    releasedSupply = releasedSupply.add(releaseAmount);
                }
                limitSupplyPerYear = limitSupplyPerYear.sub(releaseAmount);
            }
            frozenRecords[frozenRecordsCount] = FrozenRecord(releaseAmount, timestamp.add(26 * 1 weeks));
            frozenRecordsCount++;
            ReleaseSupply(msg.sender, releaseAmount, timestamp);
            return releaseAmount;
        }
    
        // 判断 timestamp 这一天有没有已经释放的记录
        function judgeReleaseRecordExist(uint256 timestamp) internal returns(bool _exist) {
            bool exist = false;
            if (frozenRecordsCount > 0) {
                for (uint index = 0; index < frozenRecordsCount; index++) {
                    if ((frozenRecords[index].unfreezeTime.parseTimestamp().year == (timestamp.add(26 * 1 weeks)).parseTimestamp().year)
                        && (frozenRecords[index].unfreezeTime.parseTimestamp().month == (timestamp.add(26 * 1 weeks)).parseTimestamp().month)
                        && (frozenRecords[index].unfreezeTime.parseTimestamp().day == (timestamp.add(26 * 1 weeks)).parseTimestamp().day)) {
                        exist = true;
                    }
                }
            }
            return exist;
        }
    
        // 更新每年释放token的限制数量
        function updateLimit() internal {
            if (createTime.add(1 years) < now && !secondYearUpdate) {
                limitSupplyPerYear = standardDecimals.mul(120000000);
                secondYearUpdate = true;
            }
            if (createTime.add(2 * 1 years) < now) {
                if (releasedSupply < totalSupply) {
                    limitSupplyPerYear = totalSupply.sub(releasedSupply);
                }
            }
        }
    
        // 解冻 releaseSupply 中释放的 token
        function unfreeze() onlyOperator returns(uint256 _unfreezeAmount) {
            uint256 unfreezeAmount = 0;
            uint index = 0;
            while (index < frozenRecordsCount) {
                if (frozenRecords[index].unfreezeTime < now) {
                    unfreezeAmount += frozenRecords[index].amount;
                    unfreezeByIndex(index);
                } else {
                    index++;
                }
            }
            return unfreezeAmount;
        }
    
        function unfreezeByIndex (uint index) internal {
            FrozenRecord unfreezeRecord = frozenRecords[index];
            balances[owner] = balances[owner].add(unfreezeRecord.amount);
            UnfreezeAmount(owner, unfreezeRecord.amount, unfreezeRecord.unfreezeTime);
            frozenRecords[index] = frozenRecords[frozenRecordsCount - 1];
            delete frozenRecords[frozenRecordsCount - 1];
            frozenRecordsCount--;
        }
    
        // 设置每天释放 token 的限额
        function setDailyLimit(uint256 _dailyLimit) onlyOwner {
            dailyLimit = _dailyLimit;
        }
    }
    
    contract LLToken is ReleaseableToken {
        string public standard = '2017082602';
        string public name = 'LLToken';
        string public symbol = 'LLT';
        uint8 public decimals = 8;
    
        function LLToken(
                         uint256 initialSupply,
                         uint256 initReleasedSupply,
                         address operator
                         ) ReleaseableToken(initialSupply, initReleasedSupply, operator) {}
    }