github.com/diadata-org/diadata@v1.4.593/config/nftContracts/cryptokitties/cryptokitties.sol (about)

     1  /**
     2   *Submitted for verification at Etherscan.io on 2017-11-28
     3  */
     4  
     5  pragma solidity ^0.4.11;
     6  
     7  
     8  /**
     9   * @title Ownable
    10   * @dev The Ownable contract has an owner address, and provides basic authorization control
    11   * functions, this simplifies the implementation of "user permissions".
    12   */
    13  contract Ownable {
    14    address public owner;
    15  
    16  
    17    /**
    18     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
    19     * account.
    20     */
    21    function Ownable() {
    22      owner = msg.sender;
    23    }
    24  
    25  
    26    /**
    27     * @dev Throws if called by any account other than the owner.
    28     */
    29    modifier onlyOwner() {
    30      require(msg.sender == owner);
    31      _;
    32    }
    33  
    34  
    35    /**
    36     * @dev Allows the current owner to transfer control of the contract to a newOwner.
    37     * @param newOwner The address to transfer ownership to.
    38     */
    39    function transferOwnership(address newOwner) onlyOwner {
    40      if (newOwner != address(0)) {
    41        owner = newOwner;
    42      }
    43    }
    44  
    45  }
    46  
    47  
    48  
    49  /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
    50  /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
    51  contract ERC721 {
    52      // Required methods
    53      function totalSupply() public view returns (uint256 total);
    54      function balanceOf(address _owner) public view returns (uint256 balance);
    55      function ownerOf(uint256 _tokenId) external view returns (address owner);
    56      function approve(address _to, uint256 _tokenId) external;
    57      function transfer(address _to, uint256 _tokenId) external;
    58      function transferFrom(address _from, address _to, uint256 _tokenId) external;
    59  
    60      // Events
    61      event Transfer(address from, address to, uint256 tokenId);
    62      event Approval(address owner, address approved, uint256 tokenId);
    63  
    64      // Optional
    65      // function name() public view returns (string name);
    66      // function symbol() public view returns (string symbol);
    67      // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
    68      // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
    69  
    70      // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
    71      function supportsInterface(bytes4 _interfaceID) external view returns (bool);
    72  }
    73  
    74  
    75  // // Auction wrapper functions
    76  
    77  
    78  // Auction wrapper functions
    79  
    80  
    81  
    82  
    83  
    84  
    85  
    86  /// @title SEKRETOOOO
    87  contract GeneScienceInterface {
    88      /// @dev simply a boolean to indicate this is the contract we expect to be
    89      function isGeneScience() public pure returns (bool);
    90  
    91      /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
    92      /// @param genes1 genes of mom
    93      /// @param genes2 genes of sire
    94      /// @return the genes that are supposed to be passed down the child
    95      function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
    96  }
    97  
    98  
    99  
   100  
   101  
   102  
   103  
   104  /// @title A facet of KittyCore that manages special access privileges.
   105  /// @author Axiom Zen (https://www.axiomzen.co)
   106  /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
   107  contract KittyAccessControl {
   108      // This facet controls access control for CryptoKitties. There are four roles managed here:
   109      //
   110      //     - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
   111      //         contracts. It is also the only role that can unpause the smart contract. It is initially
   112      //         set to the address that created the smart contract in the KittyCore constructor.
   113      //
   114      //     - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts.
   115      //
   116      //     - The COO: The COO can release gen0 kitties to auction, and mint promo cats.
   117      //
   118      // It should be noted that these roles are distinct without overlap in their access abilities, the
   119      // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
   120      // address to any role, the CEO address itself doesn't have the ability to act in those roles. This
   121      // restriction is intentional so that we aren't tempted to use the CEO address frequently out of
   122      // convenience. The less we use an address, the less likely it is that we somehow compromise the
   123      // account.
   124  
   125      /// @dev Emited when contract is upgraded - See README.md for updgrade plan
   126      event ContractUpgrade(address newContract);
   127  
   128      // The addresses of the accounts (or contracts) that can execute actions within each roles.
   129      address public ceoAddress;
   130      address public cfoAddress;
   131      address public cooAddress;
   132  
   133      // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
   134      bool public paused = false;
   135  
   136      /// @dev Access modifier for CEO-only functionality
   137      modifier onlyCEO() {
   138          require(msg.sender == ceoAddress);
   139          _;
   140      }
   141  
   142      /// @dev Access modifier for CFO-only functionality
   143      modifier onlyCFO() {
   144          require(msg.sender == cfoAddress);
   145          _;
   146      }
   147  
   148      /// @dev Access modifier for COO-only functionality
   149      modifier onlyCOO() {
   150          require(msg.sender == cooAddress);
   151          _;
   152      }
   153  
   154      modifier onlyCLevel() {
   155          require(
   156              msg.sender == cooAddress ||
   157              msg.sender == ceoAddress ||
   158              msg.sender == cfoAddress
   159          );
   160          _;
   161      }
   162  
   163      /// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
   164      /// @param _newCEO The address of the new CEO
   165      function setCEO(address _newCEO) external onlyCEO {
   166          require(_newCEO != address(0));
   167  
   168          ceoAddress = _newCEO;
   169      }
   170  
   171      /// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
   172      /// @param _newCFO The address of the new CFO
   173      function setCFO(address _newCFO) external onlyCEO {
   174          require(_newCFO != address(0));
   175  
   176          cfoAddress = _newCFO;
   177      }
   178  
   179      /// @dev Assigns a new address to act as the COO. Only available to the current CEO.
   180      /// @param _newCOO The address of the new COO
   181      function setCOO(address _newCOO) external onlyCEO {
   182          require(_newCOO != address(0));
   183  
   184          cooAddress = _newCOO;
   185      }
   186  
   187      /*** Pausable functionality adapted from OpenZeppelin ***/
   188  
   189      /// @dev Modifier to allow actions only when the contract IS NOT paused
   190      modifier whenNotPaused() {
   191          require(!paused);
   192          _;
   193      }
   194  
   195      /// @dev Modifier to allow actions only when the contract IS paused
   196      modifier whenPaused {
   197          require(paused);
   198          _;
   199      }
   200  
   201      /// @dev Called by any "C-level" role to pause the contract. Used only when
   202      ///  a bug or exploit is detected and we need to limit damage.
   203      function pause() external onlyCLevel whenNotPaused {
   204          paused = true;
   205      }
   206  
   207      /// @dev Unpauses the smart contract. Can only be called by the CEO, since
   208      ///  one reason we may pause the contract is when CFO or COO accounts are
   209      ///  compromised.
   210      /// @notice This is public rather than external so it can be called by
   211      ///  derived contracts.
   212      function unpause() public onlyCEO whenPaused {
   213          // can't unpause if contract was upgraded
   214          paused = false;
   215      }
   216  }
   217  
   218  
   219  
   220  
   221  /// @title Base contract for CryptoKitties. Holds all common structs, events and base variables.
   222  /// @author Axiom Zen (https://www.axiomzen.co)
   223  /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
   224  contract KittyBase is KittyAccessControl {
   225      /*** EVENTS ***/
   226  
   227      /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously
   228      ///  includes any time a cat is created through the giveBirth method, but it is also called
   229      ///  when a new gen0 cat is created.
   230      event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes);
   231  
   232      /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten
   233      ///  ownership is assigned, including births.
   234      event Transfer(address from, address to, uint256 tokenId);
   235  
   236      /*** DATA TYPES ***/
   237  
   238      /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy
   239      ///  of this structure, so great care was taken to ensure that it fits neatly into
   240      ///  exactly two 256-bit words. Note that the order of the members in this structure
   241      ///  is important because of the byte-packing rules used by Ethereum.
   242      ///  Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
   243      struct Kitty {
   244          // The Kitty's genetic code is packed into these 256-bits, the format is
   245          // sooper-sekret! A cat's genes never change.
   246          uint256 genes;
   247  
   248          // The timestamp from the block when this cat came into existence.
   249          uint64 birthTime;
   250  
   251          // The minimum timestamp after which this cat can engage in breeding
   252          // activities again. This same timestamp is used for the pregnancy
   253          // timer (for matrons) as well as the siring cooldown.
   254          uint64 cooldownEndBlock;
   255  
   256          // The ID of the parents of this kitty, set to 0 for gen0 cats.
   257          // Note that using 32-bit unsigned integers limits us to a "mere"
   258          // 4 billion cats. This number might seem small until you realize
   259          // that Ethereum currently has a limit of about 500 million
   260          // transactions per year! So, this definitely won't be a problem
   261          // for several years (even as Ethereum learns to scale).
   262          uint32 matronId;
   263          uint32 sireId;
   264  
   265          // Set to the ID of the sire cat for matrons that are pregnant,
   266          // zero otherwise. A non-zero value here is how we know a cat
   267          // is pregnant. Used to retrieve the genetic material for the new
   268          // kitten when the birth transpires.
   269          uint32 siringWithId;
   270  
   271          // Set to the index in the cooldown array (see below) that represents
   272          // the current cooldown duration for this Kitty. This starts at zero
   273          // for gen0 cats, and is initialized to floor(generation/2) for others.
   274          // Incremented by one for each successful breeding action, regardless
   275          // of whether this cat is acting as matron or sire.
   276          uint16 cooldownIndex;
   277  
   278          // The "generation number" of this cat. Cats minted by the CK contract
   279          // for sale are called "gen0" and have a generation number of 0. The
   280          // generation number of all other cats is the larger of the two generation
   281          // numbers of their parents, plus one.
   282          // (i.e. max(matron.generation, sire.generation) + 1)
   283          uint16 generation;
   284      }
   285  
   286      /*** CONSTANTS ***/
   287  
   288      /// @dev A lookup table indicating the cooldown duration after any successful
   289      ///  breeding action, called "pregnancy time" for matrons and "siring cooldown"
   290      ///  for sires. Designed such that the cooldown roughly doubles each time a cat
   291      ///  is bred, encouraging owners not to just keep breeding the same cat over
   292      ///  and over again. Caps out at one week (a cat can breed an unbounded number
   293      ///  of times, and the maximum cooldown is always seven days).
   294      uint32[14] public cooldowns = [
   295          uint32(1 minutes),
   296          uint32(2 minutes),
   297          uint32(5 minutes),
   298          uint32(10 minutes),
   299          uint32(30 minutes),
   300          uint32(1 hours),
   301          uint32(2 hours),
   302          uint32(4 hours),
   303          uint32(8 hours),
   304          uint32(16 hours),
   305          uint32(1 days),
   306          uint32(2 days),
   307          uint32(4 days),
   308          uint32(7 days)
   309      ];
   310  
   311      // An approximation of currently how many seconds are in between blocks.
   312      uint256 public secondsPerBlock = 15;
   313  
   314      /*** STORAGE ***/
   315  
   316      /// @dev An array containing the Kitty struct for all Kitties in existence. The ID
   317      ///  of each cat is actually an index into this array. Note that ID 0 is a negacat,
   318      ///  the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre
   319      ///  creature that is both matron and sire... to itself! Has an invalid genetic code.
   320      ///  In other words, cat ID 0 is invalid... ;-)
   321      Kitty[] kitties;
   322  
   323      /// @dev A mapping from cat IDs to the address that owns them. All cats have
   324      ///  some valid owner address, even gen0 cats are created with a non-zero owner.
   325      mapping (uint256 => address) public kittyIndexToOwner;
   326  
   327      // @dev A mapping from owner address to count of tokens that address owns.
   328      //  Used internally inside balanceOf() to resolve ownership count.
   329      mapping (address => uint256) ownershipTokenCount;
   330  
   331      /// @dev A mapping from KittyIDs to an address that has been approved to call
   332      ///  transferFrom(). Each Kitty can only have one approved address for transfer
   333      ///  at any time. A zero value means no approval is outstanding.
   334      mapping (uint256 => address) public kittyIndexToApproved;
   335  
   336      /// @dev A mapping from KittyIDs to an address that has been approved to use
   337      ///  this Kitty for siring via breedWith(). Each Kitty can only have one approved
   338      ///  address for siring at any time. A zero value means no approval is outstanding.
   339      mapping (uint256 => address) public sireAllowedToAddress;
   340  
   341      /// @dev The address of the ClockAuction contract that handles sales of Kitties. This
   342      ///  same contract handles both peer-to-peer sales as well as the gen0 sales which are
   343      ///  initiated every 15 minutes.
   344      SaleClockAuction public saleAuction;
   345  
   346      /// @dev The address of a custom ClockAuction subclassed contract that handles siring
   347      ///  auctions. Needs to be separate from saleAuction because the actions taken on success
   348      ///  after a sales and siring auction are quite different.
   349      SiringClockAuction public siringAuction;
   350  
   351      /// @dev Assigns ownership of a specific Kitty to an address.
   352      function _transfer(address _from, address _to, uint256 _tokenId) internal {
   353          // Since the number of kittens is capped to 2^32 we can't overflow this
   354          ownershipTokenCount[_to]++;
   355          // transfer ownership
   356          kittyIndexToOwner[_tokenId] = _to;
   357          // When creating new kittens _from is 0x0, but we can't account that address.
   358          if (_from != address(0)) {
   359              ownershipTokenCount[_from]--;
   360              // once the kitten is transferred also clear sire allowances
   361              delete sireAllowedToAddress[_tokenId];
   362              // clear any previously approved ownership exchange
   363              delete kittyIndexToApproved[_tokenId];
   364          }
   365          // Emit the transfer event.
   366          Transfer(_from, _to, _tokenId);
   367      }
   368  
   369      /// @dev An internal method that creates a new kitty and stores it. This
   370      ///  method doesn't do any checking and should only be called when the
   371      ///  input data is known to be valid. Will generate both a Birth event
   372      ///  and a Transfer event.
   373      /// @param _matronId The kitty ID of the matron of this cat (zero for gen0)
   374      /// @param _sireId The kitty ID of the sire of this cat (zero for gen0)
   375      /// @param _generation The generation number of this cat, must be computed by caller.
   376      /// @param _genes The kitty's genetic code.
   377      /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0)
   378      function _createKitty(
   379          uint256 _matronId,
   380          uint256 _sireId,
   381          uint256 _generation,
   382          uint256 _genes,
   383          address _owner
   384      )
   385          internal
   386          returns (uint)
   387      {
   388          // These requires are not strictly necessary, our calling code should make
   389          // sure that these conditions are never broken. However! _createKitty() is already
   390          // an expensive call (for storage), and it doesn't hurt to be especially careful
   391          // to ensure our data structures are always valid.
   392          require(_matronId == uint256(uint32(_matronId)));
   393          require(_sireId == uint256(uint32(_sireId)));
   394          require(_generation == uint256(uint16(_generation)));
   395  
   396          // New kitty starts with the same cooldown as parent gen/2
   397          uint16 cooldownIndex = uint16(_generation / 2);
   398          if (cooldownIndex > 13) {
   399              cooldownIndex = 13;
   400          }
   401  
   402          Kitty memory _kitty = Kitty({
   403              genes: _genes,
   404              birthTime: uint64(now),
   405              cooldownEndBlock: 0,
   406              matronId: uint32(_matronId),
   407              sireId: uint32(_sireId),
   408              siringWithId: 0,
   409              cooldownIndex: cooldownIndex,
   410              generation: uint16(_generation)
   411          });
   412          uint256 newKittenId = kitties.push(_kitty) - 1;
   413  
   414          // It's probably never going to happen, 4 billion cats is A LOT, but
   415          // let's just be 100% sure we never let this happen.
   416          require(newKittenId == uint256(uint32(newKittenId)));
   417  
   418          // emit the birth event
   419          Birth(
   420              _owner,
   421              newKittenId,
   422              uint256(_kitty.matronId),
   423              uint256(_kitty.sireId),
   424              _kitty.genes
   425          );
   426  
   427          // This will assign ownership, and also emit the Transfer event as
   428          // per ERC721 draft
   429          _transfer(0, _owner, newKittenId);
   430  
   431          return newKittenId;
   432      }
   433  
   434      // Any C-level can fix how many seconds per blocks are currently observed.
   435      function setSecondsPerBlock(uint256 secs) external onlyCLevel {
   436          require(secs < cooldowns[0]);
   437          secondsPerBlock = secs;
   438      }
   439  }
   440  
   441  
   442  
   443  
   444  
   445  /// @title The external contract that is responsible for generating metadata for the kitties,
   446  ///  it has one function that will return the data as bytes.
   447  contract ERC721Metadata {
   448      /// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
   449      function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
   450          if (_tokenId == 1) {
   451              buffer[0] = "Hello World! :D";
   452              count = 15;
   453          } else if (_tokenId == 2) {
   454              buffer[0] = "I would definitely choose a medi";
   455              buffer[1] = "um length string.";
   456              count = 49;
   457          } else if (_tokenId == 3) {
   458              buffer[0] = "Lorem ipsum dolor sit amet, mi e";
   459              buffer[1] = "st accumsan dapibus augue lorem,";
   460              buffer[2] = " tristique vestibulum id, libero";
   461              buffer[3] = " suscipit varius sapien aliquam.";
   462              count = 128;
   463          }
   464      }
   465  }
   466  
   467  
   468  /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant.
   469  /// @author Axiom Zen (https://www.axiomzen.co)
   470  /// @dev Ref: https://github.com/ethereum/EIPs/issues/721
   471  ///  See the KittyCore contract documentation to understand how the various contract facets are arranged.
   472  contract KittyOwnership is KittyBase, ERC721 {
   473  
   474      /// @notice Name and symbol of the non fungible token, as defined in ERC721.
   475      string public constant name = "CryptoKitties";
   476      string public constant symbol = "CK";
   477  
   478      // The contract that will return kitty metadata
   479      ERC721Metadata public erc721Metadata;
   480  
   481      bytes4 constant InterfaceSignature_ERC165 =
   482          bytes4(keccak256('supportsInterface(bytes4)'));
   483  
   484      bytes4 constant InterfaceSignature_ERC721 =
   485          bytes4(keccak256('name()')) ^
   486          bytes4(keccak256('symbol()')) ^
   487          bytes4(keccak256('totalSupply()')) ^
   488          bytes4(keccak256('balanceOf(address)')) ^
   489          bytes4(keccak256('ownerOf(uint256)')) ^
   490          bytes4(keccak256('approve(address,uint256)')) ^
   491          bytes4(keccak256('transfer(address,uint256)')) ^
   492          bytes4(keccak256('transferFrom(address,address,uint256)')) ^
   493          bytes4(keccak256('tokensOfOwner(address)')) ^
   494          bytes4(keccak256('tokenMetadata(uint256,string)'));
   495  
   496      /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
   497      ///  Returns true for any standardized interfaces implemented by this contract. We implement
   498      ///  ERC-165 (obviously!) and ERC-721.
   499      function supportsInterface(bytes4 _interfaceID) external view returns (bool)
   500      {
   501          // DEBUG ONLY
   502          //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
   503  
   504          return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
   505      }
   506  
   507      /// @dev Set the address of the sibling contract that tracks metadata.
   508      ///  CEO only.
   509      function setMetadataAddress(address _contractAddress) public onlyCEO {
   510          erc721Metadata = ERC721Metadata(_contractAddress);
   511      }
   512  
   513      // Internal utility functions: These functions all assume that their input arguments
   514      // are valid. We leave it to public methods to sanitize their inputs and follow
   515      // the required logic.
   516  
   517      /// @dev Checks if a given address is the current owner of a particular Kitty.
   518      /// @param _claimant the address we are validating against.
   519      /// @param _tokenId kitten id, only valid when > 0
   520      function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
   521          return kittyIndexToOwner[_tokenId] == _claimant;
   522      }
   523  
   524      /// @dev Checks if a given address currently has transferApproval for a particular Kitty.
   525      /// @param _claimant the address we are confirming kitten is approved for.
   526      /// @param _tokenId kitten id, only valid when > 0
   527      function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
   528          return kittyIndexToApproved[_tokenId] == _claimant;
   529      }
   530  
   531      /// @dev Marks an address as being approved for transferFrom(), overwriting any previous
   532      ///  approval. Setting _approved to address(0) clears all transfer approval.
   533      ///  NOTE: _approve() does NOT send the Approval event. This is intentional because
   534      ///  _approve() and transferFrom() are used together for putting Kitties on auction, and
   535      ///  there is no value in spamming the log with Approval events in that case.
   536      function _approve(uint256 _tokenId, address _approved) internal {
   537          kittyIndexToApproved[_tokenId] = _approved;
   538      }
   539  
   540      /// @notice Returns the number of Kitties owned by a specific address.
   541      /// @param _owner The owner address to check.
   542      /// @dev Required for ERC-721 compliance
   543      function balanceOf(address _owner) public view returns (uint256 count) {
   544          return ownershipTokenCount[_owner];
   545      }
   546  
   547      /// @notice Transfers a Kitty to another address. If transferring to a smart
   548      ///  contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
   549      ///  CryptoKitties specifically) or your Kitty may be lost forever. Seriously.
   550      /// @param _to The address of the recipient, can be a user or contract.
   551      /// @param _tokenId The ID of the Kitty to transfer.
   552      /// @dev Required for ERC-721 compliance.
   553      function transfer(
   554          address _to,
   555          uint256 _tokenId
   556      )
   557          external
   558          whenNotPaused
   559      {
   560          // Safety check to prevent against an unexpected 0x0 default.
   561          require(_to != address(0));
   562          // Disallow transfers to this contract to prevent accidental misuse.
   563          // The contract should never own any kitties (except very briefly
   564          // after a gen0 cat is created and before it goes on auction).
   565          require(_to != address(this));
   566          // Disallow transfers to the auction contracts to prevent accidental
   567          // misuse. Auction contracts should only take ownership of kitties
   568          // through the allow + transferFrom flow.
   569          require(_to != address(saleAuction));
   570          require(_to != address(siringAuction));
   571  
   572          // You can only send your own cat.
   573          require(_owns(msg.sender, _tokenId));
   574  
   575          // Reassign ownership, clear pending approvals, emit Transfer event.
   576          _transfer(msg.sender, _to, _tokenId);
   577      }
   578  
   579      /// @notice Grant another address the right to transfer a specific Kitty via
   580      ///  transferFrom(). This is the preferred flow for transfering NFTs to contracts.
   581      /// @param _to The address to be granted transfer approval. Pass address(0) to
   582      ///  clear all approvals.
   583      /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
   584      /// @dev Required for ERC-721 compliance.
   585      function approve(
   586          address _to,
   587          uint256 _tokenId
   588      )
   589          external
   590          whenNotPaused
   591      {
   592          // Only an owner can grant transfer approval.
   593          require(_owns(msg.sender, _tokenId));
   594  
   595          // Register the approval (replacing any previous approval).
   596          _approve(_tokenId, _to);
   597  
   598          // Emit approval event.
   599          Approval(msg.sender, _to, _tokenId);
   600      }
   601  
   602      /// @notice Transfer a Kitty owned by another address, for which the calling address
   603      ///  has previously been granted transfer approval by the owner.
   604      /// @param _from The address that owns the Kitty to be transfered.
   605      /// @param _to The address that should take ownership of the Kitty. Can be any address,
   606      ///  including the caller.
   607      /// @param _tokenId The ID of the Kitty to be transferred.
   608      /// @dev Required for ERC-721 compliance.
   609      function transferFrom(
   610          address _from,
   611          address _to,
   612          uint256 _tokenId
   613      )
   614          external
   615          whenNotPaused
   616      {
   617          // Safety check to prevent against an unexpected 0x0 default.
   618          require(_to != address(0));
   619          // Disallow transfers to this contract to prevent accidental misuse.
   620          // The contract should never own any kitties (except very briefly
   621          // after a gen0 cat is created and before it goes on auction).
   622          require(_to != address(this));
   623          // Check for approval and valid ownership
   624          require(_approvedFor(msg.sender, _tokenId));
   625          require(_owns(_from, _tokenId));
   626  
   627          // Reassign ownership (also clears pending approvals and emits Transfer event).
   628          _transfer(_from, _to, _tokenId);
   629      }
   630  
   631      /// @notice Returns the total number of Kitties currently in existence.
   632      /// @dev Required for ERC-721 compliance.
   633      function totalSupply() public view returns (uint) {
   634          return kitties.length - 1;
   635      }
   636  
   637      /// @notice Returns the address currently assigned ownership of a given Kitty.
   638      /// @dev Required for ERC-721 compliance.
   639      function ownerOf(uint256 _tokenId)
   640          external
   641          view
   642          returns (address owner)
   643      {
   644          owner = kittyIndexToOwner[_tokenId];
   645  
   646          require(owner != address(0));
   647      }
   648  
   649      /// @notice Returns a list of all Kitty IDs assigned to an address.
   650      /// @param _owner The owner whose Kitties we are interested in.
   651      /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
   652      ///  expensive (it walks the entire Kitty array looking for cats belonging to owner),
   653      ///  but it also returns a dynamic array, which is only supported for web3 calls, and
   654      ///  not contract-to-contract calls.
   655      function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
   656          uint256 tokenCount = balanceOf(_owner);
   657  
   658          if (tokenCount == 0) {
   659              // Return an empty array
   660              return new uint256[](0);
   661          } else {
   662              uint256[] memory result = new uint256[](tokenCount);
   663              uint256 totalCats = totalSupply();
   664              uint256 resultIndex = 0;
   665  
   666              // We count on the fact that all cats have IDs starting at 1 and increasing
   667              // sequentially up to the totalCat count.
   668              uint256 catId;
   669  
   670              for (catId = 1; catId <= totalCats; catId++) {
   671                  if (kittyIndexToOwner[catId] == _owner) {
   672                      result[resultIndex] = catId;
   673                      resultIndex++;
   674                  }
   675              }
   676  
   677              return result;
   678          }
   679      }
   680  
   681      /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
   682      ///  This method is licenced under the Apache License.
   683      ///  Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
   684      function _memcpy(uint _dest, uint _src, uint _len) private view {
   685          // Copy word-length chunks while possible
   686          for(; _len >= 32; _len -= 32) {
   687              assembly {
   688                  mstore(_dest, mload(_src))
   689              }
   690              _dest += 32;
   691              _src += 32;
   692          }
   693  
   694          // Copy remaining bytes
   695          uint256 mask = 256 ** (32 - _len) - 1;
   696          assembly {
   697              let srcpart := and(mload(_src), not(mask))
   698              let destpart := and(mload(_dest), mask)
   699              mstore(_dest, or(destpart, srcpart))
   700          }
   701      }
   702  
   703      /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
   704      ///  This method is licenced under the Apache License.
   705      ///  Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
   706      function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
   707          var outputString = new string(_stringLength);
   708          uint256 outputPtr;
   709          uint256 bytesPtr;
   710  
   711          assembly {
   712              outputPtr := add(outputString, 32)
   713              bytesPtr := _rawBytes
   714          }
   715  
   716          _memcpy(outputPtr, bytesPtr, _stringLength);
   717  
   718          return outputString;
   719      }
   720  
   721      /// @notice Returns a URI pointing to a metadata package for this token conforming to
   722      ///  ERC-721 (https://github.com/ethereum/EIPs/issues/721)
   723      /// @param _tokenId The ID number of the Kitty whose metadata should be returned.
   724      function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
   725          require(erc721Metadata != address(0));
   726          bytes32[4] memory buffer;
   727          uint256 count;
   728          (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
   729  
   730          return _toString(buffer, count);
   731      }
   732  }
   733  
   734  
   735  
   736  /// @title A facet of KittyCore that manages Kitty siring, gestation, and birth.
   737  /// @author Axiom Zen (https://www.axiomzen.co)
   738  /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
   739  contract KittyBreeding is KittyOwnership {
   740  
   741      /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy
   742      ///  timer begins for the matron.
   743      event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
   744  
   745      /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
   746      ///  the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
   747      ///  the COO role as the gas price changes.
   748      uint256 public autoBirthFee = 2 finney;
   749  
   750      // Keeps track of number of pregnant kitties.
   751      uint256 public pregnantKitties;
   752  
   753      /// @dev The address of the sibling contract that is used to implement the sooper-sekret
   754      ///  genetic combination algorithm.
   755      GeneScienceInterface public geneScience;
   756  
   757      /// @dev Update the address of the genetic contract, can only be called by the CEO.
   758      /// @param _address An address of a GeneScience contract instance to be used from this point forward.
   759      function setGeneScienceAddress(address _address) external onlyCEO {
   760          GeneScienceInterface candidateContract = GeneScienceInterface(_address);
   761  
   762          // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
   763          require(candidateContract.isGeneScience());
   764  
   765          // Set the new contract address
   766          geneScience = candidateContract;
   767      }
   768  
   769      /// @dev Checks that a given kitten is able to breed. Requires that the
   770      ///  current cooldown is finished (for sires) and also checks that there is
   771      ///  no pending pregnancy.
   772      function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
   773          // In addition to checking the cooldownEndBlock, we also need to check to see if
   774          // the cat has a pending birth; there can be some period of time between the end
   775          // of the pregnacy timer and the birth event.
   776          return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number));
   777      }
   778  
   779      /// @dev Check if a sire has authorized breeding with this matron. True if both sire
   780      ///  and matron have the same owner, or if the sire has given siring permission to
   781      ///  the matron's owner (via approveSiring()).
   782      function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
   783          address matronOwner = kittyIndexToOwner[_matronId];
   784          address sireOwner = kittyIndexToOwner[_sireId];
   785  
   786          // Siring is okay if they have same owner, or if the matron's owner was given
   787          // permission to breed with this sire.
   788          return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
   789      }
   790  
   791      /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex.
   792      ///  Also increments the cooldownIndex (unless it has hit the cap).
   793      /// @param _kitten A reference to the Kitty in storage which needs its timer started.
   794      function _triggerCooldown(Kitty storage _kitten) internal {
   795          // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
   796          _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number);
   797  
   798          // Increment the breeding count, clamping it at 13, which is the length of the
   799          // cooldowns array. We could check the array size dynamically, but hard-coding
   800          // this as a constant saves gas. Yay, Solidity!
   801          if (_kitten.cooldownIndex < 13) {
   802              _kitten.cooldownIndex += 1;
   803          }
   804      }
   805  
   806      /// @notice Grants approval to another user to sire with one of your Kitties.
   807      /// @param _addr The address that will be able to sire with your Kitty. Set to
   808      ///  address(0) to clear all siring approvals for this Kitty.
   809      /// @param _sireId A Kitty that you own that _addr will now be able to sire with.
   810      function approveSiring(address _addr, uint256 _sireId)
   811          external
   812          whenNotPaused
   813      {
   814          require(_owns(msg.sender, _sireId));
   815          sireAllowedToAddress[_sireId] = _addr;
   816      }
   817  
   818      /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
   819      ///  be called by the COO address. (This fee is used to offset the gas cost incurred
   820      ///  by the autobirth daemon).
   821      function setAutoBirthFee(uint256 val) external onlyCOO {
   822          autoBirthFee = val;
   823      }
   824  
   825      /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation
   826      ///  period has passed.
   827      function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) {
   828          return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
   829      }
   830  
   831      /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or
   832      ///  in the middle of a siring cooldown).
   833      /// @param _kittyId reference the id of the kitten, any user can inquire about it
   834      function isReadyToBreed(uint256 _kittyId)
   835          public
   836          view
   837          returns (bool)
   838      {
   839          require(_kittyId > 0);
   840          Kitty storage kit = kitties[_kittyId];
   841          return _isReadyToBreed(kit);
   842      }
   843  
   844      /// @dev Checks whether a kitty is currently pregnant.
   845      /// @param _kittyId reference the id of the kitten, any user can inquire about it
   846      function isPregnant(uint256 _kittyId)
   847          public
   848          view
   849          returns (bool)
   850      {
   851          require(_kittyId > 0);
   852          // A kitty is pregnant if and only if this field is set
   853          return kitties[_kittyId].siringWithId != 0;
   854      }
   855  
   856      /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
   857      ///  check ownership permissions (that is up to the caller).
   858      /// @param _matron A reference to the Kitty struct of the potential matron.
   859      /// @param _matronId The matron's ID.
   860      /// @param _sire A reference to the Kitty struct of the potential sire.
   861      /// @param _sireId The sire's ID
   862      function _isValidMatingPair(
   863          Kitty storage _matron,
   864          uint256 _matronId,
   865          Kitty storage _sire,
   866          uint256 _sireId
   867      )
   868          private
   869          view
   870          returns(bool)
   871      {
   872          // A Kitty can't breed with itself!
   873          if (_matronId == _sireId) {
   874              return false;
   875          }
   876  
   877          // Kitties can't breed with their parents.
   878          if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
   879              return false;
   880          }
   881          if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
   882              return false;
   883          }
   884  
   885          // We can short circuit the sibling check (below) if either cat is
   886          // gen zero (has a matron ID of zero).
   887          if (_sire.matronId == 0 || _matron.matronId == 0) {
   888              return true;
   889          }
   890  
   891          // Kitties can't breed with full or half siblings.
   892          if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
   893              return false;
   894          }
   895          if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
   896              return false;
   897          }
   898  
   899          // Everything seems cool! Let's get DTF.
   900          return true;
   901      }
   902  
   903      /// @dev Internal check to see if a given sire and matron are a valid mating pair for
   904      ///  breeding via auction (i.e. skips ownership and siring approval checks).
   905      function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
   906          internal
   907          view
   908          returns (bool)
   909      {
   910          Kitty storage matron = kitties[_matronId];
   911          Kitty storage sire = kitties[_sireId];
   912          return _isValidMatingPair(matron, _matronId, sire, _sireId);
   913      }
   914  
   915      /// @notice Checks to see if two cats can breed together, including checks for
   916      ///  ownership and siring approvals. Does NOT check that both cats are ready for
   917      ///  breeding (i.e. breedWith could still fail until the cooldowns are finished).
   918      ///  TODO: Shouldn't this check pregnancy and cooldowns?!?
   919      /// @param _matronId The ID of the proposed matron.
   920      /// @param _sireId The ID of the proposed sire.
   921      function canBreedWith(uint256 _matronId, uint256 _sireId)
   922          external
   923          view
   924          returns(bool)
   925      {
   926          require(_matronId > 0);
   927          require(_sireId > 0);
   928          Kitty storage matron = kitties[_matronId];
   929          Kitty storage sire = kitties[_sireId];
   930          return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
   931              _isSiringPermitted(_sireId, _matronId);
   932      }
   933  
   934      /// @dev Internal utility function to initiate breeding, assumes that all breeding
   935      ///  requirements have been checked.
   936      function _breedWith(uint256 _matronId, uint256 _sireId) internal {
   937          // Grab a reference to the Kitties from storage.
   938          Kitty storage sire = kitties[_sireId];
   939          Kitty storage matron = kitties[_matronId];
   940  
   941          // Mark the matron as pregnant, keeping track of who the sire is.
   942          matron.siringWithId = uint32(_sireId);
   943  
   944          // Trigger the cooldown for both parents.
   945          _triggerCooldown(sire);
   946          _triggerCooldown(matron);
   947  
   948          // Clear siring permission for both parents. This may not be strictly necessary
   949          // but it's likely to avoid confusion!
   950          delete sireAllowedToAddress[_matronId];
   951          delete sireAllowedToAddress[_sireId];
   952  
   953          // Every time a kitty gets pregnant, counter is incremented.
   954          pregnantKitties++;
   955  
   956          // Emit the pregnancy event.
   957          Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
   958      }
   959  
   960      /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you
   961      ///  have previously been given Siring approval. Will either make your cat pregnant, or will
   962      ///  fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
   963      /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful)
   964      /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful)
   965      function breedWithAuto(uint256 _matronId, uint256 _sireId)
   966          external
   967          payable
   968          whenNotPaused
   969      {
   970          // Checks for payment.
   971          require(msg.value >= autoBirthFee);
   972  
   973          // Caller must own the matron.
   974          require(_owns(msg.sender, _matronId));
   975  
   976          // Neither sire nor matron are allowed to be on auction during a normal
   977          // breeding operation, but we don't need to check that explicitly.
   978          // For matron: The caller of this function can't be the owner of the matron
   979          //   because the owner of a Kitty on auction is the auction house, and the
   980          //   auction house will never call breedWith().
   981          // For sire: Similarly, a sire on auction will be owned by the auction house
   982          //   and the act of transferring ownership will have cleared any oustanding
   983          //   siring approval.
   984          // Thus we don't need to spend gas explicitly checking to see if either cat
   985          // is on auction.
   986  
   987          // Check that matron and sire are both owned by caller, or that the sire
   988          // has given siring permission to caller (i.e. matron's owner).
   989          // Will fail for _sireId = 0
   990          require(_isSiringPermitted(_sireId, _matronId));
   991  
   992          // Grab a reference to the potential matron
   993          Kitty storage matron = kitties[_matronId];
   994  
   995          // Make sure matron isn't pregnant, or in the middle of a siring cooldown
   996          require(_isReadyToBreed(matron));
   997  
   998          // Grab a reference to the potential sire
   999          Kitty storage sire = kitties[_sireId];
  1000  
  1001          // Make sure sire isn't pregnant, or in the middle of a siring cooldown
  1002          require(_isReadyToBreed(sire));
  1003  
  1004          // Test that these cats are a valid mating pair.
  1005          require(_isValidMatingPair(
  1006              matron,
  1007              _matronId,
  1008              sire,
  1009              _sireId
  1010          ));
  1011  
  1012          // All checks passed, kitty gets pregnant!
  1013          _breedWith(_matronId, _sireId);
  1014      }
  1015  
  1016      /// @notice Have a pregnant Kitty give birth!
  1017      /// @param _matronId A Kitty ready to give birth.
  1018      /// @return The Kitty ID of the new kitten.
  1019      /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed,
  1020      ///  combines the genes of the two parents to create a new kitten. The new Kitty is assigned
  1021      ///  to the current owner of the matron. Upon successful completion, both the matron and the
  1022      ///  new kitten will be ready to breed again. Note that anyone can call this function (if they
  1023      ///  are willing to pay the gas!), but the new kitten always goes to the mother's owner.
  1024      function giveBirth(uint256 _matronId)
  1025          external
  1026          whenNotPaused
  1027          returns(uint256)
  1028      {
  1029          // Grab a reference to the matron in storage.
  1030          Kitty storage matron = kitties[_matronId];
  1031  
  1032          // Check that the matron is a valid cat.
  1033          require(matron.birthTime != 0);
  1034  
  1035          // Check that the matron is pregnant, and that its time has come!
  1036          require(_isReadyToGiveBirth(matron));
  1037  
  1038          // Grab a reference to the sire in storage.
  1039          uint256 sireId = matron.siringWithId;
  1040          Kitty storage sire = kitties[sireId];
  1041  
  1042          // Determine the higher generation number of the two parents
  1043          uint16 parentGen = matron.generation;
  1044          if (sire.generation > matron.generation) {
  1045              parentGen = sire.generation;
  1046          }
  1047  
  1048          // Call the sooper-sekret gene mixing operation.
  1049          uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
  1050  
  1051          // Make the new kitten!
  1052          address owner = kittyIndexToOwner[_matronId];
  1053          uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner);
  1054  
  1055          // Clear the reference to sire from the matron (REQUIRED! Having siringWithId
  1056          // set is what marks a matron as being pregnant.)
  1057          delete matron.siringWithId;
  1058  
  1059          // Every time a kitty gives birth counter is decremented.
  1060          pregnantKitties--;
  1061  
  1062          // Send the balance fee to the person who made birth happen.
  1063          msg.sender.send(autoBirthFee);
  1064  
  1065          // return the new kitten's ID
  1066          return kittenId;
  1067      }
  1068  }
  1069  
  1070  
  1071  
  1072  
  1073  
  1074  
  1075  
  1076  
  1077  
  1078  
  1079  /// @title Auction Core
  1080  /// @dev Contains models, variables, and internal methods for the auction.
  1081  /// @notice We omit a fallback function to prevent accidental sends to this contract.
  1082  contract ClockAuctionBase {
  1083  
  1084      // Represents an auction on an NFT
  1085      struct Auction {
  1086          // Current owner of NFT
  1087          address seller;
  1088          // Price (in wei) at beginning of auction
  1089          uint128 startingPrice;
  1090          // Price (in wei) at end of auction
  1091          uint128 endingPrice;
  1092          // Duration (in seconds) of auction
  1093          uint64 duration;
  1094          // Time when auction started
  1095          // NOTE: 0 if this auction has been concluded
  1096          uint64 startedAt;
  1097      }
  1098  
  1099      // Reference to contract tracking NFT ownership
  1100      ERC721 public nonFungibleContract;
  1101  
  1102      // Cut owner takes on each auction, measured in basis points (1/100 of a percent).
  1103      // Values 0-10,000 map to 0%-100%
  1104      uint256 public ownerCut;
  1105  
  1106      // Map from token ID to their corresponding auction.
  1107      mapping (uint256 => Auction) tokenIdToAuction;
  1108  
  1109      event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
  1110      event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
  1111      event AuctionCancelled(uint256 tokenId);
  1112  
  1113      /// @dev Returns true if the claimant owns the token.
  1114      /// @param _claimant - Address claiming to own the token.
  1115      /// @param _tokenId - ID of token whose ownership to verify.
  1116      function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
  1117          return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
  1118      }
  1119  
  1120      /// @dev Escrows the NFT, assigning ownership to this contract.
  1121      /// Throws if the escrow fails.
  1122      /// @param _owner - Current owner address of token to escrow.
  1123      /// @param _tokenId - ID of token whose approval to verify.
  1124      function _escrow(address _owner, uint256 _tokenId) internal {
  1125          // it will throw if transfer fails
  1126          nonFungibleContract.transferFrom(_owner, this, _tokenId);
  1127      }
  1128  
  1129      /// @dev Transfers an NFT owned by this contract to another address.
  1130      /// Returns true if the transfer succeeds.
  1131      /// @param _receiver - Address to transfer NFT to.
  1132      /// @param _tokenId - ID of token to transfer.
  1133      function _transfer(address _receiver, uint256 _tokenId) internal {
  1134          // it will throw if transfer fails
  1135          nonFungibleContract.transfer(_receiver, _tokenId);
  1136      }
  1137  
  1138      /// @dev Adds an auction to the list of open auctions. Also fires the
  1139      ///  AuctionCreated event.
  1140      /// @param _tokenId The ID of the token to be put on auction.
  1141      /// @param _auction Auction to add.
  1142      function _addAuction(uint256 _tokenId, Auction _auction) internal {
  1143          // Require that all auctions have a duration of
  1144          // at least one minute. (Keeps our math from getting hairy!)
  1145          require(_auction.duration >= 1 minutes);
  1146  
  1147          tokenIdToAuction[_tokenId] = _auction;
  1148  
  1149          AuctionCreated(
  1150              uint256(_tokenId),
  1151              uint256(_auction.startingPrice),
  1152              uint256(_auction.endingPrice),
  1153              uint256(_auction.duration)
  1154          );
  1155      }
  1156  
  1157      /// @dev Cancels an auction unconditionally.
  1158      function _cancelAuction(uint256 _tokenId, address _seller) internal {
  1159          _removeAuction(_tokenId);
  1160          _transfer(_seller, _tokenId);
  1161          AuctionCancelled(_tokenId);
  1162      }
  1163  
  1164      /// @dev Computes the price and transfers winnings.
  1165      /// Does NOT transfer ownership of token.
  1166      function _bid(uint256 _tokenId, uint256 _bidAmount)
  1167          internal
  1168          returns (uint256)
  1169      {
  1170          // Get a reference to the auction struct
  1171          Auction storage auction = tokenIdToAuction[_tokenId];
  1172  
  1173          // Explicitly check that this auction is currently live.
  1174          // (Because of how Ethereum mappings work, we can't just count
  1175          // on the lookup above failing. An invalid _tokenId will just
  1176          // return an auction object that is all zeros.)
  1177          require(_isOnAuction(auction));
  1178  
  1179          // Check that the bid is greater than or equal to the current price
  1180          uint256 price = _currentPrice(auction);
  1181          require(_bidAmount >= price);
  1182  
  1183          // Grab a reference to the seller before the auction struct
  1184          // gets deleted.
  1185          address seller = auction.seller;
  1186  
  1187          // The bid is good! Remove the auction before sending the fees
  1188          // to the sender so we can't have a reentrancy attack.
  1189          _removeAuction(_tokenId);
  1190  
  1191          // Transfer proceeds to seller (if there are any!)
  1192          if (price > 0) {
  1193              // Calculate the auctioneer's cut.
  1194              // (NOTE: _computeCut() is guaranteed to return a
  1195              // value <= price, so this subtraction can't go negative.)
  1196              uint256 auctioneerCut = _computeCut(price);
  1197              uint256 sellerProceeds = price - auctioneerCut;
  1198  
  1199              // NOTE: Doing a transfer() in the middle of a complex
  1200              // method like this is generally discouraged because of
  1201              // reentrancy attacks and DoS attacks if the seller is
  1202              // a contract with an invalid fallback function. We explicitly
  1203              // guard against reentrancy attacks by removing the auction
  1204              // before calling transfer(), and the only thing the seller
  1205              // can DoS is the sale of their own asset! (And if it's an
  1206              // accident, they can call cancelAuction(). )
  1207              seller.transfer(sellerProceeds);
  1208          }
  1209  
  1210          // Calculate any excess funds included with the bid. If the excess
  1211          // is anything worth worrying about, transfer it back to bidder.
  1212          // NOTE: We checked above that the bid amount is greater than or
  1213          // equal to the price so this cannot underflow.
  1214          uint256 bidExcess = _bidAmount - price;
  1215  
  1216          // Return the funds. Similar to the previous transfer, this is
  1217          // not susceptible to a re-entry attack because the auction is
  1218          // removed before any transfers occur.
  1219          msg.sender.transfer(bidExcess);
  1220  
  1221          // Tell the world!
  1222          AuctionSuccessful(_tokenId, price, msg.sender);
  1223  
  1224          return price;
  1225      }
  1226  
  1227      /// @dev Removes an auction from the list of open auctions.
  1228      /// @param _tokenId - ID of NFT on auction.
  1229      function _removeAuction(uint256 _tokenId) internal {
  1230          delete tokenIdToAuction[_tokenId];
  1231      }
  1232  
  1233      /// @dev Returns true if the NFT is on auction.
  1234      /// @param _auction - Auction to check.
  1235      function _isOnAuction(Auction storage _auction) internal view returns (bool) {
  1236          return (_auction.startedAt > 0);
  1237      }
  1238  
  1239      /// @dev Returns current price of an NFT on auction. Broken into two
  1240      ///  functions (this one, that computes the duration from the auction
  1241      ///  structure, and the other that does the price computation) so we
  1242      ///  can easily test that the price computation works correctly.
  1243      function _currentPrice(Auction storage _auction)
  1244          internal
  1245          view
  1246          returns (uint256)
  1247      {
  1248          uint256 secondsPassed = 0;
  1249  
  1250          // A bit of insurance against negative values (or wraparound).
  1251          // Probably not necessary (since Ethereum guarnatees that the
  1252          // now variable doesn't ever go backwards).
  1253          if (now > _auction.startedAt) {
  1254              secondsPassed = now - _auction.startedAt;
  1255          }
  1256  
  1257          return _computeCurrentPrice(
  1258              _auction.startingPrice,
  1259              _auction.endingPrice,
  1260              _auction.duration,
  1261              secondsPassed
  1262          );
  1263      }
  1264  
  1265      /// @dev Computes the current price of an auction. Factored out
  1266      ///  from _currentPrice so we can run extensive unit tests.
  1267      ///  When testing, make this function public and turn on
  1268      ///  `Current price computation` test suite.
  1269      function _computeCurrentPrice(
  1270          uint256 _startingPrice,
  1271          uint256 _endingPrice,
  1272          uint256 _duration,
  1273          uint256 _secondsPassed
  1274      )
  1275          internal
  1276          pure
  1277          returns (uint256)
  1278      {
  1279          // NOTE: We don't use SafeMath (or similar) in this function because
  1280          //  all of our public functions carefully cap the maximum values for
  1281          //  time (at 64-bits) and currency (at 128-bits). _duration is
  1282          //  also known to be non-zero (see the require() statement in
  1283          //  _addAuction())
  1284          if (_secondsPassed >= _duration) {
  1285              // We've reached the end of the dynamic pricing portion
  1286              // of the auction, just return the end price.
  1287              return _endingPrice;
  1288          } else {
  1289              // Starting price can be higher than ending price (and often is!), so
  1290              // this delta can be negative.
  1291              int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
  1292  
  1293              // This multiplication can't overflow, _secondsPassed will easily fit within
  1294              // 64-bits, and totalPriceChange will easily fit within 128-bits, their product
  1295              // will always fit within 256-bits.
  1296              int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
  1297  
  1298              // currentPriceChange can be negative, but if so, will have a magnitude
  1299              // less that _startingPrice. Thus, this result will always end up positive.
  1300              int256 currentPrice = int256(_startingPrice) + currentPriceChange;
  1301  
  1302              return uint256(currentPrice);
  1303          }
  1304      }
  1305  
  1306      /// @dev Computes owner's cut of a sale.
  1307      /// @param _price - Sale price of NFT.
  1308      function _computeCut(uint256 _price) internal view returns (uint256) {
  1309          // NOTE: We don't use SafeMath (or similar) in this function because
  1310          //  all of our entry functions carefully cap the maximum values for
  1311          //  currency (at 128-bits), and ownerCut <= 10000 (see the require()
  1312          //  statement in the ClockAuction constructor). The result of this
  1313          //  function is always guaranteed to be <= _price.
  1314          return _price * ownerCut / 10000;
  1315      }
  1316  
  1317  }
  1318  
  1319  
  1320  
  1321  
  1322  
  1323  
  1324  
  1325  /**
  1326   * @title Pausable
  1327   * @dev Base contract which allows children to implement an emergency stop mechanism.
  1328   */
  1329  contract Pausable is Ownable {
  1330    event Pause();
  1331    event Unpause();
  1332  
  1333    bool public paused = false;
  1334  
  1335  
  1336    /**
  1337     * @dev modifier to allow actions only when the contract IS paused
  1338     */
  1339    modifier whenNotPaused() {
  1340      require(!paused);
  1341      _;
  1342    }
  1343  
  1344    /**
  1345     * @dev modifier to allow actions only when the contract IS NOT paused
  1346     */
  1347    modifier whenPaused {
  1348      require(paused);
  1349      _;
  1350    }
  1351  
  1352    /**
  1353     * @dev called by the owner to pause, triggers stopped state
  1354     */
  1355    function pause() onlyOwner whenNotPaused returns (bool) {
  1356      paused = true;
  1357      Pause();
  1358      return true;
  1359    }
  1360  
  1361    /**
  1362     * @dev called by the owner to unpause, returns to normal state
  1363     */
  1364    function unpause() onlyOwner whenPaused returns (bool) {
  1365      paused = false;
  1366      Unpause();
  1367      return true;
  1368    }
  1369  }
  1370  
  1371  
  1372  /// @title Clock auction for non-fungible tokens.
  1373  /// @notice We omit a fallback function to prevent accidental sends to this contract.
  1374  contract ClockAuction is Pausable, ClockAuctionBase {
  1375  
  1376      /// @dev The ERC-165 interface signature for ERC-721.
  1377      ///  Ref: https://github.com/ethereum/EIPs/issues/165
  1378      ///  Ref: https://github.com/ethereum/EIPs/issues/721
  1379      bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
  1380  
  1381      /// @dev Constructor creates a reference to the NFT ownership contract
  1382      ///  and verifies the owner cut is in the valid range.
  1383      /// @param _nftAddress - address of a deployed contract implementing
  1384      ///  the Nonfungible Interface.
  1385      /// @param _cut - percent cut the owner takes on each auction, must be
  1386      ///  between 0-10,000.
  1387      function ClockAuction(address _nftAddress, uint256 _cut) public {
  1388          require(_cut <= 10000);
  1389          ownerCut = _cut;
  1390  
  1391          ERC721 candidateContract = ERC721(_nftAddress);
  1392          require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
  1393          nonFungibleContract = candidateContract;
  1394      }
  1395  
  1396      /// @dev Remove all Ether from the contract, which is the owner's cuts
  1397      ///  as well as any Ether sent directly to the contract address.
  1398      ///  Always transfers to the NFT contract, but can be called either by
  1399      ///  the owner or the NFT contract.
  1400      function withdrawBalance() external {
  1401          address nftAddress = address(nonFungibleContract);
  1402  
  1403          require(
  1404              msg.sender == owner ||
  1405              msg.sender == nftAddress
  1406          );
  1407          // We are using this boolean method to make sure that even if one fails it will still work
  1408          bool res = nftAddress.send(this.balance);
  1409      }
  1410  
  1411      /// @dev Creates and begins a new auction.
  1412      /// @param _tokenId - ID of token to auction, sender must be owner.
  1413      /// @param _startingPrice - Price of item (in wei) at beginning of auction.
  1414      /// @param _endingPrice - Price of item (in wei) at end of auction.
  1415      /// @param _duration - Length of time to move between starting
  1416      ///  price and ending price (in seconds).
  1417      /// @param _seller - Seller, if not the message sender
  1418      function createAuction(
  1419          uint256 _tokenId,
  1420          uint256 _startingPrice,
  1421          uint256 _endingPrice,
  1422          uint256 _duration,
  1423          address _seller
  1424      )
  1425          external
  1426          whenNotPaused
  1427      {
  1428          // Sanity check that no inputs overflow how many bits we've allocated
  1429          // to store them in the auction struct.
  1430          require(_startingPrice == uint256(uint128(_startingPrice)));
  1431          require(_endingPrice == uint256(uint128(_endingPrice)));
  1432          require(_duration == uint256(uint64(_duration)));
  1433  
  1434          require(_owns(msg.sender, _tokenId));
  1435          _escrow(msg.sender, _tokenId);
  1436          Auction memory auction = Auction(
  1437              _seller,
  1438              uint128(_startingPrice),
  1439              uint128(_endingPrice),
  1440              uint64(_duration),
  1441              uint64(now)
  1442          );
  1443          _addAuction(_tokenId, auction);
  1444      }
  1445  
  1446      /// @dev Bids on an open auction, completing the auction and transferring
  1447      ///  ownership of the NFT if enough Ether is supplied.
  1448      /// @param _tokenId - ID of token to bid on.
  1449      function bid(uint256 _tokenId)
  1450          external
  1451          payable
  1452          whenNotPaused
  1453      {
  1454          // _bid will throw if the bid or funds transfer fails
  1455          _bid(_tokenId, msg.value);
  1456          _transfer(msg.sender, _tokenId);
  1457      }
  1458  
  1459      /// @dev Cancels an auction that hasn't been won yet.
  1460      ///  Returns the NFT to original owner.
  1461      /// @notice This is a state-modifying function that can
  1462      ///  be called while the contract is paused.
  1463      /// @param _tokenId - ID of token on auction
  1464      function cancelAuction(uint256 _tokenId)
  1465          external
  1466      {
  1467          Auction storage auction = tokenIdToAuction[_tokenId];
  1468          require(_isOnAuction(auction));
  1469          address seller = auction.seller;
  1470          require(msg.sender == seller);
  1471          _cancelAuction(_tokenId, seller);
  1472      }
  1473  
  1474      /// @dev Cancels an auction when the contract is paused.
  1475      ///  Only the owner may do this, and NFTs are returned to
  1476      ///  the seller. This should only be used in emergencies.
  1477      /// @param _tokenId - ID of the NFT on auction to cancel.
  1478      function cancelAuctionWhenPaused(uint256 _tokenId)
  1479          whenPaused
  1480          onlyOwner
  1481          external
  1482      {
  1483          Auction storage auction = tokenIdToAuction[_tokenId];
  1484          require(_isOnAuction(auction));
  1485          _cancelAuction(_tokenId, auction.seller);
  1486      }
  1487  
  1488      /// @dev Returns auction info for an NFT on auction.
  1489      /// @param _tokenId - ID of NFT on auction.
  1490      function getAuction(uint256 _tokenId)
  1491          external
  1492          view
  1493          returns
  1494      (
  1495          address seller,
  1496          uint256 startingPrice,
  1497          uint256 endingPrice,
  1498          uint256 duration,
  1499          uint256 startedAt
  1500      ) {
  1501          Auction storage auction = tokenIdToAuction[_tokenId];
  1502          require(_isOnAuction(auction));
  1503          return (
  1504              auction.seller,
  1505              auction.startingPrice,
  1506              auction.endingPrice,
  1507              auction.duration,
  1508              auction.startedAt
  1509          );
  1510      }
  1511  
  1512      /// @dev Returns the current price of an auction.
  1513      /// @param _tokenId - ID of the token price we are checking.
  1514      function getCurrentPrice(uint256 _tokenId)
  1515          external
  1516          view
  1517          returns (uint256)
  1518      {
  1519          Auction storage auction = tokenIdToAuction[_tokenId];
  1520          require(_isOnAuction(auction));
  1521          return _currentPrice(auction);
  1522      }
  1523  
  1524  }
  1525  
  1526  
  1527  /// @title Reverse auction modified for siring
  1528  /// @notice We omit a fallback function to prevent accidental sends to this contract.
  1529  contract SiringClockAuction is ClockAuction {
  1530  
  1531      // @dev Sanity check that allows us to ensure that we are pointing to the
  1532      //  right auction in our setSiringAuctionAddress() call.
  1533      bool public isSiringClockAuction = true;
  1534  
  1535      // Delegate constructor
  1536      function SiringClockAuction(address _nftAddr, uint256 _cut) public
  1537          ClockAuction(_nftAddr, _cut) {}
  1538  
  1539      /// @dev Creates and begins a new auction. Since this function is wrapped,
  1540      /// require sender to be KittyCore contract.
  1541      /// @param _tokenId - ID of token to auction, sender must be owner.
  1542      /// @param _startingPrice - Price of item (in wei) at beginning of auction.
  1543      /// @param _endingPrice - Price of item (in wei) at end of auction.
  1544      /// @param _duration - Length of auction (in seconds).
  1545      /// @param _seller - Seller, if not the message sender
  1546      function createAuction(
  1547          uint256 _tokenId,
  1548          uint256 _startingPrice,
  1549          uint256 _endingPrice,
  1550          uint256 _duration,
  1551          address _seller
  1552      )
  1553          external
  1554      {
  1555          // Sanity check that no inputs overflow how many bits we've allocated
  1556          // to store them in the auction struct.
  1557          require(_startingPrice == uint256(uint128(_startingPrice)));
  1558          require(_endingPrice == uint256(uint128(_endingPrice)));
  1559          require(_duration == uint256(uint64(_duration)));
  1560  
  1561          require(msg.sender == address(nonFungibleContract));
  1562          _escrow(_seller, _tokenId);
  1563          Auction memory auction = Auction(
  1564              _seller,
  1565              uint128(_startingPrice),
  1566              uint128(_endingPrice),
  1567              uint64(_duration),
  1568              uint64(now)
  1569          );
  1570          _addAuction(_tokenId, auction);
  1571      }
  1572  
  1573      /// @dev Places a bid for siring. Requires the sender
  1574      /// is the KittyCore contract because all bid methods
  1575      /// should be wrapped. Also returns the kitty to the
  1576      /// seller rather than the winner.
  1577      function bid(uint256 _tokenId)
  1578          external
  1579          payable
  1580      {
  1581          require(msg.sender == address(nonFungibleContract));
  1582          address seller = tokenIdToAuction[_tokenId].seller;
  1583          // _bid checks that token ID is valid and will throw if bid fails
  1584          _bid(_tokenId, msg.value);
  1585          // We transfer the kitty back to the seller, the winner will get
  1586          // the offspring
  1587          _transfer(seller, _tokenId);
  1588      }
  1589  
  1590  }
  1591  
  1592  
  1593  
  1594  
  1595  
  1596  /// @title Clock auction modified for sale of kitties
  1597  /// @notice We omit a fallback function to prevent accidental sends to this contract.
  1598  contract SaleClockAuction is ClockAuction {
  1599  
  1600      // @dev Sanity check that allows us to ensure that we are pointing to the
  1601      //  right auction in our setSaleAuctionAddress() call.
  1602      bool public isSaleClockAuction = true;
  1603  
  1604      // Tracks last 5 sale price of gen0 kitty sales
  1605      uint256 public gen0SaleCount;
  1606      uint256[5] public lastGen0SalePrices;
  1607  
  1608      // Delegate constructor
  1609      function SaleClockAuction(address _nftAddr, uint256 _cut) public
  1610          ClockAuction(_nftAddr, _cut) {}
  1611  
  1612      /// @dev Creates and begins a new auction.
  1613      /// @param _tokenId - ID of token to auction, sender must be owner.
  1614      /// @param _startingPrice - Price of item (in wei) at beginning of auction.
  1615      /// @param _endingPrice - Price of item (in wei) at end of auction.
  1616      /// @param _duration - Length of auction (in seconds).
  1617      /// @param _seller - Seller, if not the message sender
  1618      function createAuction(
  1619          uint256 _tokenId,
  1620          uint256 _startingPrice,
  1621          uint256 _endingPrice,
  1622          uint256 _duration,
  1623          address _seller
  1624      )
  1625          external
  1626      {
  1627          // Sanity check that no inputs overflow how many bits we've allocated
  1628          // to store them in the auction struct.
  1629          require(_startingPrice == uint256(uint128(_startingPrice)));
  1630          require(_endingPrice == uint256(uint128(_endingPrice)));
  1631          require(_duration == uint256(uint64(_duration)));
  1632  
  1633          require(msg.sender == address(nonFungibleContract));
  1634          _escrow(_seller, _tokenId);
  1635          Auction memory auction = Auction(
  1636              _seller,
  1637              uint128(_startingPrice),
  1638              uint128(_endingPrice),
  1639              uint64(_duration),
  1640              uint64(now)
  1641          );
  1642          _addAuction(_tokenId, auction);
  1643      }
  1644  
  1645      /// @dev Updates lastSalePrice if seller is the nft contract
  1646      /// Otherwise, works the same as default bid method.
  1647      function bid(uint256 _tokenId)
  1648          external
  1649          payable
  1650      {
  1651          // _bid verifies token ID size
  1652          address seller = tokenIdToAuction[_tokenId].seller;
  1653          uint256 price = _bid(_tokenId, msg.value);
  1654          _transfer(msg.sender, _tokenId);
  1655  
  1656          // If not a gen0 auction, exit
  1657          if (seller == address(nonFungibleContract)) {
  1658              // Track gen0 sale prices
  1659              lastGen0SalePrices[gen0SaleCount % 5] = price;
  1660              gen0SaleCount++;
  1661          }
  1662      }
  1663  
  1664      function averageGen0SalePrice() external view returns (uint256) {
  1665          uint256 sum = 0;
  1666          for (uint256 i = 0; i < 5; i++) {
  1667              sum += lastGen0SalePrices[i];
  1668          }
  1669          return sum / 5;
  1670      }
  1671  
  1672  }
  1673  
  1674  
  1675  /// @title Handles creating auctions for sale and siring of kitties.
  1676  ///  This wrapper of ReverseAuction exists only so that users can create
  1677  ///  auctions with only one transaction.
  1678  contract KittyAuction is KittyBreeding {
  1679  
  1680      // @notice The auction contract variables are defined in KittyBase to allow
  1681      //  us to refer to them in KittyOwnership to prevent accidental transfers.
  1682      // `saleAuction` refers to the auction for gen0 and p2p sale of kitties.
  1683      // `siringAuction` refers to the auction for siring rights of kitties.
  1684  
  1685      /// @dev Sets the reference to the sale auction.
  1686      /// @param _address - Address of sale contract.
  1687      function setSaleAuctionAddress(address _address) external onlyCEO {
  1688          SaleClockAuction candidateContract = SaleClockAuction(_address);
  1689  
  1690          // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
  1691          require(candidateContract.isSaleClockAuction());
  1692  
  1693          // Set the new contract address
  1694          saleAuction = candidateContract;
  1695      }
  1696  
  1697      /// @dev Sets the reference to the siring auction.
  1698      /// @param _address - Address of siring contract.
  1699      function setSiringAuctionAddress(address _address) external onlyCEO {
  1700          SiringClockAuction candidateContract = SiringClockAuction(_address);
  1701  
  1702          // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
  1703          require(candidateContract.isSiringClockAuction());
  1704  
  1705          // Set the new contract address
  1706          siringAuction = candidateContract;
  1707      }
  1708  
  1709      /// @dev Put a kitty up for auction.
  1710      ///  Does some ownership trickery to create auctions in one tx.
  1711      function createSaleAuction(
  1712          uint256 _kittyId,
  1713          uint256 _startingPrice,
  1714          uint256 _endingPrice,
  1715          uint256 _duration
  1716      )
  1717          external
  1718          whenNotPaused
  1719      {
  1720          // Auction contract checks input sizes
  1721          // If kitty is already on any auction, this will throw
  1722          // because it will be owned by the auction contract.
  1723          require(_owns(msg.sender, _kittyId));
  1724          // Ensure the kitty is not pregnant to prevent the auction
  1725          // contract accidentally receiving ownership of the child.
  1726          // NOTE: the kitty IS allowed to be in a cooldown.
  1727          require(!isPregnant(_kittyId));
  1728          _approve(_kittyId, saleAuction);
  1729          // Sale auction throws if inputs are invalid and clears
  1730          // transfer and sire approval after escrowing the kitty.
  1731          saleAuction.createAuction(
  1732              _kittyId,
  1733              _startingPrice,
  1734              _endingPrice,
  1735              _duration,
  1736              msg.sender
  1737          );
  1738      }
  1739  
  1740      /// @dev Put a kitty up for auction to be sire.
  1741      ///  Performs checks to ensure the kitty can be sired, then
  1742      ///  delegates to reverse auction.
  1743      function createSiringAuction(
  1744          uint256 _kittyId,
  1745          uint256 _startingPrice,
  1746          uint256 _endingPrice,
  1747          uint256 _duration
  1748      )
  1749          external
  1750          whenNotPaused
  1751      {
  1752          // Auction contract checks input sizes
  1753          // If kitty is already on any auction, this will throw
  1754          // because it will be owned by the auction contract.
  1755          require(_owns(msg.sender, _kittyId));
  1756          require(isReadyToBreed(_kittyId));
  1757          _approve(_kittyId, siringAuction);
  1758          // Siring auction throws if inputs are invalid and clears
  1759          // transfer and sire approval after escrowing the kitty.
  1760          siringAuction.createAuction(
  1761              _kittyId,
  1762              _startingPrice,
  1763              _endingPrice,
  1764              _duration,
  1765              msg.sender
  1766          );
  1767      }
  1768  
  1769      /// @dev Completes a siring auction by bidding.
  1770      ///  Immediately breeds the winning matron with the sire on auction.
  1771      /// @param _sireId - ID of the sire on auction.
  1772      /// @param _matronId - ID of the matron owned by the bidder.
  1773      function bidOnSiringAuction(
  1774          uint256 _sireId,
  1775          uint256 _matronId
  1776      )
  1777          external
  1778          payable
  1779          whenNotPaused
  1780      {
  1781          // Auction contract checks input sizes
  1782          require(_owns(msg.sender, _matronId));
  1783          require(isReadyToBreed(_matronId));
  1784          require(_canBreedWithViaAuction(_matronId, _sireId));
  1785  
  1786          // Define the current price of the auction.
  1787          uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
  1788          require(msg.value >= currentPrice + autoBirthFee);
  1789  
  1790          // Siring auction will throw if the bid fails.
  1791          siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
  1792          _breedWith(uint32(_matronId), uint32(_sireId));
  1793      }
  1794  
  1795      /// @dev Transfers the balance of the sale auction contract
  1796      /// to the KittyCore contract. We use two-step withdrawal to
  1797      /// prevent two transfer calls in the auction bid function.
  1798      function withdrawAuctionBalances() external onlyCLevel {
  1799          saleAuction.withdrawBalance();
  1800          siringAuction.withdrawBalance();
  1801      }
  1802  }
  1803  
  1804  
  1805  /// @title all functions related to creating kittens
  1806  contract KittyMinting is KittyAuction {
  1807  
  1808      // Limits the number of cats the contract owner can ever create.
  1809      uint256 public constant PROMO_CREATION_LIMIT = 5000;
  1810      uint256 public constant GEN0_CREATION_LIMIT = 45000;
  1811  
  1812      // Constants for gen0 auctions.
  1813      uint256 public constant GEN0_STARTING_PRICE = 10 finney;
  1814      uint256 public constant GEN0_AUCTION_DURATION = 1 days;
  1815  
  1816      // Counts the number of cats the contract owner has created.
  1817      uint256 public promoCreatedCount;
  1818      uint256 public gen0CreatedCount;
  1819  
  1820      /// @dev we can create promo kittens, up to a limit. Only callable by COO
  1821      /// @param _genes the encoded genes of the kitten to be created, any value is accepted
  1822      /// @param _owner the future owner of the created kittens. Default to contract COO
  1823      function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
  1824          address kittyOwner = _owner;
  1825          if (kittyOwner == address(0)) {
  1826               kittyOwner = cooAddress;
  1827          }
  1828          require(promoCreatedCount < PROMO_CREATION_LIMIT);
  1829  
  1830          promoCreatedCount++;
  1831          _createKitty(0, 0, 0, _genes, kittyOwner);
  1832      }
  1833  
  1834      /// @dev Creates a new gen0 kitty with the given genes and
  1835      ///  creates an auction for it.
  1836      function createGen0Auction(uint256 _genes) external onlyCOO {
  1837          require(gen0CreatedCount < GEN0_CREATION_LIMIT);
  1838  
  1839          uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this));
  1840          _approve(kittyId, saleAuction);
  1841  
  1842          saleAuction.createAuction(
  1843              kittyId,
  1844              _computeNextGen0Price(),
  1845              0,
  1846              GEN0_AUCTION_DURATION,
  1847              address(this)
  1848          );
  1849  
  1850          gen0CreatedCount++;
  1851      }
  1852  
  1853      /// @dev Computes the next gen0 auction starting price, given
  1854      ///  the average of the past 5 prices + 50%.
  1855      function _computeNextGen0Price() internal view returns (uint256) {
  1856          uint256 avePrice = saleAuction.averageGen0SalePrice();
  1857  
  1858          // Sanity check to ensure we don't overflow arithmetic
  1859          require(avePrice == uint256(uint128(avePrice)));
  1860  
  1861          uint256 nextPrice = avePrice + (avePrice / 2);
  1862  
  1863          // We never auction for less than starting price
  1864          if (nextPrice < GEN0_STARTING_PRICE) {
  1865              nextPrice = GEN0_STARTING_PRICE;
  1866          }
  1867  
  1868          return nextPrice;
  1869      }
  1870  }
  1871  
  1872  
  1873  /// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain.
  1874  /// @author Axiom Zen (https://www.axiomzen.co)
  1875  /// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost.
  1876  contract KittyCore is KittyMinting {
  1877  
  1878      // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections,
  1879      // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
  1880      // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
  1881      // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
  1882      // them in their own contracts, we can upgrade them without disrupting the main contract that tracks
  1883      // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of
  1884      // the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
  1885      // Don't worry, I'm sure someone will reverse engineer it soon enough!
  1886      //
  1887      // Secondly, we break the core contract into multiple files using inheritence, one for each major
  1888      // facet of functionality of CK. This allows us to keep related code bundled together while still
  1889      // avoiding a single giant file with everything in it. The breakdown is as follows:
  1890      //
  1891      //      - KittyBase: This is where we define the most fundamental code shared throughout the core
  1892      //             functionality. This includes our main data storage, constants and data types, plus
  1893      //             internal functions for managing these items.
  1894      //
  1895      //      - KittyAccessControl: This contract manages the various addresses and constraints for operations
  1896      //             that can be executed only by specific roles. Namely CEO, CFO and COO.
  1897      //
  1898      //      - KittyOwnership: This provides the methods required for basic non-fungible token
  1899      //             transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
  1900      //
  1901      //      - KittyBreeding: This file contains the methods necessary to breed cats together, including
  1902      //             keeping track of siring offers, and relies on an external genetic combination contract.
  1903      //
  1904      //      - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring
  1905      //             services. The actual auction functionality is handled in two sibling contracts (one
  1906      //             for sales and one for siring), while auction creation and bidding is mostly mediated
  1907      //             through this facet of the core contract.
  1908      //
  1909      //      - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats.
  1910      //             We can make up to 5000 "promo" cats that can be given away (especially important when
  1911      //             the community is new), and all others can only be created and then immediately put up
  1912      //             for auction via an algorithmically determined starting price. Regardless of how they
  1913      //             are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
  1914      //             community to breed, breed, breed!
  1915  
  1916      // Set in case the core contract is broken and an upgrade is required
  1917      address public newContractAddress;
  1918  
  1919      /// @notice Creates the main CryptoKitties smart contract instance.
  1920      function KittyCore() public {
  1921          // Starts paused.
  1922          paused = true;
  1923  
  1924          // the creator of the contract is the initial CEO
  1925          ceoAddress = msg.sender;
  1926  
  1927          // the creator of the contract is also the initial COO
  1928          cooAddress = msg.sender;
  1929  
  1930          // start with the mythical kitten 0 - so we don't have generation-0 parent issues
  1931          _createKitty(0, 0, 0, uint256(-1), address(0));
  1932      }
  1933  
  1934      /// @dev Used to mark the smart contract as upgraded, in case there is a serious
  1935      ///  breaking bug. This method does nothing but keep track of the new contract and
  1936      ///  emit a message indicating that the new address is set. It's up to clients of this
  1937      ///  contract to update to the new contract address in that case. (This contract will
  1938      ///  be paused indefinitely if such an upgrade takes place.)
  1939      /// @param _v2Address new address
  1940      function setNewAddress(address _v2Address) external onlyCEO whenPaused {
  1941          // See README.md for updgrade plan
  1942          newContractAddress = _v2Address;
  1943          ContractUpgrade(_v2Address);
  1944      }
  1945  
  1946      /// @notice No tipping!
  1947      /// @dev Reject all Ether from being sent here, unless it's from one of the
  1948      ///  two auction contracts. (Hopefully, we can prevent user accidents.)
  1949      function() external payable {
  1950          require(
  1951              msg.sender == address(saleAuction) ||
  1952              msg.sender == address(siringAuction)
  1953          );
  1954      }
  1955  
  1956      /// @notice Returns all the relevant information about a specific kitty.
  1957      /// @param _id The ID of the kitty of interest.
  1958      function getKitty(uint256 _id)
  1959          external
  1960          view
  1961          returns (
  1962          bool isGestating,
  1963          bool isReady,
  1964          uint256 cooldownIndex,
  1965          uint256 nextActionAt,
  1966          uint256 siringWithId,
  1967          uint256 birthTime,
  1968          uint256 matronId,
  1969          uint256 sireId,
  1970          uint256 generation,
  1971          uint256 genes
  1972      ) {
  1973          Kitty storage kit = kitties[_id];
  1974  
  1975          // if this variable is 0 then it's not gestating
  1976          isGestating = (kit.siringWithId != 0);
  1977          isReady = (kit.cooldownEndBlock <= block.number);
  1978          cooldownIndex = uint256(kit.cooldownIndex);
  1979          nextActionAt = uint256(kit.cooldownEndBlock);
  1980          siringWithId = uint256(kit.siringWithId);
  1981          birthTime = uint256(kit.birthTime);
  1982          matronId = uint256(kit.matronId);
  1983          sireId = uint256(kit.sireId);
  1984          generation = uint256(kit.generation);
  1985          genes = kit.genes;
  1986      }
  1987  
  1988      /// @dev Override unpause so it requires all external contract addresses
  1989      ///  to be set before contract can be unpaused. Also, we can't have
  1990      ///  newContractAddress set either, because then the contract was upgraded.
  1991      /// @notice This is public rather than external so we can call super.unpause
  1992      ///  without using an expensive CALL.
  1993      function unpause() public onlyCEO whenPaused {
  1994          require(saleAuction != address(0));
  1995          require(siringAuction != address(0));
  1996          require(geneScience != address(0));
  1997          require(newContractAddress == address(0));
  1998  
  1999          // Actually unpause the contract.
  2000          super.unpause();
  2001      }
  2002  
  2003      // @dev Allows the CFO to capture the balance available to the contract.
  2004      function withdrawBalance() external onlyCFO {
  2005          uint256 balance = this.balance;
  2006          // Subtract all the currently pregnant kittens we have, plus 1 of margin.
  2007          uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee;
  2008  
  2009          if (balance > subtractFees) {
  2010              cfoAddress.send(balance - subtractFees);
  2011          }
  2012      }
  2013  }