Skip to content
Verified contractPartial

AxieRedemption

Address0xae8e74a21c25c22112749f7a9cd600d4b5cb2191
Balance

1.04254 ETH

 

Transactions

413

 

Compiler

solc 0.4.23

 

Same code

Only this contract

 

Details

Compiler
solc 0.4.23+commit.124ca40d
Language
solidity
Optimization
Yes, 200 runs
EVM version
byzantium
License
Not stated
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
5,555,626
Creation transaction
0x73aa972aaa…e0b9dbbcc5

contracts/presale/AxieRedemption.sol

pragma solidity ^0.4.19;


import "oraclize-api/contracts/usingOraclize.sol";

import "./AxieRedemptionInternal.sol";


contract AxieRedemption is AxieRedemptionInternal, usingOraclize {
  function _startTimestamp() internal returns (uint256) {
    // Wednesday, March 14, 2018 4:00:00 AM.
    return 1521000000;
  }

  function _sendRandomQuery(uint256 _gasLimit) internal returns (uint256) {
    return uint256(oraclize_query("WolframAlpha", "random number between 1 and 2^64", _gasLimit));
  }

  // solium-disable-next-line function-order, mixedcase
  function __callback(bytes32 _queryId, string _result) public {
    require(msg.sender == oraclize_cbAddress());
    _receiveRandomQuery(uint256(_queryId), _result);
  }
}

contracts/core/AxieCoreExtraInterface.sol

pragma solidity ^0.4.23;


contract AxieCoreExtraInterface {
  function getExtra(
    uint256 _axieId
  )
    external
    view
    returns (
      uint256 _sireId,
      uint256 _matronId,
      uint256 _exp,
      uint256 _numBreeding
    );

  function spawn(
    uint256 _genes,
    uint256 _sireId,
    uint256 _matronId,
    uint256 _exp,
    address _owner
  )
    external
    returns (uint256 _axieId);

  function updateExp(
    uint256 _axieId,
    uint256 _exp
  )
    external;

  function updateNumBreeding(
    uint256 _axieId,
    uint256 _numBreeding
  )
    external;

  function isEligibleForPairing(
    uint256 _sireId,
    uint256 _matronId
  )
    external
    view
    returns (bool _eligible);
}

contracts/erc/erc20/ERC20.sol

pragma solidity ^0.4.23;


import "zeppelin/contracts/math/SafeMath.sol";
import "./ERC20Interface.sol";


/**
 * @title An implementation of the ERC-20 Token Standard.
 * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md.
 */
contract ERC20 is ERC20Interface {
  using SafeMath for uint256;

  uint256 internal _totalSupply;
  mapping (address => uint256) internal _balance;
  mapping (address => mapping (address => uint256)) internal _allowed;

  /**
   * @notice Returns the total token supply.
   * @return The supply.
   */
  function totalSupply() public view returns (uint256) {
    return _totalSupply;
  }

  /**
   * @notice Returns the balance of an account with address `_owner`.
   * @return The account balance.
   */
  function balanceOf(address _owner) public view returns (uint256) {
    return _balance[_owner];
  }

  /**
   * @notice Transfers `_value` amount of tokens to address `_to`.
   *
   * @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) public returns (bool) {
    require(_to != address(0));

    _balance[msg.sender] = _balance[msg.sender].sub(_value);
    _balance[_to] = _balance[_to].add(_value);

    emit Transfer(msg.sender, _to, _value);

    return true;
  }

  /**
   * @notice Transfers `_value` amount of tokens from address `_from` to address `_to`.
   *
   * @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) public returns (bool) {
    require(_to != address(0));

    _balance[_from] = _balance[_from].sub(_value);
    _balance[_to] = _balance[_to].add(_value);
    _allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(_value);

    emit Transfer(_from, _to, _value);

    return true;
  }

  /**
   * @notice Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount.
   *   If this function is called again it overwrites the current allowance with `_value`.
   *
   * @param _spender The address of the account able to transfer the tokens.
   * @param _value The amount of tokens to be approved for transfer.
   *
   * @return Whether the approval was successful or not.
   */
  function approve(address _spender, uint256 _value) public returns (bool) {
    _allowed[msg.sender][_spender] = _value;
    emit Approval(msg.sender, _spender, _value);
    return true;
  }

  /**
   * @notice Returns the amount which `_spender` is still allowed to withdraw from `_owner`.
   *
   * @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) public view returns (uint256) {
    return _allowed[_owner][_spender];
  }
}

contracts/erc/erc20/ERC20Burnable.sol

pragma solidity ^0.4.23;


import "./ERC20.sol";


/**
 * @title An implementation of the ERC-20 Token Standard
 *   which allows tokens to be burnt.
 */
contract ERC20Burnable is ERC20 {
  event Burn(address indexed burner, uint256 value);

  function burn(uint256 _value) public returns (bool) {
    _balance[msg.sender] = _balance[msg.sender].sub(_value);
    _totalSupply = _totalSupply.sub(_value);

    emit Transfer(msg.sender, address(0), _value);
    emit Burn(msg.sender, _value);

    return true;
  }

  function burnFrom(address _from, uint256 _value) public returns (bool) {
    _balance[_from] = _balance[_from].sub(_value);
    _totalSupply = _totalSupply.sub(_value);
    _allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(_value);

    emit Transfer(_from, address(0), _value);
    emit Burn(_from, _value);

    return true;
  }
}

contracts/erc/erc20/ERC20DetailedInterface.sol

pragma solidity ^0.4.23;


import "./ERC20Interface.sol";


/**
 * @title Contains optional methods which give some detailed information about the token
 *   in ERC-20 Token Standard.
 * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md.
 */
contract ERC20DetailedInterface is ERC20Interface {
  /**
   * @notice Returns the name of the token.
   * @return The name.
   */
  function name() public view returns (string _name);

  /**
   * @notice Returns the name of the token.
   * @return The symbol.
   */
  function symbol() public view returns (string _symbol);

  /**
   * @notice Returns the number of decimals the token uses.
   * @dev For example, 8 means to divide the token amount by 100,000,000
   *   to get its user representation.
   * @return The number of decimals.
   */
  function decimals() public view returns (uint8 _decimals);
}

contracts/erc/erc20/ERC20Extended.sol

pragma solidity ^0.4.23;


import "./ERC20.sol";
import "./ERC20RecipientInterface.sol";


/**
 * @title An implementation of the ERC-20 Token Standard
 *   which implements `approveAndCall` function according to the extended standard.
 */
contract ERC20Extended is ERC20 {
  /**
   * @notice Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount.
   *   After the approval, executes `receiveApproval` function on `_spender`.
   *   If this function is called again it overwrites the current allowance with `_value`.
   *
   * @param _spender The address that will spend the funds.
   * @param _value The amount of tokens to be spent.
   * @param _data Additional data to be passed to `receiveApproval` function on `_spender`.
   *
   * @return Whether the approval was successful or not.
   */
  function approveAndCall(address _spender, uint256 _value, bytes _data) public returns (bool) {
    require(approve(_spender, _value));
    ERC20RecipientInterface(_spender).receiveApproval(msg.sender, _value, this, _data);
    return true;
  }
}

contracts/erc/erc20/ERC20Interface.sol

pragma solidity ^0.4.23;


/**
 * @title ERC-20 Token Standard.
 * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md.
 */
contract ERC20Interface {
  /**
   * @dev MUST trigger when tokens are transferred, including zero value transfers.
   * @dev A token contract which creates new tokens SHOULD trigger a `Transfer` event
   *   with the `_from` address set to `0x0` when tokens are created.
   */
  event Transfer(address indexed _from, address indexed _to, uint256 _value);

  /**
   * @dev MUST trigger on any successful call to `approve(address _spender, uint256 _value)`.
   */
  event Approval(address indexed _owner, address indexed _spender, uint256 _value);

  /**
   * @notice Returns the total token supply.
   * @return The supply.
   */
  function totalSupply() public view returns (uint256 _supply);

  /**
   * @notice Returns the balance of an account with address `_owner`.
   * @return The account balance.
   */
  function balanceOf(address _owner) public view returns (uint256 _balance);

  /**
   * @notice Transfers `_value` amount of tokens to address `_to`.
   *
   * @param _to The address of the recipient.
   * @param _value The amount of token to be transferred.
   *
   * @dev The function MUST fire the `Transfer` event.
   * @dev The function SHOULD throw if the `_from` account balance does not have enough tokens to spend.
   * @dev Transfers of 0 values MUST be treated as normal transfers and fire the `Transfer` event.
   *
   * @return Whether the transfer was successful or not.
   */
  function transfer(address _to, uint256 _value) public returns (bool _success);

  /**
   * @notice Transfers `_value` amount of tokens from address `_from` to address `_to`.
   *
   * @param _from The address of the sender.
   * @param _to The address of the recipient.
   * @param _value The amount of token to be transferred.
   *
   * @dev The `transferFrom` method is used for a withdraw workflow,
   *   allowing contracts to transfer tokens on your behalf.
   *   This can be used for example to allow a contract to transfer tokens on your behalf
   *   and/or to charge fees in sub-currencies.
   * @dev The function MUST fire the `Transfer` event.
   * @dev The function SHOULD throw unless the `_from` account
   *   has deliberately authorized the sender of the message via some mechanism.
   * @dev Transfers of 0 values MUST be treated as normal transfers and fire the `Transfer` event.
   *
   * @return Whether the transfer was successful or not.
   */
  function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success);

  /**
   * @notice Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount.
   *   If this function is called again it overwrites the current allowance with `_value`.
   *
   * @param _spender The address of the account able to transfer the tokens.
   * @param _value The amount of tokens to be approved for transfer.
   *
   * @dev To prevent attack vectors like the one described in
   *   https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/
   *   and discussed in
   *   https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729,
   *   clients SHOULD make sure to create user interfaces in such a way
   *   that they set the allowance first to 0 before setting it to another value for the same spender.
   *   THOUGH The contract itself shouldn't enforce it,
   *   to allow backwards compatibility with contracts deployed before.
   *
   * @return Whether the approval was successful or not.
   */
  function approve(address _spender, uint256 _value) public returns (bool _success);

  /**
   * @notice Returns the amount which `_spender` is still allowed to withdraw from `_owner`.
   *
   * @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) public view returns (uint256 _remaining);
}

contracts/erc/erc20/ERC20Mintable.sol

pragma solidity ^0.4.23;


import "zeppelin/contracts/math/SafeMath.sol";
import "zeppelin/contracts/ownership/Ownable.sol";
import "./ERC20.sol";


/**
 * @title An implementation of the ERC-20 Token Standard
 *   which allows tokens to be minted.
 */
contract ERC20Mintable is ERC20, Ownable {
  bool public mintingFinished = false;

  event Mint(address indexed to, uint256 value);
  event MintFinished();

  modifier canMint() {
    require(!mintingFinished);
    _;
  }

  function mint(address _to, uint256 _value) onlyOwner canMint public returns (bool) {
    _balance[_to] = _balance[_to].add(_value);
    _totalSupply = _totalSupply.add(_value);

    emit Mint(_to, _value);
    emit Transfer(address(0), _to, _value);

    return true;
  }

  function finishMinting() onlyOwner canMint public returns (bool) {
    mintingFinished = true;
    emit MintFinished();
    return true;
  }
}

contracts/erc/erc20/ERC20RecipientInterface.sol

pragma solidity ^0.4.23;


interface ERC20RecipientInterface {
  function receiveApproval(address _from, uint256 _value, address _erc20Address, bytes _data) external;
}

contracts/presale/AxiePresale.sol

pragma solidity ^0.4.19;


import "zeppelin/contracts/lifecycle/Pausable.sol";
import "zeppelin/contracts/math/SafeMath.sol";
import "zeppelin/contracts/ownership/HasNoEther.sol";


contract AxiePresale is HasNoEther, Pausable {
  using SafeMath for uint256;

  // No Axies can be adopted after this end date: Friday, March 16, 2018 11:59:59 PM GMT.
  // uint256 constant public PRESALE_END_TIMESTAMP = 1521244799;

  // Modified for development purpose.
  uint256 constant public PRESALE_END_TIMESTAMP = 9999999999;

  uint8 constant public CLASS_BEAST = 0;
  uint8 constant public CLASS_AQUATIC = 2;
  uint8 constant public CLASS_PLANT = 4;

  uint256 constant public INITIAL_PRICE_INCREMENT = 1600 szabo; // 0.0016 Ether
  uint256 constant public INITIAL_PRICE = INITIAL_PRICE_INCREMENT;
  uint256 constant public REF_CREDITS_PER_AXIE = 5;

  mapping (uint8 => uint256) public currentPrices;
  mapping (uint8 => uint256) public priceIncrements;

  mapping (uint8 => uint256) public totalAxiesAdopted;
  mapping (address => mapping (uint8 => uint256)) public axiesAdopted;

  mapping (address => uint256) public referralCredits;
  mapping (address => uint256) public axiesRewarded;
  uint256 public totalAxiesRewarded;

  event AxiesAdopted(
    address indexed adopter,
    uint8 indexed clazz,
    uint256 quantity,
    address indexed referrer
  );

  event AxiesRewarded(address indexed receiver, uint256 quantity);

  event AdoptedAxiesRedeemed(address indexed receiver, uint8 indexed clazz, uint256 quantity);
  event RewardedAxiesRedeemed(address indexed receiver, uint256 quantity);

  constructor() public {
    priceIncrements[CLASS_BEAST] = priceIncrements[CLASS_AQUATIC] = //
      priceIncrements[CLASS_PLANT] = INITIAL_PRICE_INCREMENT;

    currentPrices[CLASS_BEAST] = currentPrices[CLASS_AQUATIC] = //
      currentPrices[CLASS_PLANT] = INITIAL_PRICE;
  }

  function axiesPrice(
    uint256 beastQuantity,
    uint256 aquaticQuantity,
    uint256 plantQuantity
  )
    public
    view
    returns (uint256 totalPrice)
  {
    uint256 price;

    (price,,) = _axiesPrice(CLASS_BEAST, beastQuantity);
    totalPrice = totalPrice.add(price);

    (price,,) = _axiesPrice(CLASS_AQUATIC, aquaticQuantity);
    totalPrice = totalPrice.add(price);

    (price,,) = _axiesPrice(CLASS_PLANT, plantQuantity);
    totalPrice = totalPrice.add(price);
  }

  function adoptAxies(
    uint256 beastQuantity,
    uint256 aquaticQuantity,
    uint256 plantQuantity,
    address referrer
  )
    public
    payable
    whenNotPaused
  {
    require(now <= PRESALE_END_TIMESTAMP);

    require(beastQuantity <= 3);
    require(aquaticQuantity <= 3);
    require(plantQuantity <= 3);

    address adopter = msg.sender;
    address actualReferrer = 0x0;

    // An adopter cannot be his/her own referrer.
    if (referrer != adopter) {
      actualReferrer = referrer;
    }

    uint256 value = msg.value;
    uint256 price;

    if (beastQuantity > 0) {
      price = _adoptAxies(
        adopter,
        CLASS_BEAST,
        beastQuantity,
        actualReferrer
      );

      require(value >= price);
      value -= price;
    }

    if (aquaticQuantity > 0) {
      price = _adoptAxies(
        adopter,
        CLASS_AQUATIC,
        aquaticQuantity,
        actualReferrer
      );

      require(value >= price);
      value -= price;
    }

    if (plantQuantity > 0) {
      price = _adoptAxies(
        adopter,
        CLASS_PLANT,
        plantQuantity,
        actualReferrer
      );

      require(value >= price);
      value -= price;
    }

    msg.sender.transfer(value);

    // The current referral is ignored if the referrer's address is 0x0.
    if (actualReferrer != 0x0) {
      uint256 numCredit = referralCredits[actualReferrer]
        .add(beastQuantity)
        .add(aquaticQuantity)
        .add(plantQuantity);

      uint256 numReward = numCredit / REF_CREDITS_PER_AXIE;

      if (numReward > 0) {
        referralCredits[actualReferrer] = numCredit % REF_CREDITS_PER_AXIE;
        axiesRewarded[actualReferrer] = axiesRewarded[actualReferrer].add(numReward);
        totalAxiesRewarded = totalAxiesRewarded.add(numReward);
        emit AxiesRewarded(actualReferrer, numReward);
      } else {
        referralCredits[actualReferrer] = numCredit;
      }
    }
  }

  function redeemAdoptedAxies(
    address receiver,
    uint256 beastQuantity,
    uint256 aquaticQuantity,
    uint256 plantQuantity
  )
    public
    onlyOwner
    returns (
      uint256 /* remainingBeastQuantity */,
      uint256 /* remainingAquaticQuantity */,
      uint256 /* remainingPlantQuantity */
    )
  {
    return (
      _redeemAdoptedAxies(receiver, CLASS_BEAST, beastQuantity),
      _redeemAdoptedAxies(receiver, CLASS_AQUATIC, aquaticQuantity),
      _redeemAdoptedAxies(receiver, CLASS_PLANT, plantQuantity)
    );
  }

  function redeemRewardedAxies(
    address receiver,
    uint256 quantity
  )
    public
    onlyOwner
    returns (uint256 remainingQuantity)
  {
    remainingQuantity = axiesRewarded[receiver] = axiesRewarded[receiver].sub(quantity);

    if (quantity > 0) {
      // This requires that rewarded Axies are always included in the total
      // to make sure overflow won't happen.
      totalAxiesRewarded -= quantity;

      emit RewardedAxiesRedeemed(receiver, quantity);
    }
  }

  /**
   * @dev Calculate price of Axies from the same class.
   * @param clazz The class of Axies.
   * @param quantity Number of Axies to be calculated.
   */
  function _axiesPrice(
    uint8 clazz,
    uint256 quantity
  )
    private
    view
    returns (uint256 totalPrice, uint256 priceIncrement, uint256 currentPrice)
  {
    priceIncrement = priceIncrements[clazz];
    currentPrice = currentPrices[clazz];

    uint256 nextPrice;

    for (uint256 i = 0; i < quantity; i++) {
      totalPrice = totalPrice.add(currentPrice);
      nextPrice = currentPrice.add(priceIncrement);

      if (nextPrice / 100 finney != currentPrice / 100 finney) {
        priceIncrement >>= 1;
      }

      currentPrice = nextPrice;
    }
  }

  /**
   * @dev Adopt some Axies from the same class.
   * @param adopter Address of the adopter.
   * @param clazz The class of adopted Axies.
   * @param quantity Number of Axies to be adopted, this should be positive.
   * @param referrer Address of the referrer.
   */
  function _adoptAxies(
    address adopter,
    uint8 clazz,
    uint256 quantity,
    address referrer
  )
    private
    returns (uint256 totalPrice)
  {
    (totalPrice, priceIncrements[clazz], currentPrices[clazz]) = _axiesPrice(clazz, quantity);

    axiesAdopted[adopter][clazz] = axiesAdopted[adopter][clazz].add(quantity);
    totalAxiesAdopted[clazz] = totalAxiesAdopted[clazz].add(quantity);

    emit AxiesAdopted(
      adopter,
      clazz,
      quantity,
      referrer
    );
  }

  /**
   * @dev Redeem adopted Axies from the same class.
   * @param receiver Address of the receiver.
   * @param clazz The class of adopted Axies.
   * @param quantity Number of adopted Axies to be redeemed.
   */
  function _redeemAdoptedAxies(
    address receiver,
    uint8 clazz,
    uint256 quantity
  )
    private
    returns (uint256 remainingQuantity)
  {
    remainingQuantity = axiesAdopted[receiver][clazz] = axiesAdopted[receiver][clazz].sub(quantity);

    if (quantity > 0) {
      // This requires that adopted Axies are always included in the total
      // to make sure overflow won't happen.
      totalAxiesAdopted[clazz] -= quantity;

      emit AdoptedAxiesRedeemed(receiver, clazz, quantity);
    }
  }
}

contracts/presale/AxiePresaleExtended.sol

pragma solidity ^0.4.19;


import "zeppelin/contracts/lifecycle/Pausable.sol";
import "zeppelin/contracts/math/SafeMath.sol";
import "zeppelin/contracts/ownership/HasNoContracts.sol";

import "./AxiePresale.sol";


contract AxiePresaleExtended is HasNoContracts, Pausable {
  using SafeMath for uint256;

  // No Axies can be adopted after this end date: Monday, April 16, 2018 11:59:59 PM GMT.
  // uint256 constant public PRESALE_END_TIMESTAMP = 1523923199;

  // Modified for development purpose.
  uint256 constant public PRESALE_END_TIMESTAMP = 9999999999;

  // The total number of adopted Axies will be capped at 5250,
  // so the number of Axies which have Mystic parts will be capped roughly at 2000.
  uint256 constant public MAX_TOTAL_ADOPTED_AXIES = 5250;

  uint8 constant public CLASS_BEAST = 0;
  uint8 constant public CLASS_AQUATIC = 2;
  uint8 constant public CLASS_PLANT = 4;

  // The initial price increment and the initial price are for reference only
  uint256 constant public INITIAL_PRICE_INCREMENT = 1600 szabo; // 0.0016 Ether
  uint256 constant public INITIAL_PRICE = INITIAL_PRICE_INCREMENT;

  uint256 constant public REF_CREDITS_PER_AXIE = 5;

  AxiePresale public presaleContract;
  address public redemptionAddress;

  mapping (uint8 => uint256) public currentPrice;
  mapping (uint8 => uint256) public priceIncrement;

  mapping (uint8 => uint256) private _totalAdoptedAxies;
  mapping (uint8 => uint256) private _totalDeductedAdoptedAxies;
  mapping (address => mapping (uint8 => uint256)) private _numAdoptedAxies;
  mapping (address => mapping (uint8 => uint256)) private _numDeductedAdoptedAxies;

  mapping (address => uint256) private _numRefCredits;
  mapping (address => uint256) private _numDeductedRefCredits;
  uint256 public numBountyCredits;

  uint256 private _totalRewardedAxies;
  uint256 private _totalDeductedRewardedAxies;
  mapping (address => uint256) private _numRewardedAxies;
  mapping (address => uint256) private _numDeductedRewardedAxies;

  event AxiesAdopted(
    address indexed _adopter,
    uint8 indexed _class,
    uint256 _quantity,
    address indexed _referrer
  );

  event AxiesRewarded(address indexed _receiver, uint256 _quantity);

  event AdoptedAxiesRedeemed(address indexed _receiver, uint8 indexed _class, uint256 _quantity);
  event RewardedAxiesRedeemed(address indexed _receiver, uint256 _quantity);

  event RefCreditsMinted(address indexed _receiver, uint256 _numMintedCredits);

  constructor() public payable {
    require(msg.value == 0);
    paused = true;
    numBountyCredits = 300;
  }

  function () external payable {
    require(msg.sender == address(presaleContract));
  }

  modifier whenNotInitialized {
    require(presaleContract == address(0));
    _;
  }

  modifier whenInitialized {
    require(presaleContract != address(0));
    _;
  }

  modifier onlyRedemptionAddress {
    require(msg.sender == redemptionAddress);
    _;
  }

  function reclaimEther() external onlyOwner whenInitialized {
    presaleContract.reclaimEther();
    owner.transfer(address(this).balance);
  }

  /**
   * @dev This must be called only once after the owner of the presale contract
   *  has been updated to this contract.
   */
  function initialize(address _presaleAddress) external onlyOwner whenNotInitialized {
    // Set the presale address.
    presaleContract = AxiePresale(_presaleAddress);

    presaleContract.pause();

    // Restore price increments from the old contract.
    priceIncrement[CLASS_BEAST] = presaleContract.priceIncrements(CLASS_BEAST);
    priceIncrement[CLASS_AQUATIC] = presaleContract.priceIncrements(CLASS_AQUATIC);
    priceIncrement[CLASS_PLANT] = presaleContract.priceIncrements(CLASS_PLANT);

    // Restore current prices from the old contract.
    currentPrice[CLASS_BEAST] = presaleContract.currentPrices(CLASS_BEAST);
    currentPrice[CLASS_AQUATIC] = presaleContract.currentPrices(CLASS_AQUATIC);
    currentPrice[CLASS_PLANT] = presaleContract.currentPrices(CLASS_PLANT);

    paused = false;
  }

  function setRedemptionAddress(address _redemptionAddress) external onlyOwner whenInitialized {
    redemptionAddress = _redemptionAddress;
  }

  function totalAdoptedAxies(
    uint8 _class,
    bool _deduction
  )
    external
    view
    whenInitialized
    returns (uint256 _number)
  {
    _number = _totalAdoptedAxies[_class]
      .add(presaleContract.totalAxiesAdopted(_class));

    if (_deduction) {
      _number = _number.sub(_totalDeductedAdoptedAxies[_class]);
    }
  }

  function numAdoptedAxies(
    address _owner,
    uint8 _class,
    bool _deduction
  )
    external
    view
    whenInitialized
    returns (uint256 _number)
  {
    _number = _numAdoptedAxies[_owner][_class]
      .add(presaleContract.axiesAdopted(_owner, _class));

    if (_deduction) {
      _number = _number.sub(_numDeductedAdoptedAxies[_owner][_class]);
    }
  }

  function numRefCredits(
    address _owner,
    bool _deduction
  )
    external
    view
    whenInitialized
    returns (uint256 _number)
  {
    _number = _numRefCredits[_owner]
      .add(presaleContract.referralCredits(_owner));

    if (_deduction) {
      _number = _number.sub(_numDeductedRefCredits[_owner]);
    }
  }

  function totalRewardedAxies(
    bool _deduction
  )
    external
    view
    whenInitialized
    returns (uint256 _number)
  {
    _number = _totalRewardedAxies
      .add(presaleContract.totalAxiesRewarded());

    if (_deduction) {
      _number = _number.sub(_totalDeductedRewardedAxies);
    }
  }

  function numRewardedAxies(
    address _owner,
    bool _deduction
  )
    external
    view
    whenInitialized
    returns (uint256 _number)
  {
    _number = _numRewardedAxies[_owner]
      .add(presaleContract.axiesRewarded(_owner));

    if (_deduction) {
      _number = _number.sub(_numDeductedRewardedAxies[_owner]);
    }
  }

  function axiesPrice(
    uint256 _beastQuantity,
    uint256 _aquaticQuantity,
    uint256 _plantQuantity
  )
    external
    view
    whenInitialized
    returns (uint256 _totalPrice)
  {
    uint256 price;

    (price,,) = _sameClassAxiesPrice(CLASS_BEAST, _beastQuantity);
    _totalPrice = _totalPrice.add(price);

    (price,,) = _sameClassAxiesPrice(CLASS_AQUATIC, _aquaticQuantity);
    _totalPrice = _totalPrice.add(price);

    (price,,) = _sameClassAxiesPrice(CLASS_PLANT, _plantQuantity);
    _totalPrice = _totalPrice.add(price);
  }

  function adoptAxies(
    uint256 _beastQuantity,
    uint256 _aquaticQuantity,
    uint256 _plantQuantity,
    address _referrer
  )
    external
    payable
    whenInitialized
    whenNotPaused
  {
    require(now <= PRESALE_END_TIMESTAMP);
    require(_beastQuantity <= 3 && _aquaticQuantity <= 3 && _plantQuantity <= 3);

    uint256 _totalAdopted = this.totalAdoptedAxies(CLASS_BEAST, false)
      .add(this.totalAdoptedAxies(CLASS_AQUATIC, false))
      .add(this.totalAdoptedAxies(CLASS_PLANT, false))
      .add(_beastQuantity)
      .add(_aquaticQuantity)
      .add(_plantQuantity);

    require(_totalAdopted <= MAX_TOTAL_ADOPTED_AXIES);

    address _adopter = msg.sender;
    address _actualReferrer = 0x0;

    // An adopter cannot be his/her own referrer.
    if (_referrer != _adopter) {
      _actualReferrer = _referrer;
    }

    uint256 _value = msg.value;
    uint256 _price;

    if (_beastQuantity > 0) {
      _price = _adoptSameClassAxies(
        _adopter,
        CLASS_BEAST,
        _beastQuantity,
        _actualReferrer
      );

      require(_value >= _price);
      _value -= _price;
    }

    if (_aquaticQuantity > 0) {
      _price = _adoptSameClassAxies(
        _adopter,
        CLASS_AQUATIC,
        _aquaticQuantity,
        _actualReferrer
      );

      require(_value >= _price);
      _value -= _price;
    }

    if (_plantQuantity > 0) {
      _price = _adoptSameClassAxies(
        _adopter,
        CLASS_PLANT,
        _plantQuantity,
        _actualReferrer
      );

      require(_value >= _price);
      _value -= _price;
    }

    msg.sender.transfer(_value);

    // The current referral is ignored if the referrer's address is 0x0.
    if (_actualReferrer != 0x0) {
      _applyRefCredits(
        _actualReferrer,
        _beastQuantity.add(_aquaticQuantity).add(_plantQuantity)
      );
    }
  }

  function mintRefCredits(
    address _receiver,
    uint256 _numMintedCredits
  )
    external
    onlyOwner
    whenInitialized
    returns (uint256)
  {
    require(_receiver != address(0));
    numBountyCredits = numBountyCredits.sub(_numMintedCredits);
    _applyRefCredits(_receiver, _numMintedCredits);
    emit RefCreditsMinted(_receiver, _numMintedCredits);
    return numBountyCredits;
  }

  function redeemAdoptedAxies(
    address _receiver,
    uint256 _beastQuantity,
    uint256 _aquaticQuantity,
    uint256 _plantQuantity
  )
    external
    onlyRedemptionAddress
    whenInitialized
    returns (
      uint256 /* remainingBeastQuantity */,
      uint256 /* remainingAquaticQuantity */,
      uint256 /* remainingPlantQuantity */
    )
  {
    return (
      _redeemSameClassAdoptedAxies(_receiver, CLASS_BEAST, _beastQuantity),
      _redeemSameClassAdoptedAxies(_receiver, CLASS_AQUATIC, _aquaticQuantity),
      _redeemSameClassAdoptedAxies(_receiver, CLASS_PLANT, _plantQuantity)
    );
  }

  function redeemRewardedAxies(
    address _receiver,
    uint256 _quantity
  )
    external
    onlyRedemptionAddress
    whenInitialized
    returns (uint256 _remainingQuantity)
  {
    _remainingQuantity = this.numRewardedAxies(_receiver, true).sub(_quantity);

    if (_quantity > 0) {
      _numDeductedRewardedAxies[_receiver] = _numDeductedRewardedAxies[_receiver].add(_quantity);
      _totalDeductedRewardedAxies = _totalDeductedRewardedAxies.add(_quantity);

      emit RewardedAxiesRedeemed(_receiver, _quantity);
    }
  }

  /**
   * @notice Calculate price of Axies from the same class.
   * @param _class The class of Axies.
   * @param _quantity Number of Axies to be calculated.
   */
  function _sameClassAxiesPrice(
    uint8 _class,
    uint256 _quantity
  )
    private
    view
    returns (
      uint256 _totalPrice,
      uint256 /* should be _subsequentIncrement */ _currentIncrement,
      uint256 /* should be _subsequentPrice */ _currentPrice
    )
  {
    _currentIncrement = priceIncrement[_class];
    _currentPrice = currentPrice[_class];

    uint256 _nextPrice;

    for (uint256 i = 0; i < _quantity; i++) {
      _totalPrice = _totalPrice.add(_currentPrice);
      _nextPrice = _currentPrice.add(_currentIncrement);

      if (_nextPrice / 100 finney != _currentPrice / 100 finney) {
        _currentIncrement >>= 1;
      }

      _currentPrice = _nextPrice;
    }
  }

  /**
   * @notice Adopt some Axies from the same class.
   * @dev The quantity MUST be positive.
   * @param _adopter Address of the adopter.
   * @param _class The class of adopted Axies.
   * @param _quantity Number of Axies to be adopted.
   * @param _referrer Address of the referrer.
   */
  function _adoptSameClassAxies(
    address _adopter,
    uint8 _class,
    uint256 _quantity,
    address _referrer
  )
    private
    returns (uint256 _totalPrice)
  {
    (_totalPrice, priceIncrement[_class], currentPrice[_class]) = _sameClassAxiesPrice(_class, _quantity);

    _numAdoptedAxies[_adopter][_class] = _numAdoptedAxies[_adopter][_class].add(_quantity);
    _totalAdoptedAxies[_class] = _totalAdoptedAxies[_class].add(_quantity);

    emit AxiesAdopted(
      _adopter,
      _class,
      _quantity,
      _referrer
    );
  }

  function _applyRefCredits(address _receiver, uint256 _numAppliedCredits) private {
    _numRefCredits[_receiver] = _numRefCredits[_receiver].add(_numAppliedCredits);

    uint256 _numCredits = this.numRefCredits(_receiver, true);
    uint256 _numRewards = _numCredits / REF_CREDITS_PER_AXIE;

    if (_numRewards > 0) {
      _numDeductedRefCredits[_receiver] = _numDeductedRefCredits[_receiver]
        .add(_numRewards.mul(REF_CREDITS_PER_AXIE));

      _numRewardedAxies[_receiver] = _numRewardedAxies[_receiver].add(_numRewards);
      _totalRewardedAxies = _totalRewardedAxies.add(_numRewards);

      emit AxiesRewarded(_receiver, _numRewards);
    }
  }

  /**
   * @notice Redeem adopted Axies from the same class.
   * @dev Emit the `AdoptedAxiesRedeemed` event if the quantity is positive.
   * @param _receiver The address of the receiver.
   * @param _class The class of adopted Axies.
   * @param _quantity The number of adopted Axies to be redeemed.
   */
  function _redeemSameClassAdoptedAxies(
    address _receiver,
    uint8 _class,
    uint256 _quantity
  )
    private
    returns (uint256 _remainingQuantity)
  {
    _remainingQuantity = this.numAdoptedAxies(_receiver, _class, true).sub(_quantity);

    if (_quantity > 0) {
      _numDeductedAdoptedAxies[_receiver][_class] = _numDeductedAdoptedAxies[_receiver][_class].add(_quantity);
      _totalDeductedAdoptedAxies[_class] = _totalDeductedAdoptedAxies[_class].add(_quantity);

      emit AdoptedAxiesRedeemed(_receiver, _class, _quantity);
    }
  }
}

contracts/presale/AxieRedemptionInternal.sol

pragma solidity ^0.4.19;


import "zeppelin/contracts/lifecycle/Pausable.sol";
import "zeppelin/contracts/math/SafeMath.sol";
import "zeppelin/contracts/ownership/HasNoContracts.sol";

import "../core/AxieCoreExtraInterface.sol";
import "../erc/erc20/ERC20RecipientInterface.sol";
import "../token/AxieOriginCoin.sol";
import "./AxiePresaleExtended.sol";


contract AxieRedemptionInternal is ERC20RecipientInterface, Pausable, HasNoContracts {
  using SafeMath for uint256;

  uint8 constant public CLASS_BEAST = 0;
  uint8 constant public CLASS_BUG = 1;
  uint8 constant public CLASS_BIRD = 2;
  uint8 constant public CLASS_PLANT = 3;
  uint8 constant public CLASS_AQUATIC = 4;
  uint8 constant public CLASS_REPTILE = 5;

  uint8 constant public NUM_ORIGIN_COINS_PER_AXIE = 5;

  struct Redemption {
    address receiver;
    uint256 clazz;
    uint256 redeemedAt;
  }

  uint8[15] private _twoBitNumbers;

  AxiePresaleExtended public presaleContract;
  AxieOriginCoin public originCoinContract;
  AxieCoreExtraInterface public coreExtraContract;

  uint256 public defaultGasLimit = 350000;

  mapping (uint256 => Redemption) public redemptionByQueryId;
  mapping (address => mapping (uint256 => uint256[])) public ownedRedemptions;
  mapping (uint256 => uint256) public ownedRedemptionIndex;

  event RedemptionStarted(uint256 indexed _queryId);
  event RedemptionRetried(uint256 indexed _queryId, uint256 indexed _oldQueryId);
  event RedemptionFinished(uint256 indexed _queryId);

  constructor() internal {
    _twoBitNumbers = [
      48, 40, 36, 34, 33,
      24, 20, 18, 17,
      12, 10, 9,
      6, 5,
      3
    ];
  }

  function () external payable {
    require(msg.sender == owner);
  }

  modifier requireDependencyContracts {
    require(
      // solium-disable operator-whitespace
      presaleContract != address(0) &&
        originCoinContract != address(0) &&
        coreExtraContract != address(0)
      // solium-enable operator-whitespace
    );
    _;
  }

  modifier onlyOriginCoinAddress {
    require(msg.sender == address(originCoinContract));
    _;
  }

  modifier whenStarted {
    require(now >= _startTimestamp());
    _;
  }

  function reclaimEther(uint256 remaining) external onlyOwner {
    if (address(this).balance > remaining) {
      owner.transfer(address(this).balance - remaining);
    }
  }

  function setPresaleContract(address _presaleAddress) external onlyOwner {
    presaleContract = AxiePresaleExtended(_presaleAddress);
  }

  function setOriginCoinContract(address _originCoinAddress) external onlyOwner {
    originCoinContract = AxieOriginCoin(_originCoinAddress);
  }

  function setCoreExtraContract(address _coreExtraAddress) external onlyOwner {
    coreExtraContract = AxieCoreExtraInterface(_coreExtraAddress);
  }

  function setDefaultGasLimit(uint256 _newGasLimit) onlyOwner {
    defaultGasLimit = _newGasLimit;
  }

  function numBeingRedeemedAxies(address _receiver, uint256 _class) external view returns (uint256) {
    return ownedRedemptions[_receiver][_class].length;
  }

  function redeemAdoptedAxies(
    uint256 _oldClass
  )
    external
    requireDependencyContracts
    whenStarted
    whenNotPaused
  {
    _redeemAdoptedAxies(msg.sender, _oldClass);
  }

  function redeemPlayersAdoptedAxies(
    address _receiver,
    uint256 _oldClass
  )
    external
    requireDependencyContracts
    onlyOwner
    whenStarted
  {
    _redeemAdoptedAxies(_receiver, _oldClass);
  }

  /**
   * @dev Redeems rewarded Axies.
   */
  function receiveApproval(
    address _from,
    uint256 /* _value */,
    address /* _erc20Address */,
    bytes /* _data */
  )
    external
    requireDependencyContracts
    onlyOriginCoinAddress
    whenStarted
    whenNotPaused
  {
    require(originCoinContract.burnFrom(_from, NUM_ORIGIN_COINS_PER_AXIE));
    _redeemAxies(_from, uint256(-1));
  }

  function retryRedemption(
    uint256 _oldQueryId,
    uint256 _gasLimit
  )
    external
    requireDependencyContracts
    onlyOwner
    whenStarted
  {
    Redemption memory _redemption = redemptionByQueryId[_oldQueryId];
    require(_redemption.receiver != address(0));

    uint256 _redemptionIndex = ownedRedemptionIndex[_oldQueryId];
    uint256 _queryId = _sendRandomQuery(_gasLimit);

    redemptionByQueryId[_queryId] = _redemption;
    delete redemptionByQueryId[_oldQueryId];

    ownedRedemptions[_redemption.receiver][_redemption.clazz][_redemptionIndex] = _queryId;
    ownedRedemptionIndex[_queryId] = _redemptionIndex;
    delete ownedRedemptionIndex[_oldQueryId];

    emit RedemptionRetried(_queryId, _oldQueryId);
  }

  function _startTimestamp() internal returns (uint256);

  function _sendRandomQuery(uint256 _gasLimit) internal returns (uint256);

  function _receiveRandomQuery(
    uint256 _queryId,
    string _result
  )
    internal
    whenStarted
    whenNotPaused
  {
    Redemption memory _redemption = redemptionByQueryId[_queryId];
    require(_redemption.receiver != address(0));

    uint256 _redemptionIndex = ownedRedemptionIndex[_queryId];
    uint256 _lastRedemptionIndex = ownedRedemptions[_redemption.receiver][_redemption.clazz].length.sub(1);
    uint256 _lastRedemptionQueryId = ownedRedemptions[_redemption.receiver][_redemption.clazz][_lastRedemptionIndex];

    uint256 _seed = uint256(keccak256(_result));
    uint256 _genes;

    if (_redemption.clazz != uint256(-1)) {
      _genes = _generateGenes(_redemption.clazz, _seed);
    } else {
      _genes = _generateGenes(_seed);
    }

    ownedRedemptions[_redemption.receiver][_redemption.clazz][_redemptionIndex] = _lastRedemptionQueryId;
    ownedRedemptionIndex[_lastRedemptionQueryId] = _redemptionIndex;

    delete ownedRedemptions[_redemption.receiver][_redemption.clazz][_lastRedemptionIndex];
    ownedRedemptions[_redemption.receiver][_redemption.clazz].length--;

    delete redemptionByQueryId[_queryId];
    delete ownedRedemptionIndex[_queryId];

    // Spawn an Axie with the generated `genes`.
    coreExtraContract.spawn(
      _genes,
      0, // Sire ID
      0, // Matron ID
      400, // Initial EXP
      _redemption.receiver
    );

    emit RedemptionFinished(_queryId);
  }

  function _currentPeriod() private view returns (uint256 _period) {
    _period = now / 12 hours & 1;
    require(_period == 0 || _period == 1);
  }

  function _currentWeather() private view returns (uint256 _weather) {
    _weather = uint256(keccak256(now / 8 hours)) & 7;
    require(_weather >= 0 && _weather <= 7);
  }

  function _randomNumber(
    uint256 _upper,
    uint256 _initialSeed
  )
    private
    view
    returns (uint256 _number, uint256 _seed)
  {
    _seed = uint256(
      keccak256(
        _initialSeed,
        blockhash(block.number - 1),
        block.coinbase,
        block.difficulty
      )
    );

    _number = _seed % _upper;
  }

  function _appendRandomBits(
    uint256 _genes,
    uint256 _upper,
    uint256 _addition,
    uint256 _numBits,
    uint256 _initialSeed
  )
    private
    view
    returns (uint256 _newGenes, uint256 _seed)
  {
    uint256 _number;
    (_number, _seed) = _randomNumber(_upper, _initialSeed);
    _newGenes = _genes << _numBits | ((_number + _addition) & ((uint256(1) << _numBits) - 1));
  }

  function _randomClass(uint256 _initialSeed) private view returns (uint256 _class, uint256 _seed) {
    // solium-disable-next-line comma-whitespace
    (_class, _seed) = _randomNumber(6 /* CLASS_REPTILE + 1 */, _initialSeed);
  }

  function _appendRandomColor(
    uint256 _genes,
    uint256 _initialSeed
  )
    private
    view
    returns (uint256 _newGenes, uint256 _seed)
  {
    uint256 _number;

    (_number, _seed) = _randomNumber(20, _initialSeed);

    if (_number < 2) {
      _newGenes = _genes << 4 | _number;
    } else {
      _newGenes = _genes << 4 | ((_number - 2) / 6 + 2);
    }
  }

  function _appendRandomPart(
    uint256 _genes,
    uint256 _upper,
    uint256 _forcedClass,
    uint256 _initialSeed
  )
    private
    view
    returns (uint256 _newGenes, uint256 _seed)
  {
    uint256 _number;
    bool _mystic;

    (_number, _seed) = _randomNumber(100, _initialSeed);
    _mystic = _number < 7;
    _newGenes = (_genes << 2 | (_mystic ? 3 : 0)) << 4;

    if (_forcedClass != uint256(-1)) {
      _newGenes = _newGenes | _forcedClass;
    } else {
      (_number, _seed) = _randomClass(_seed);
      _newGenes = _newGenes | _number;
    }

    _newGenes = _newGenes << 6;

    if (_mystic) {
      _newGenes = _newGenes | 2;
    } else {
      (_number, _seed) = _randomNumber(_upper, _seed);
      _newGenes = _newGenes | ((_number + 1) << 1 & 63);
    }

    // The first recessive gene

    (_number, _seed) = _randomClass(_seed);
    _newGenes = _newGenes << 4 | _number;

    (_number, _seed) = _randomNumber(_upper, _seed);
    _newGenes = _newGenes << 6 | ((_number + 1) << 1 & 63);

    // The second recessive gene

    (_number, _seed) = _randomClass(_seed);
    _newGenes = _newGenes << 4 | _number;

    (_number, _seed) = _randomNumber(_upper, _seed);
    _newGenes = _newGenes << 6 | ((_number + 1) << 1 & 63);
  }

  function _generateGenes(uint256 _class, uint256 _initialSeed) private view returns (uint256) {
    // solium-disable-next-line function-whitespace, operator-whitespace
    require(_class >= 0 /* CLASS_BEAST */ && _class <= 5 /* CLASS_REPTILE */);

    uint256 _seed = _initialSeed;
    uint256 _genes = _class;

    _genes = _genes << 1 | _currentPeriod();
    _genes = _genes << 3 | _currentWeather();
    _genes = _genes << 5; // Market - the default market is the global market.
    _genes = _genes << 5; // Contribution - special types for advisors, moderators, translators, etc.
    _genes = _genes | 1; // Origin indicator.
    _genes = _genes << 16; // More reservation.

    // solium-disable arg-overflow

    // Body
    (_genes, _seed) = _appendRandomBits(_genes, 13, 1, 6, _seed);
    (_genes, _seed) = _appendRandomBits(_genes, 13, 1, 6, _seed);
    (_genes, _seed) = _appendRandomBits(_genes, 13, 1, 6, _seed);

    // Color
    (_genes, _seed) = _appendRandomColor(_genes, _seed);
    (_genes, _seed) = _appendRandomColor(_genes, _seed);
    (_genes, _seed) = _appendRandomColor(_genes, _seed);

    uint256 _number;

    (_number, _seed) = _randomNumber(15, _seed);
    _number = _twoBitNumbers[_number];

    // Eyes
    (_genes, _seed) = _appendRandomPart(_genes, 2, _number >> 5 != 0 ? _class : uint256(-1), _seed);

    // Mouth
    (_genes, _seed) = _appendRandomPart(_genes, 2, _number >> 4 & 1 != 0 ? _class : uint256(-1), _seed);

    // Ears
    (_genes, _seed) = _appendRandomPart(_genes, 3, _number >> 3 & 1 != 0 ? _class : uint256(-1), _seed);

    // Horn
    (_genes, _seed) = _appendRandomPart(_genes, 3, _number >> 2 & 1 != 0 ? _class : uint256(-1), _seed);

    // Back
    (_genes, _seed) = _appendRandomPart(_genes, 3, _number >> 1 & 1 != 0 ? _class : uint256(-1), _seed);

    // Tail
    (_genes, _seed) = _appendRandomPart(_genes, 3, _number & 1 != 0 ? _class : uint256(-1), _seed);

    // solium-enable arg-overflow

    return _genes;
  }

  function _generateGenes(uint256 _initialSeed) private view returns (uint256) {
    uint256 _class;
    uint256 _seed;
    (_class, _seed) = _randomClass(_initialSeed);
    return _generateGenes(_class, _seed);
  }

  function _redeemAxies(address _receiver, uint256 _class) private {
    uint256 _queryId = _sendRandomQuery(defaultGasLimit);

    Redemption memory _redemption = Redemption(
      _receiver,
      _class,
      now
    );

    redemptionByQueryId[_queryId] = _redemption;

    uint256 _length = ownedRedemptions[_receiver][_class].length;
    ownedRedemptions[_receiver][_class].push(_queryId);
    ownedRedemptionIndex[_queryId] = _length;

    emit RedemptionStarted(_queryId);
  }

  function _redeemAdoptedAxies(address _receiver, uint256 _oldClass) private {
    uint256 _class;

    if (_oldClass == 0) { // Old Beast
      presaleContract.redeemAdoptedAxies(_receiver, 1, 0, 0);
      _class = CLASS_BEAST;
    } else if (_oldClass == 2) { // Old Aquatic
      presaleContract.redeemAdoptedAxies(_receiver, 0, 1, 0);
      _class = CLASS_AQUATIC;
    } else if (_oldClass == 4) { // Old Plant
      presaleContract.redeemAdoptedAxies(_receiver, 0, 0, 1);
      _class = CLASS_PLANT;
    } else {
      revert();
    }

    _redeemAxies(_receiver, _class);
  }
}

contracts/token/AxieOriginCoin.sol

pragma solidity ^0.4.23;


import "../erc/erc20/ERC20Burnable.sol";
import "../erc/erc20/ERC20DetailedInterface.sol";
import "../erc/erc20/ERC20Extended.sol";
import "../erc/erc20/ERC20Mintable.sol";


/**
 * @title The contract which holds Axie Origin Coins.
 * @dev Five Axie Origin Coins can be redeemed for one Origin Axie.
 */
contract AxieOriginCoin is
  ERC20Extended,
  ERC20DetailedInterface,
  ERC20Mintable,
  ERC20Burnable
{
  uint256 constant public NUM_COIN_PER_AXIE = 5;
  uint256 constant public NUM_RESERVED_AXIE = 427;
  uint256 constant public NUM_RESERVED_COIN = NUM_RESERVED_AXIE * NUM_COIN_PER_AXIE;

  constructor() public {
    _initialize();
  }

  /**
   * @notice Returns the name of the token.
   * @return The name.
   */
  function name() public view returns (string) {
    return "Axie Origin Coin";
  }

  /**
   * @notice Returns the name of the token.
   * @return The symbol.
   */
  function symbol() public view returns (string) {
    return "AOC";
  }

  /**
   * @notice Returns the number of decimals the token uses.
   * @return The number of decimals.
   */
  function decimals() public view returns (uint8) {
    return 0;
  }

  function _allocateUnspentRefTokens() internal {
    // 0
    mint(0x052731748979e182fdf9Bf849C6df54f9f196645, 3);
    mint(0x1878B18693fc273DE9FD833B83f9679785c01aB2, 1);
    mint(0x1E3934EA7E416F4E2BC5F7d55aE9783da0061475, 1);
    mint(0x32451d81EB31411B2CA4e70F3d87B3DEACCEA2d2, 3);
    mint(0x494952f01a30547d269aaF147e6226f940f5B041, 8);
    // 5
    mint(0x5BD73bB4e2A9f81922dbE7F4b321cfAE208BE2E6, 1);
    mint(0x6564A5639e17e186f749e493Af98a51fd3092048, 12);
    mint(0x696A567271BBDAC6f435CAb9D69e56cD115B76eB, 1);
    mint(0x70580eA14d98a53fd59376dC7e959F4a6129bB9b, 2);
    mint(0x75f732C1b1D0bBdA60f4B49EF0B36EB6e8AD6531, 1);
    // 10
    mint(0x84418eD93d141CFE7471dED46747D003117eCaD5, 2);
    mint(0x9455A90Cbf43D331Dd76a2d07192431370f64384, 2);
    mint(0x95fd3579c73Ea675C89415285355C4795118B345, 1);
    mint(0xa3346F3Af6A3AE749aCA18d7968A03811d15d733, 1);
    mint(0xA586A3B8939e9C0DC72D88166F6F6bb7558EeDCe, 1);
    // 15
    mint(0xAb01D4895b802c38Eee7553bb52A4160CFca2878, 1);
    mint(0xd6E8D52Be82550B230176b6E9bA49BC3fAF43E4a, 1);
    mint(0xEAB0c22D927d15391dd0CfbE89a3b59F6e814551, 3);
    mint(0x03300279d711b8dEb1353DD9719eFf81Ea1b6bEd, 3);
    mint(0x03b4A1fdeCeC66338071180a7F2f2D518CFf224A, 4);
    // 20
    mint(0x0537544De3935408246EE2Ad09949D046F92574D, 4);
    mint(0x0E26169270D92Ff3649461B55CA51C99703dE59e, 1);
    mint(0x16Ea1F673E01419BA9aF51365b88138Ac492489a, 1);
    mint(0x28d02f67316123Dc0293849a0D254AD86b379b34, 2);
    mint(0x38A6022FECb675a53F31CDaB3457456DD6e5911c, 2);
    // 25
    mint(0x4260E8206c58cD0530d9A5cff55B77D6165c7BCd, 1);
    mint(0x7E1DCf785f0353BF657c38Ab7865C1f184EFE208, 4);
    mint(0x7f328117b7de7579C6249258d084f75556E2699d, 1);
    mint(0x8a9d49a6e9D037843560091fC280B9Ff9819e462, 3);
    mint(0x8C5fC43ad00Cc53e11F61bEce329DDc5E3ea0929, 3);
    // 30
    mint(0x8FF9679fc77B077cB5f8818B7B63022582b5d538, 1);
    mint(0x97bfc7fc1Ee5b25CfAF6075bac5d7EcA037AD694, 1);
    mint(0x993a64DB27a51D1E6C1AFF56Fb61Ba0Dac253acb, 2);
    mint(0xa6bCEc585F12CeFBa9709A080cE2EFD38f871024, 1);
    mint(0xaF6488744207273c79B896922e65651C61033787, 5);
    // 35
    mint(0xB3C2a4ce7ce57A74371b7E3dAE8f3393229c2aaC, 3);
    mint(0xb4A90c06d5bC51D79D44e11336077b6F9ccD5683, 23);
    mint(0xB94c9e7D28e54cb37fA3B0D3FFeC24A8E4affA90, 3);
    mint(0xDe0D2e92e85B8B7828723Ee789ffA3Ba9FdCDb9c, 1);
    mint(0xe37Ba1117746473db68A807aE9E37a2088BDB20f, 1);
    // 40
    mint(0x5eA1D56D0ddE1cA5B50c277275855F69edEfA169, 1);
    mint(0x6692DE2d4b3102ab922cB21157EeBCD9BDDDBb15, 4);
    // 42
  }

  function _initialize() internal {
    // Reserve 20% of all remaining Axies from the Presale.
    mint(msg.sender, NUM_RESERVED_COIN);

    // As its name says.
    _allocateUnspentRefTokens();

    // Don't allow tokens to be minted anymore.
    finishMinting();
  }
}

oraclize-api/contracts/usingOraclize.sol

// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD



Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:



The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;

contract OraclizeI {
    address public cbAddress;
    function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
    function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
    function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
    function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
    function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
    function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
    function getPrice(string _datasource) public returns (uint _dsprice);
    function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
    function setProofType(byte _proofType) external;
    function setCustomGasPrice(uint _gasPrice) external;
    function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
    function getAddress() public returns (address _addr);
}
contract usingOraclize {
    uint constant day = 60*60*24;
    uint constant week = 60*60*24*7;
    uint constant month = 60*60*24*30;
    byte constant proofType_NONE = 0x00;
    byte constant proofType_TLSNotary = 0x10;
    byte constant proofType_Android = 0x20;
    byte constant proofType_Ledger = 0x30;
    byte constant proofType_Native = 0xF0;
    byte constant proofStorage_IPFS = 0x01;
    uint8 constant networkID_auto = 0;
    uint8 constant networkID_mainnet = 1;
    uint8 constant networkID_testnet = 2;
    uint8 constant networkID_morden = 2;
    uint8 constant networkID_consensys = 161;

    OraclizeAddrResolverI OAR;

    OraclizeI oraclize;
    modifier oraclizeAPI {
        if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
            oraclize_setNetwork(networkID_auto);

        if(address(oraclize) != OAR.getAddress())
            oraclize = OraclizeI(OAR.getAddress());

        _;
    }
    modifier coupon(string code){
        oraclize = OraclizeI(OAR.getAddress());
        _;
    }

    function oraclize_setNetwork(uint8 networkID) internal returns(bool){
      return oraclize_setNetwork();
      networkID; // silence the warning and remain backwards compatible
    }
    function oraclize_setNetwork() internal returns(bool){
        if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
            OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
            oraclize_setNetworkName("eth_mainnet");
            return true;
        }
        if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
            OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
            oraclize_setNetworkName("eth_ropsten3");
            return true;
        }
        if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
            OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
            oraclize_setNetworkName("eth_kovan");
            return true;
        }
        if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
            OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
            oraclize_setNetworkName("eth_rinkeby");
            return true;
        }
        if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
            OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
            return true;
        }
        if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
            OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
            return true;
        }
        if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
            OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
            return true;
        }
        return false;
    }

    function __callback(bytes32 myid, string result) public {
        __callback(myid, result, new bytes(0));
    }
    function __callback(bytes32 myid, string result, bytes proof) public {
      return;
      myid; result; proof; // Silence compiler warnings
    }

    function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
        return oraclize.getPrice(datasource);
    }

    function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
        return oraclize.getPrice(datasource, gaslimit);
    }

    function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query.value(price)(0, datasource, arg);
    }
    function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query.value(price)(timestamp, datasource, arg);
    }
    function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
    }
    function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
    }
    function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query2.value(price)(0, datasource, arg1, arg2);
    }
    function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
    }
    function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
    }
    function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
    }
    function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN.value(price)(0, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN.value(price)(timestamp, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN.value(price)(0, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN.value(price)(timestamp, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_cbAddress() oraclizeAPI internal returns (address){
        return oraclize.cbAddress();
    }
    function oraclize_setProof(byte proofP) oraclizeAPI internal {
        return oraclize.setProofType(proofP);
    }
    function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
        return oraclize.setCustomGasPrice(gasPrice);
    }

    function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
        return oraclize.randomDS_getSessionPubKeyHash();
    }

    function getCodeSize(address _addr) constant internal returns(uint _size) {
        assembly {
            _size := extcodesize(_addr)
        }
    }

    function parseAddr(string _a) internal pure returns (address){
        bytes memory tmp = bytes(_a);
        uint160 iaddr = 0;
        uint160 b1;
        uint160 b2;
        for (uint i=2; i<2+2*20; i+=2){
            iaddr *= 256;
            b1 = uint160(tmp[i]);
            b2 = uint160(tmp[i+1]);
            if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
            else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
            else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
            if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
            else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
            else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
            iaddr += (b1*16+b2);
        }
        return address(iaddr);
    }

    function strCompare(string _a, string _b) internal pure returns (int) {
        bytes memory a = bytes(_a);
        bytes memory b = bytes(_b);
        uint minLength = a.length;
        if (b.length < minLength) minLength = b.length;
        for (uint i = 0; i < minLength; i ++)
            if (a[i] < b[i])
                return -1;
            else if (a[i] > b[i])
                return 1;
        if (a.length < b.length)
            return -1;
        else if (a.length > b.length)
            return 1;
        else
            return 0;
    }

    function indexOf(string _haystack, string _needle) internal pure returns (int) {
        bytes memory h = bytes(_haystack);
        bytes memory n = bytes(_needle);
        if(h.length < 1 || n.length < 1 || (n.length > h.length))
            return -1;
        else if(h.length > (2**128 -1))
            return -1;
        else
        {
            uint subindex = 0;
            for (uint i = 0; i < h.length; i ++)
            {
                if (h[i] == n[0])
                {
                    subindex = 1;
                    while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
                    {
                        subindex++;
                    }
                    if(subindex == n.length)
                        return int(i);
                }
            }
            return -1;
        }
    }

    function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
        bytes memory _ba = bytes(_a);
        bytes memory _bb = bytes(_b);
        bytes memory _bc = bytes(_c);
        bytes memory _bd = bytes(_d);
        bytes memory _be = bytes(_e);
        string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
        bytes memory babcde = bytes(abcde);
        uint k = 0;
        for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
        for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
        for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
        for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
        for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
        return string(babcde);
    }

    function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
        return strConcat(_a, _b, _c, _d, "");
    }

    function strConcat(string _a, string _b, string _c) internal pure returns (string) {
        return strConcat(_a, _b, _c, "", "");
    }

    function strConcat(string _a, string _b) internal pure returns (string) {
        return strConcat(_a, _b, "", "", "");
    }

    // parseInt
    function parseInt(string _a) internal pure returns (uint) {
        return parseInt(_a, 0);
    }

    // parseInt(parseFloat*10^_b)
    function parseInt(string _a, uint _b) internal pure returns (uint) {
        bytes memory bresult = bytes(_a);
        uint mint = 0;
        bool decimals = false;
        for (uint i=0; i<bresult.length; i++){
            if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
                if (decimals){
                   if (_b == 0) break;
                    else _b--;
                }
                mint *= 10;
                mint += uint(bresult[i]) - 48;
            } else if (bresult[i] == 46) decimals = true;
        }
        if (_b > 0) mint *= 10**_b;
        return mint;
    }

    function uint2str(uint i) internal pure returns (string){
        if (i == 0) return "0";
        uint j = i;
        uint len;
        while (j != 0){
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len - 1;
        while (i != 0){
            bstr[k--] = byte(48 + i % 10);
            i /= 10;
        }
        return string(bstr);
    }

    function stra2cbor(string[] arr) internal pure returns (bytes) {
            uint arrlen = arr.length;

            // get correct cbor output length
            uint outputlen = 0;
            bytes[] memory elemArray = new bytes[](arrlen);
            for (uint i = 0; i < arrlen; i++) {
                elemArray[i] = (bytes(arr[i]));
                outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
            }
            uint ctr = 0;
            uint cborlen = arrlen + 0x80;
            outputlen += byte(cborlen).length;
            bytes memory res = new bytes(outputlen);

            while (byte(cborlen).length > ctr) {
                res[ctr] = byte(cborlen)[ctr];
                ctr++;
            }
            for (i = 0; i < arrlen; i++) {
                res[ctr] = 0x5F;
                ctr++;
                for (uint x = 0; x < elemArray[i].length; x++) {
                    // if there's a bug with larger strings, this may be the culprit
                    if (x % 23 == 0) {
                        uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
                        elemcborlen += 0x40;
                        uint lctr = ctr;
                        while (byte(elemcborlen).length > ctr - lctr) {
                            res[ctr] = byte(elemcborlen)[ctr - lctr];
                            ctr++;
                        }
                    }
                    res[ctr] = elemArray[i][x];
                    ctr++;
                }
                res[ctr] = 0xFF;
                ctr++;
            }
            return res;
        }

    function ba2cbor(bytes[] arr) internal pure returns (bytes) {
            uint arrlen = arr.length;

            // get correct cbor output length
            uint outputlen = 0;
            bytes[] memory elemArray = new bytes[](arrlen);
            for (uint i = 0; i < arrlen; i++) {
                elemArray[i] = (bytes(arr[i]));
                outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
            }
            uint ctr = 0;
            uint cborlen = arrlen + 0x80;
            outputlen += byte(cborlen).length;
            bytes memory res = new bytes(outputlen);

            while (byte(cborlen).length > ctr) {
                res[ctr] = byte(cborlen)[ctr];
                ctr++;
            }
            for (i = 0; i < arrlen; i++) {
                res[ctr] = 0x5F;
                ctr++;
                for (uint x = 0; x < elemArray[i].length; x++) {
                    // if there's a bug with larger strings, this may be the culprit
                    if (x % 23 == 0) {
                        uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
                        elemcborlen += 0x40;
                        uint lctr = ctr;
                        while (byte(elemcborlen).length > ctr - lctr) {
                            res[ctr] = byte(elemcborlen)[ctr - lctr];
                            ctr++;
                        }
                    }
                    res[ctr] = elemArray[i][x];
                    ctr++;
                }
                res[ctr] = 0xFF;
                ctr++;
            }
            return res;
        }


    string oraclize_network_name;
    function oraclize_setNetworkName(string _network_name) internal {
        oraclize_network_name = _network_name;
    }

    function oraclize_getNetworkName() internal view returns (string) {
        return oraclize_network_name;
    }

    function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
        require((_nbytes > 0) && (_nbytes <= 32));
        // Convert from seconds to ledger timer ticks
        _delay *= 10; 
        bytes memory nbytes = new bytes(1);
        nbytes[0] = byte(_nbytes);
        bytes memory unonce = new bytes(32);
        bytes memory sessionKeyHash = new bytes(32);
        bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
        assembly {
            mstore(unonce, 0x20)
            mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
            mstore(sessionKeyHash, 0x20)
            mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
        }
        bytes memory delay = new bytes(32);
        assembly { 
            mstore(add(delay, 0x20), _delay) 
        }
        
        bytes memory delay_bytes8 = new bytes(8);
        copyBytes(delay, 24, 8, delay_bytes8, 0);

        bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
        bytes32 queryId = oraclize_query("random", args, _customGasLimit);
        
        bytes memory delay_bytes8_left = new bytes(8);
        
        assembly {
            let x := mload(add(delay_bytes8, 0x20))
            mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))

        }
        
        oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
        return queryId;
    }
    
    function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
        oraclize_randomDS_args[queryId] = commitment;
    }

    mapping(bytes32=>bytes32) oraclize_randomDS_args;
    mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;

    function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
        bool sigok;
        address signer;

        bytes32 sigr;
        bytes32 sigs;

        bytes memory sigr_ = new bytes(32);
        uint offset = 4+(uint(dersig[3]) - 0x20);
        sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
        bytes memory sigs_ = new bytes(32);
        offset += 32 + 2;
        sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);

        assembly {
            sigr := mload(add(sigr_, 32))
            sigs := mload(add(sigs_, 32))
        }


        (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
        if (address(keccak256(pubkey)) == signer) return true;
        else {
            (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
            return (address(keccak256(pubkey)) == signer);
        }
    }

    function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
        bool sigok;

        // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
        bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
        copyBytes(proof, sig2offset, sig2.length, sig2, 0);

        bytes memory appkey1_pubkey = new bytes(64);
        copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);

        bytes memory tosign2 = new bytes(1+65+32);
        tosign2[0] = byte(1); //role
        copyBytes(proof, sig2offset-65, 65, tosign2, 1);
        bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
        copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
        sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);

        if (sigok == false) return false;


        // Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
        bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";

        bytes memory tosign3 = new bytes(1+65);
        tosign3[0] = 0xFE;
        copyBytes(proof, 3, 65, tosign3, 1);

        bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
        copyBytes(proof, 3+65, sig3.length, sig3, 0);

        sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);

        return sigok;
    }

    modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
        // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
        require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));

        bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
        require(proofVerified);

        _;
    }

    function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
        // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
        if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;

        bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
        if (proofVerified == false) return 2;

        return 0;
    }

    function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
        bool match_ = true;
        
        require(prefix.length == n_random_bytes);

        for (uint256 i=0; i< n_random_bytes; i++) {
            if (content[i] != prefix[i]) match_ = false;
        }

        return match_;
    }

    function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){

        // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
        uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
        bytes memory keyhash = new bytes(32);
        copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
        if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;

        bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
        copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);

        // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
        if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;

        // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
        // This is to verify that the computed args match with the ones specified in the query.
        bytes memory commitmentSlice1 = new bytes(8+1+32);
        copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);

        bytes memory sessionPubkey = new bytes(64);
        uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
        copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);

        bytes32 sessionPubkeyHash = sha256(sessionPubkey);
        if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
            delete oraclize_randomDS_args[queryId];
        } else return false;


        // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
        bytes memory tosign1 = new bytes(32+8+1+32);
        copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
        if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;

        // verify if sessionPubkeyHash was verified already, if not.. let's do it!
        if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
            oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
        }

        return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
    }

    // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
    function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
        uint minLength = length + toOffset;

        // Buffer too small
        require(to.length >= minLength); // Should be a better way?

        // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
        uint i = 32 + fromOffset;
        uint j = 32 + toOffset;

        while (i < (32 + fromOffset + length)) {
            assembly {
                let tmp := mload(add(from, i))
                mstore(add(to, j), tmp)
            }
            i += 32;
            j += 32;
        }

        return to;
    }

    // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
    // Duplicate Solidity's ecrecover, but catching the CALL return value
    function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
        // We do our own memory management here. Solidity uses memory offset
        // 0x40 to store the current end of memory. We write past it (as
        // writes are memory extensions), but don't update the offset so
        // Solidity will reuse it. The memory used here is only needed for
        // this context.

        // FIXME: inline assembly can't access return values
        bool ret;
        address addr;

        assembly {
            let size := mload(0x40)
            mstore(size, hash)
            mstore(add(size, 32), v)
            mstore(add(size, 64), r)
            mstore(add(size, 96), s)

            // NOTE: we can reuse the request memory because we deal with
            //       the return code
            ret := call(3000, 1, 0, size, 128, size, 32)
            addr := mload(size)
        }

        return (ret, addr);
    }

    // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
    function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
        bytes32 r;
        bytes32 s;
        uint8 v;

        if (sig.length != 65)
          return (false, 0);

        // The signature format is a compact form of:
        //   {bytes32 r}{bytes32 s}{uint8 v}
        // Compact means, uint8 is not padded to 32 bytes.
        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))

            // Here we are loading the last 32 bytes. We exploit the fact that
            // 'mload' will pad with zeroes if we overread.
            // There is no 'mload8' to do this, but that would be nicer.
            v := byte(0, mload(add(sig, 96)))

            // Alternative solution:
            // 'byte' is not working due to the Solidity parser, so lets
            // use the second best option, 'and'
            // v := and(mload(add(sig, 65)), 255)
        }

        // albeit non-transactional signatures are not specified by the YP, one would expect it
        // to match the YP range of [27, 28]
        //
        // geth uses [0, 1] and some clients have followed. This might change, see:
        //  https://github.com/ethereum/go-ethereum/issues/2053
        if (v < 27)
          v += 27;

        if (v != 27 && v != 28)
            return (false, 0);

        return safer_ecrecover(hash, v, r, s);
    }

}
// </ORACLIZE_API>

zeppelin/contracts/lifecycle/Pausable.sol

pragma solidity ^0.4.11;


import "../ownership/Ownable.sol";


/**
 * @title Pausable
 * @dev Base contract which allows children to implement an emergency stop mechanism.
 */
contract Pausable is Ownable {
  event Pause();
  event Unpause();

  bool public paused = false;


  /**
   * @dev Modifier to make a function callable only when the contract is not paused.
   */
  modifier whenNotPaused() {
    require(!paused);
    _;
  }

  /**
   * @dev Modifier to make a function callable only when the contract is paused.
   */
  modifier whenPaused() {
    require(paused);
    _;
  }

  /**
   * @dev called by the owner to pause, triggers stopped state
   */
  function pause() onlyOwner whenNotPaused public {
    paused = true;
    Pause();
  }

  /**
   * @dev called by the owner to unpause, returns to normal state
   */
  function unpause() onlyOwner whenPaused public {
    paused = false;
    Unpause();
  }
}

zeppelin/contracts/math/SafeMath.sol

pragma solidity ^0.4.11;


/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
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;
  }
}

zeppelin/contracts/ownership/HasNoContracts.sol

pragma solidity ^0.4.11;

import "./Ownable.sol";

/**
 * @title Contracts that should not own Contracts
 * @author Remco Bloemen <remco@2π.com>
 * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner
 * of this contract to reclaim ownership of the contracts.
 */
contract HasNoContracts is Ownable {

  /**
   * @dev Reclaim ownership of Ownable contracts
   * @param contractAddr The address of the Ownable to be reclaimed.
   */
  function reclaimContract(address contractAddr) external onlyOwner {
    Ownable contractInst = Ownable(contractAddr);
    contractInst.transferOwnership(owner);
  }
}

zeppelin/contracts/ownership/HasNoEther.sol

pragma solidity ^0.4.11;

import "./Ownable.sol";

/**
 * @title Contracts that should not own Ether
 * @author Remco Bloemen <remco@2π.com>
 * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
 * in the contract, it will allow the owner to reclaim this ether.
 * @notice Ether can still be send to this contract by:
 * calling functions labeled `payable`
 * `selfdestruct(contract_address)`
 * mining directly to the contract address
*/
contract HasNoEther is Ownable {

  /**
  * @dev Constructor that rejects incoming Ether
  * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
  * leave out payable, then Solidity will allow inheriting contracts to implement a payable
  * constructor. By doing it this way we prevent a payable constructor from working. Alternatively
  * we could use assembly to access msg.value.
  */
  function HasNoEther() payable {
    require(msg.value == 0);
  }

  /**
   * @dev Disallows direct send by settings a default function without the `payable` flag.
   */
  function() external {
  }

  /**
   * @dev Transfer all Ether held by the contract to the owner.
   */
  function reclaimEther() external onlyOwner {
    assert(owner.send(this.balance));
  }
}

zeppelin/contracts/ownership/Ownable.sol

pragma solidity ^0.4.11;


/**
 * @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() {
    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;
  }

}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "byzantium"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.