ETH Price: $2,149.78 (-2.04%)

Transaction Decoder

Block:
8732518 at Oct-13-2019 10:07:05 AM +UTC
Transaction Fee:
0.00047322 ETH $1.02
Gas Used:
52,580 Gas / 9 Gwei

Emitted Events:

21 KittyCore.Transfer( from=SaleClockAuction, to=[Receiver] CloneableWallet, tokenId=1694122 )
22 SaleClockAuction.AuctionCancelled( tokenId=1694122 )
23 CloneableWallet.InvocationSuccess( hash=FA1E76EB311C0930B38D06A6F0F4798FF2B820F9A058AF6173A3E6DAB7A361AE, result=0, numOperations=1 )

Account State Difference:

  Address   Before After State Difference Code
0x06012c8c...f8E7A266d
(K1POOL.COM)
0.701940754039451285 Eth0.702413974039451285 Eth0.00047322
0x70E78DD5...e5C322C1F
0.299527356 Eth
Nonce: 3041
0.299054136 Eth
Nonce: 3042
0.00047322
0x8C3dfFaB...Ab0A4B3b6
0xb1690C08...20FB57d8C
(CryptoKitties: Sales Auction)

Execution Trace

CloneableWallet.invoke1CosignerSends( v=28, r=B4DFAFC064E1A90EC188728A78A33B12E7E37D627B1D085F411DE25189D97DE0, s=366C4477CCF5B238AA932DDD4A6650F177121AF0BDCB6E6AA24CE94B191E273F, nonce=1753, authorizedAddress=0x1F4b98e78E5e504179ae3108EA3422B5c8f929a3, data=0x00B1690C08E213A35ED9BAB7B318DE14420FB57D8C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002496B5A755000000000000000000000000000000000000000000000000000000000019D9AA )
  • CloneableWallet.invoke1CosignerSends( v=28, r=B4DFAFC064E1A90EC188728A78A33B12E7E37D627B1D085F411DE25189D97DE0, s=366C4477CCF5B238AA932DDD4A6650F177121AF0BDCB6E6AA24CE94B191E273F, nonce=1753, authorizedAddress=0x1F4b98e78E5e504179ae3108EA3422B5c8f929a3, data=0x00B1690C08E213A35ED9BAB7B318DE14420FB57D8C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002496B5A755000000000000000000000000000000000000000000000000000000000019D9AA )
    • Null: 0x000...001.fa1e76eb( )
    • SaleClockAuction.cancelAuction( _tokenId=1694122 )
      • KittyCore.transfer( _to=0x8C3dfFaB3Cc45FB09410dedFC23446dAb0A4B3b6, _tokenId=1694122 )
        invoke1CosignerSends[CoreWallet (ln:622)]
        File 1 of 4: CloneableWallet
        // File: contracts/ERC721/ERC721ReceiverDraft.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ERC721ReceiverDraft
        /// @dev Interface for any contract that wants to support safeTransfers from
        ///  ERC721 asset contracts.
        /// @dev Note: this is the interface defined from 
        ///  https://github.com/ethereum/EIPs/commit/2bddd126def7c046e1e62408dc2b51bdd9e57f0f
        ///  to https://github.com/ethereum/EIPs/commit/27788131d5975daacbab607076f2ee04624f9dbb 
        ///  and is not the final interface.
        ///  Due to the extended period of time this revision was specified in the draft,
        ///  we are supporting both this and the newer (final) interface in order to be 
        ///  compatible with any ERC721 implementations that may have used this interface.
        contract ERC721ReceiverDraft {
        
            /// @dev Magic value to be returned upon successful reception of an NFT
            ///  Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
            ///  which can be also obtained as `ERC721ReceiverDraft(0).onERC721Received.selector`
            /// @dev see https://github.com/ethereum/EIPs/commit/2bddd126def7c046e1e62408dc2b51bdd9e57f0f
            bytes4 internal constant ERC721_RECEIVED_DRAFT = 0xf0b9e5ba;
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            ///  after a `transfer`. This function MAY throw to revert and reject the
            ///  transfer. This function MUST use 50,000 gas or less. Return of other
            ///  than the magic value MUST result in the transaction being reverted.
            ///  Note: the contract address is always the message sender.
            /// @param _from The sending address 
            /// @param _tokenId The NFT identifier which is being transfered
            /// @param data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
            ///  unless throwing
            function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
        }
        
        // File: contracts/ERC721/ERC721ReceiverFinal.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ERC721ReceiverFinal
        /// @notice Interface for any contract that wants to support safeTransfers from
        ///  ERC721 asset contracts.
        ///  @dev Note: this is the final interface as defined at http://erc721.org
        contract ERC721ReceiverFinal {
        
            /// @dev Magic value to be returned upon successful reception of an NFT
            ///  Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
            ///  which can be also obtained as `ERC721ReceiverFinal(0).onERC721Received.selector`
            /// @dev see https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v1.12.0/contracts/token/ERC721/ERC721Receiver.sol
            bytes4 internal constant ERC721_RECEIVED_FINAL = 0x150b7a02;
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            /// after a `safetransfer`. This function MAY throw to revert and reject the
            /// transfer. Return of other than the magic value MUST result in the
            /// transaction being reverted.
            /// Note: the contract address is always the message sender.
            /// @param _operator The address which called `safeTransferFrom` function
            /// @param _from The address which previously owned the token
            /// @param _tokenId The NFT identifier which is being transferred
            /// @param _data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
            function onERC721Received(
                address _operator,
                address _from,
                uint256 _tokenId,
                bytes _data
            )
            public
                returns (bytes4);
        }
        
        // File: contracts/ERC721/ERC721Receivable.sol
        
        pragma solidity ^0.4.24;
        
        
        
        /// @title ERC721Receivable handles the reception of ERC721 tokens
        ///  See ERC721 specification
        /// @author Christopher Scott
        /// @dev These functions are public, and could be called by anyone, even in the case
        ///  where no NFTs have been transferred. Since it's not a reliable source of
        ///  truth about ERC721 tokens being transferred, we save the gas and don't
        ///  bother emitting a (potentially spurious) event as found in 
        ///  https://github.com/OpenZeppelin/openzeppelin-solidity/blob/5471fc808a17342d738853d7bf3e9e5ef3108074/contracts/mocks/ERC721ReceiverMock.sol
        contract ERC721Receivable is ERC721ReceiverDraft, ERC721ReceiverFinal {
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            ///  after a `transfer`. This function MAY throw to revert and reject the
            ///  transfer. This function MUST use 50,000 gas or less. Return of other
            ///  than the magic value MUST result in the transaction being reverted.
            ///  Note: the contract address is always the message sender.
            /// @param _from The sending address 
            /// @param _tokenId The NFT identifier which is being transfered
            /// @param data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
            ///  unless throwing
            function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4) {
                _from;
                _tokenId;
                data;
        
                // emit ERC721Received(_operator, _from, _tokenId, _data, gasleft());
        
                return ERC721_RECEIVED_DRAFT;
            }
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            /// after a `safetransfer`. This function MAY throw to revert and reject the
            /// transfer. Return of other than the magic value MUST result in the
            /// transaction being reverted.
            /// Note: the contract address is always the message sender.
            /// @param _operator The address which called `safeTransferFrom` function
            /// @param _from The address which previously owned the token
            /// @param _tokenId The NFT identifier which is being transferred
            /// @param _data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
            function onERC721Received(
                address _operator,
                address _from,
                uint256 _tokenId,
                bytes _data
            )
                public
                returns(bytes4)
            {
                _operator;
                _from;
                _tokenId;
                _data;
        
                // emit ERC721Received(_operator, _from, _tokenId, _data, gasleft());
        
                return ERC721_RECEIVED_FINAL;
            }
        
        }
        
        // File: contracts/ERC223/ERC223Receiver.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ERC223Receiver ensures we are ERC223 compatible
        /// @author Christopher Scott
        contract ERC223Receiver {
            
            bytes4 public constant ERC223_ID = 0xc0ee0b8a;
        
            struct TKN {
                address sender;
                uint value;
                bytes data;
                bytes4 sig;
            }
            
            /// @notice tokenFallback is called from an ERC223 compatible contract
            /// @param _from the address from which the token was sent
            /// @param _value the amount of tokens sent
            /// @param _data the data sent with the transaction
            function tokenFallback(address _from, uint _value, bytes _data) public pure {
                _from;
                _value;
                _data;
            //   TKN memory tkn;
            //   tkn.sender = _from;
            //   tkn.value = _value;
            //   tkn.data = _data;
            //   uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
            //   tkn.sig = bytes4(u);
              
              /* tkn variable is analogue of msg variable of Ether transaction
              *  tkn.sender is person who initiated this token transaction   (analogue of msg.sender)
              *  tkn.value the number of tokens that were sent   (analogue of msg.value)
              *  tkn.data is data of token transaction   (analogue of msg.data)
              *  tkn.sig is 4 bytes signature of function
              *  if data of token transaction is a function execution
              */
        
            }
        }
        
        // File: contracts/ERC1271/ERC1271.sol
        
        pragma solidity ^0.4.24;
        
        contract ERC1271 {
        
            /// @dev bytes4(keccak256("isValidSignature(bytes32,bytes)")
            bytes4 internal constant ERC1271_VALIDSIGNATURE = 0x1626ba7e;
        
            /// @dev Should return whether the signature provided is valid for the provided data
            /// @param hash 32-byte hash of the data that is signed
            /// @param _signature Signature byte array associated with _data
            ///  MUST return the bytes4 magic value 0x1626ba7e when function passes.
            ///  MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
            ///  MUST allow external calls
            function isValidSignature(
                bytes32 hash, 
                bytes _signature)
                external
                view 
                returns (bytes4);
        }
        
        // File: contracts/ECDSA.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ECDSA is a library that contains useful methods for working with ECDSA signatures
        library ECDSA {
        
            /// @notice Extracts the r, s, and v components from the `sigData` field starting from the `offset`
            /// @dev Note: does not do any bounds checking on the arguments!
            /// @param sigData the signature data; could be 1 or more packed signatures.
            /// @param offset the offset in sigData from which to start unpacking the signature components.
            function extractSignature(bytes sigData, uint256 offset) internal pure returns  (bytes32 r, bytes32 s, uint8 v) {
                // Divide the signature in r, s and v variables
                // ecrecover takes the signature parameters, and the only way to get them
                // currently is to use assembly.
                // solium-disable-next-line security/no-inline-assembly
                assembly {
                     let dataPointer := add(sigData, offset)
                     r := mload(add(dataPointer, 0x20))
                     s := mload(add(dataPointer, 0x40))
                     v := byte(0, mload(add(dataPointer, 0x60)))
                }
            
                return (r, s, v);
            }
        }
        
        // File: contracts/Wallet/CoreWallet.sol
        
        pragma solidity ^0.4.24;
        
        
        
        
        
        
        /// @title Core Wallet
        /// @notice A basic smart contract wallet with cosigner functionality. The notion of "cosigner" is
        ///  the simplest possible multisig solution, a two-of-two signature scheme. It devolves nicely
        ///  to "one-of-one" (i.e. singlesig) by simply having the cosigner set to the same value as
        ///  the main signer.
        /// 
        ///  Most "advanced" functionality (deadman's switch, multiday recovery flows, blacklisting, etc)
        ///  can be implemented externally to this smart contract, either as an additional smart contract
        ///  (which can be tracked as a signer without cosigner, or as a cosigner) or as an off-chain flow
        ///  using a public/private key pair as cosigner. Of course, the basic cosigning functionality could
        ///  also be implemented in this way, but (A) the complexity and gas cost of two-of-two multisig (as
        ///  implemented here) is negligable even if you don't need the cosigner functionality, and
        ///  (B) two-of-two multisig (as implemented here) handles a lot of really common use cases, most
        ///  notably third-party gas payment and off-chain blacklisting and fraud detection.
        contract CoreWallet is ERC721Receivable, ERC223Receiver, ERC1271  {
        
            using ECDSA for bytes;
        
            /// @notice We require that presigned transactions use the EIP-191 signing format.
            ///  See that EIP for more info: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-191.md
            byte public constant EIP191_VERSION_DATA = byte(0);
            byte public constant EIP191_PREFIX = byte(0x19);
        
            /// @notice This is the version of the contract.
            string public constant VERSION = "1.0.0";
        
            /// @notice A pre-shifted "1", used to increment the authVersion, so we can "prepend"
            ///  the authVersion to an address (for lookups in the authorizations mapping)
            ///  by using the '+' operator (which is cheaper than a shift and a mask). See the
            ///  comment on the `authorizations` variable for how this is used.
            uint256 public constant AUTH_VERSION_INCREMENTOR = (1 << 160);
            
            /// @notice The pre-shifted authVersion (to get the current authVersion as an integer,
            ///  shift this value right by 160 bits). Starts as `1 << 160` (`AUTH_VERSION_INCREMENTOR`)
            ///  See the comment on the `authorizations` variable for how this is used.
            uint256 public authVersion;
        
            /// @notice A mapping containing all of the addresses that are currently authorized to manage
            ///  the assets owned by this wallet.
            ///
            ///  The keys in this mapping are authorized addresses with a version number prepended,
            ///  like so: (authVersion,96)(address,160). The current authVersion MUST BE included
            ///  for each look-up; this allows us to effectively clear the entire mapping of its
            ///  contents merely by incrementing the authVersion variable. (This is important for
            ///  the emergencyRecovery() method.) Inspired by https://ethereum.stackexchange.com/a/42540
            ///
            ///  The values in this mapping are 256bit words, whose lower 20 bytes constitute "cosigners"
            ///  for each address. If an address maps to itself, then that address is said to have no cosigner.
            ///
            ///  The upper 12 bytes are reserved for future meta-data purposes.  The meta-data could refer
            ///  to the key (authorized address) or the value (cosigner) of the mapping.
            ///
            ///  Addresses that map to a non-zero cosigner in the current authVersion are called
            ///  "authorized addresses".
            mapping(uint256 => uint256) public authorizations;
        
            /// @notice A per-key nonce value, incremented each time a transaction is processed with that key.
            ///  Used for replay prevention. The nonce value in the transaction must exactly equal the current
            ///  nonce value in the wallet for that key. (This mirrors the way Ethereum's transaction nonce works.)
            mapping(address => uint256) public nonces;
        
            /// @notice A special address that is authorized to call `emergencyRecovery()`. That function
            ///  resets ALL authorization for this wallet, and must therefore be treated with utmost security.
            ///  Reasonable choices for recoveryAddress include:
            ///       - the address of a private key in cold storage
            ///       - a physically secured hardware wallet
            ///       - a multisig smart contract, possibly with a time-delayed challenge period
            ///       - the zero address, if you like performing without a safety net ;-)
            address public recoveryAddress;
        
            /// @notice Used to track whether or not this contract instance has been initialized. This
            ///  is necessary since it is common for this wallet smart contract to be used as the "library
            ///  code" for an clone contract. See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md
            ///  for more information about clone contracts.
            bool public initialized;
            
            /// @notice Used to decorate methods that can only be called directly by the recovery address.
            modifier onlyRecoveryAddress() {
                require(msg.sender == recoveryAddress, "sender must be recovery address");
                _;
            }
        
            /// @notice Used to decorate the `init` function so this can only be called one time. Necessary
            ///  since this contract will often be used as a "clone". (See above.)
            modifier onlyOnce() {
                require(!initialized, "must not already be initialized");
                initialized = true;
                _;
            }
            
            /// @notice Used to decorate methods that can only be called indirectly via an `invoke()` method.
            ///  In practice, it means that those methods can only be called by a signer/cosigner
            ///  pair that is currently authorized. Theoretically, we could factor out the
            ///  signer/cosigner verification code and use it explicitly in this modifier, but that
            ///  would either result in duplicated code, or additional overhead in the invoke()
            ///  calls (due to the stack manipulation for calling into the shared verification function).
            ///  Doing it this way makes calling the administration functions more expensive (since they
            ///  go through a explict call() instead of just branching within the contract), but it
            ///  makes invoke() more efficient. We assume that invoke() will be used much, much more often
            ///  than any of the administration functions.
            modifier onlyInvoked() {
                require(msg.sender == address(this), "must be called from `invoke()`");
                _;
            }
            
            /// @notice Emitted when an authorized address is added, removed, or modified. When an
            ///  authorized address is removed ("deauthorized"), cosigner will be address(0) in
            ///  this event.
            ///  
            ///  NOTE: When emergencyRecovery() is called, all existing addresses are deauthorized
            ///  WITHOUT Authorized(addr, 0) being emitted. If you are keeping an off-chain mirror of
            ///  authorized addresses, you must also watch for EmergencyRecovery events.
            /// @dev hash is 0xf5a7f4fb8a92356e8c8c4ae7ac3589908381450500a7e2fd08c95600021ee889
            /// @param authorizedAddress the address to authorize or unauthorize
            /// @param cosigner the 2-of-2 signatory (optional).
            event Authorized(address authorizedAddress, uint256 cosigner);
            
            /// @notice Emitted when an emergency recovery has been performed. If this event is fired,
            ///  ALL previously authorized addresses have been deauthorized and the only authorized
            ///  address is the authorizedAddress indicated in this event.
            /// @dev hash is 0xe12d0bbeb1d06d7a728031056557140afac35616f594ef4be227b5b172a604b5
            /// @param authorizedAddress the new authorized address
            /// @param cosigner the cosigning address for `authorizedAddress`
            event EmergencyRecovery(address authorizedAddress, uint256 cosigner);
        
            /// @notice Emitted when the recovery address changes. Either (but not both) of the
            ///  parameters may be zero.
            /// @dev hash is 0x568ab3dedd6121f0385e007e641e74e1f49d0fa69cab2957b0b07c4c7de5abb6
            /// @param previousRecoveryAddress the previous recovery address
            /// @param newRecoveryAddress the new recovery address
            event RecoveryAddressChanged(address previousRecoveryAddress, address newRecoveryAddress);
        
            /// @dev Emitted when this contract receives a non-zero amount ether via the fallback function
            ///  (i.e. This event is not fired if the contract receives ether as part of a method invocation)
            /// @param from the address which sent you ether
            /// @param value the amount of ether sent
            event Received(address from, uint value);
        
            /// @notice Emitted whenever a transaction is processed sucessfully from this wallet. Includes
            ///  both simple send ether transactions, as well as other smart contract invocations.
            /// @dev hash is 0x101214446435ebbb29893f3348e3aae5ea070b63037a3df346d09d3396a34aee
            /// @param hash The hash of the entire operation set. 0 is returned when emitted from `invoke0()`.
            /// @param result A bitfield of the results of the operations. A bit of 0 means success, and 1 means failure.
            /// @param numOperations A count of the number of operations processed
            event InvocationSuccess(
                bytes32 hash,
                uint256 result,
                uint256 numOperations
            );
        
            /// @notice The shared initialization code used to setup the contract state regardless of whether or
            ///  not the clone pattern is being used.
            /// @param _authorizedAddress the initial authorized address, must not be zero!
            /// @param _cosigner the initial cosigning address for `_authorizedAddress`, can be equal to `_authorizedAddress`
            /// @param _recoveryAddress the initial recovery address for the wallet, can be address(0)
            function init(address _authorizedAddress, uint256 _cosigner, address _recoveryAddress) public onlyOnce {
                require(_authorizedAddress != _recoveryAddress, "Do not use the recovery address as an authorized address.");
                require(address(_cosigner) != _recoveryAddress, "Do not use the recovery address as a cosigner.");
                require(_authorizedAddress != address(0), "Authorized addresses must not be zero.");
                require(address(_cosigner) != address(0), "Initial cosigner must not be zero.");
                
                recoveryAddress = _recoveryAddress;
                // set initial authorization value
                authVersion = AUTH_VERSION_INCREMENTOR;
                // add initial authorized address
                authorizations[authVersion + uint256(_authorizedAddress)] = _cosigner;
                
                emit Authorized(_authorizedAddress, _cosigner);
            }
        
            /// @notice The fallback function, invoked whenever we receive a transaction that doesn't call any of our
            ///  named functions. In particular, this method is called when we are the target of a simple send transaction
            ///  or when someone tries to call a method that we don't implement. We assume that a "correct" invocation of
            ///  this method only occurs when someone is trying to transfer ether to this wallet, in which case and the
            ///  `msg.data.length` will be 0.
            ///
            ///  NOTE: Some smart contracts send 0 eth as part of a more complex
            ///  operation (-cough- CryptoKitties -cough-) ; ideally, we'd `require(msg.value > 0)` here, but to work
            ///  with those kinds of smart contracts, we accept zero sends and just skip logging in that case.
            function() external payable {
                require(msg.data.length == 0, "Invalid transaction.");
                if (msg.value > 0) {
                    emit Received(msg.sender, msg.value);
                }
            }
            
            /// @notice Configures an authorizable address. Can be used in four ways:
            ///   - Add a new signer/cosigner pair (cosigner must be non-zero)
            ///   - Set or change the cosigner for an existing signer (if authorizedAddress != cosigner)
            ///   - Remove the cosigning requirement for a signer (if authorizedAddress == cosigner)
            ///   - Remove a signer (if cosigner == address(0))
            /// @dev Must be called through `invoke()`
            /// @param _authorizedAddress the address to configure authorization
            /// @param _cosigner the corresponding cosigning address
            function setAuthorized(address _authorizedAddress, uint256 _cosigner) external onlyInvoked {
                // TODO: Allowing a signer to remove itself is actually pretty terrible; it could result in the user
                //  removing their only available authorized key. Unfortunately, due to how the invocation forwarding
                //  works, we don't actually _know_ which signer was used to call this method, so there's no easy way
                //  to prevent this.
                
                // TODO: Allowing the backup key to be set as an authorized address bypasses the recovery mechanisms.
                //  Dapper can prevent this with offchain logic and the cosigner, but it would be nice to have 
                //  this enforced by the smart contract logic itself.
                
                require(_authorizedAddress != address(0), "Authorized addresses must not be zero.");
                require(_authorizedAddress != recoveryAddress, "Do not use the recovery address as an authorized address.");
                require(address(_cosigner) == address(0) || address(_cosigner) != recoveryAddress, "Do not use the recovery address as a cosigner.");
         
                authorizations[authVersion + uint256(_authorizedAddress)] = _cosigner;
                emit Authorized(_authorizedAddress, _cosigner);
            }
            
            /// @notice Performs an emergency recovery operation, removing all existing authorizations and setting
            ///  a sole new authorized address with optional cosigner. THIS IS A SCORCHED EARTH SOLUTION, and great
            ///  care should be taken to ensure that this method is never called unless it is a last resort. See the
            ///  comments above about the proper kinds of addresses to use as the recoveryAddress to ensure this method
            ///  is not trivially abused.
            /// @param _authorizedAddress the new and sole authorized address
            /// @param _cosigner the corresponding cosigner address, can be equal to _authorizedAddress
            function emergencyRecovery(address _authorizedAddress, uint256 _cosigner) external onlyRecoveryAddress {
                require(_authorizedAddress != address(0), "Authorized addresses must not be zero.");
                require(_authorizedAddress != recoveryAddress, "Do not use the recovery address as an authorized address.");
                require(address(_cosigner) != address(0), "The cosigner must not be zero.");
        
                // Incrementing the authVersion number effectively erases the authorizations mapping. See the comments
                // on the authorizations variable (above) for more information.
                authVersion += AUTH_VERSION_INCREMENTOR;
        
                // Store the new signer/cosigner pair as the only remaining authorized address
                authorizations[authVersion + uint256(_authorizedAddress)] = _cosigner;
                emit EmergencyRecovery(_authorizedAddress, _cosigner);
            }
        
            /// @notice Sets the recovery address, which can be zero (indicating that no recovery is possible)
            ///  Can be updated by any authorized address. This address should be set with GREAT CARE. See the
            ///  comments above about the proper kinds of addresses to use as the recoveryAddress to ensure this
            ///  mechanism is not trivially abused.
            /// @dev Must be called through `invoke()`
            /// @param _recoveryAddress the new recovery address
            function setRecoveryAddress(address _recoveryAddress) external onlyInvoked {
                require(
                    address(authorizations[authVersion + uint256(_recoveryAddress)]) == address(0),
                    "Do not use an authorized address as the recovery address."
                );
         
                address previous = recoveryAddress;
                recoveryAddress = _recoveryAddress;
        
                emit RecoveryAddressChanged(previous, recoveryAddress);
            }
        
            /// @notice Allows ANY caller to recover gas by way of deleting old authorization keys after
            ///  a recovery operation. Anyone can call this method to delete the old unused storage and
            ///  get themselves a bit of gas refund in the bargin.
            /// @dev keys must be known to caller or else nothing is refunded
            /// @param _version the version of the mapping which you want to delete (unshifted)
            /// @param _keys the authorization keys to delete 
            function recoverGas(uint256 _version, address[] _keys) external {
                // TODO: should this be 0xffffffffffffffffffffffff ?
                require(_version > 0 && _version < 0xffffffff, "Invalid version number.");
                
                uint256 shiftedVersion = _version << 160;
        
                require(shiftedVersion < authVersion, "You can only recover gas from expired authVersions.");
        
                for (uint256 i = 0; i < _keys.length; ++i) {
                    delete(authorizations[shiftedVersion + uint256(_keys[i])]);
                }
            }
        
            /// @notice Should return whether the signature provided is valid for the provided data
            ///  See https://github.com/ethereum/EIPs/issues/1271
            /// @dev This function meets the following conditions as per the EIP:
            ///  MUST return the bytes4 magic value `0x1626ba7e` when function passes.
            ///  MUST NOT modify state (using `STATICCALL` for solc < 0.5, `view` modifier for solc > 0.5)
            ///  MUST allow external calls
            /// @param hash A 32 byte hash of the signed data.  The actual hash that is hashed however is the
            ///  the following tightly packed arguments: `0x19,0x0,wallet_address,hash`
            /// @param _signature Signature byte array associated with `_data`
            /// @return Magic value `0x1626ba7e` upon success, 0 otherwise.
            function isValidSignature(bytes32 hash, bytes _signature) external view returns (bytes4) {
                
                // We 'hash the hash' for the following reasons:
                // 1. `hash` is not the hash of an Ethereum transaction
                // 2. signature must target this wallet to avoid replaying the signature for another wallet
                // with the same key
                // 3. Gnosis does something similar: 
                // https://github.com/gnosis/safe-contracts/blob/102e632d051650b7c4b0a822123f449beaf95aed/contracts/GnosisSafe.sol
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    hash));
        
                bytes32[2] memory r;
                bytes32[2] memory s;
                uint8[2] memory v;
                address signer;
                address cosigner;
        
                // extract 1 or 2 signatures depending on length
                if (_signature.length == 65) {
                    (r[0], s[0], v[0]) = _signature.extractSignature(0);
                    signer = ecrecover(operationHash, v[0], r[0], s[0]);
                    cosigner = signer;
                } else if (_signature.length == 130) {
                    (r[0], s[0], v[0]) = _signature.extractSignature(0);
                    (r[1], s[1], v[1]) = _signature.extractSignature(65);
                    signer = ecrecover(operationHash, v[0], r[0], s[0]);
                    cosigner = ecrecover(operationHash, v[1], r[1], s[1]);
                } else {
                    return 0;
                }
                    
                // check for valid signature
                if (signer == address(0)) {
                    return 0;
                }
        
                // check for valid signature
                if (cosigner == address(0)) {
                    return 0;
                }
        
                // check to see if this is an authorized key
                if (address(authorizations[authVersion + uint256(signer)]) != cosigner) {
                    return 0;
                }
        
                return ERC1271_VALIDSIGNATURE;
            }
        
            /// @notice Query if a contract implements an interface
            /// @param interfaceID The interface identifier, as specified in ERC-165
            /// @dev Interface identification is specified in ERC-165. This function
            ///  uses less than 30,000 gas.
            /// @return `true` if the contract implements `interfaceID` and
            ///  `interfaceID` is not 0xffffffff, `false` otherwise
            function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
                // I am not sure why the linter is complaining about the whitespace
                return
                    interfaceID == this.supportsInterface.selector || // ERC165
                    interfaceID == ERC721_RECEIVED_FINAL || // ERC721 Final
                    interfaceID == ERC721_RECEIVED_DRAFT || // ERC721 Draft
                    interfaceID == ERC223_ID || // ERC223
                    interfaceID == ERC1271_VALIDSIGNATURE; // ERC1271
            }
        
            /// @notice A version of `invoke()` that has no explicit signatures, and uses msg.sender
            ///  as both the signer and cosigner. Will only succeed if `msg.sender` is an authorized
            ///  signer for this wallet, with no cosigner, saving transaction size and gas in that case.
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke0(bytes data) external {
                // The nonce doesn't need to be incremented for transactions that don't include explicit signatures;
                // the built-in nonce of the native ethereum transaction will protect against replay attacks, and we
                // can save the gas that would be spent updating the nonce variable
        
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner)
                require(address(authorizations[authVersion + uint256(msg.sender)]) == msg.sender, "Invalid authorization.");
        
                internalInvoke(0, data);
            }
        
            /// @notice A version of `invoke()` that has one explicit signature which is used to derive the authorized
            ///  address. Uses `msg.sender` as the cosigner.
            /// @param v the v value for the signature; see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
            /// @param r the r value for the signature
            /// @param s the s value for the signature
            /// @param nonce the nonce value for the signature
            /// @param authorizedAddress the address of the authorization key; this is used here so that cosigner signatures are interchangeable
            ///  between this function and `invoke2()`
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke1CosignerSends(uint8 v, bytes32 r, bytes32 s, uint256 nonce, address authorizedAddress, bytes data) external {
                // check signature version
                require(v == 27 || v == 28, "Invalid signature version.");
        
                // calculate hash
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    nonce,
                    authorizedAddress,
                    data));
         
                // recover signer
                address signer = ecrecover(operationHash, v, r, s);
        
                // check for valid signature
                require(signer != address(0), "Invalid signature.");
        
                // check nonce
                require(nonce == nonces[signer], "must use correct nonce");
        
                // check signer
                require(signer == authorizedAddress, "authorized addresses must be equal");
        
                // Get cosigner
                address requiredCosigner = address(authorizations[authVersion + uint256(signer)]);
                
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
                // if the actual cosigner matches the required cosigner.
                require(requiredCosigner == signer || requiredCosigner == msg.sender, "Invalid authorization.");
        
                // increment nonce to prevent replay attacks
                nonces[signer] = nonce + 1;
        
                // call internal function
                internalInvoke(operationHash, data);
            }
        
            /// @notice A version of `invoke()` that has one explicit signature which is used to derive the cosigning
            ///  address. Uses `msg.sender` as the authorized address.
            /// @param v the v value for the signature; see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
            /// @param r the r value for the signature
            /// @param s the s value for the signature
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke1SignerSends(uint8 v, bytes32 r, bytes32 s, bytes data) external {
                // check signature version
                // `ecrecover` will infact return 0 if given invalid
                // so perhaps this check is redundant
                require(v == 27 || v == 28, "Invalid signature version.");
                
                uint256 nonce = nonces[msg.sender];
        
                // calculate hash
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    nonce,
                    msg.sender,
                    data));
         
                // recover cosigner
                address cosigner = ecrecover(operationHash, v, r, s);
                
                // check for valid signature
                require(cosigner != address(0), "Invalid signature.");
        
                // Get required cosigner
                address requiredCosigner = address(authorizations[authVersion + uint256(msg.sender)]);
                
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
                // if the actual cosigner matches the required cosigner.
                require(requiredCosigner == cosigner || requiredCosigner == msg.sender, "Invalid authorization.");
        
                // increment nonce to prevent replay attacks
                nonces[msg.sender] = nonce + 1;
         
                internalInvoke(operationHash, data);
            }
        
            /// @notice A version of `invoke()` that has two explicit signatures, the first is used to derive the authorized
            ///  address, the second to derive the cosigner. The value of `msg.sender` is ignored.
            /// @param v the v values for the signatures
            /// @param r the r values for the signatures
            /// @param s the s values for the signatures
            /// @param nonce the nonce value for the signature
            /// @param authorizedAddress the address of the signer; forces the signature to be unique and tied to the signers nonce 
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke2(uint8[2] v, bytes32[2] r, bytes32[2] s, uint256 nonce, address authorizedAddress, bytes data) external {
                // check signature versions
                // `ecrecover` will infact return 0 if given invalid
                // so perhaps these checks are redundant
                require(v[0] == 27 || v[0] == 28, "invalid signature version v[0]");
                require(v[1] == 27 || v[1] == 28, "invalid signature version v[1]");
         
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    nonce,
                    authorizedAddress,
                    data));
         
                // recover signer and cosigner
                address signer = ecrecover(operationHash, v[0], r[0], s[0]);
                address cosigner = ecrecover(operationHash, v[1], r[1], s[1]);
        
                // check for valid signatures
                require(signer != address(0), "Invalid signature for signer.");
                require(cosigner != address(0), "Invalid signature for cosigner.");
        
                // check signer address
                require(signer == authorizedAddress, "authorized addresses must be equal");
        
                // check nonces
                require(nonce == nonces[signer], "must use correct nonce for signer");
        
                // Get Mapping
                address requiredCosigner = address(authorizations[authVersion + uint256(signer)]);
                
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
                // if the actual cosigner matches the required cosigner.
                require(requiredCosigner == signer || requiredCosigner == cosigner, "Invalid authorization.");
        
                // increment nonce to prevent replay attacks
                nonces[signer]++;
        
                internalInvoke(operationHash, data);
            }
        
            /// @dev Internal invoke call, 
            /// @param operationHash The hash of the operation
            /// @param data The data to send to the `call()` operation
            ///  The data is prefixed with a global 1 byte revert flag
            ///  If revert is 1, then any revert from a `call()` operation is rethrown.
            ///  Otherwise, the error is recorded in the `result` field of the `InvocationSuccess` event.
            ///  Immediately following the revert byte (no padding), the data format is then is a series
            ///  of 1 or more tightly packed tuples:
            ///  `<target(20),amount(32),datalength(32),data>`
            ///  If `datalength == 0`, the data field must be omitted
            function internalInvoke(bytes32 operationHash, bytes data) internal {
                // keep track of the number of operations processed
                uint256 numOps;
                // keep track of the result of each operation as a bit
                uint256 result;
        
                // We need to store a reference to this string as a variable so we can use it as an argument to
                // the revert call from assembly.
                string memory invalidLengthMessage = "Data field too short";
                string memory callFailed = "Call failed";
        
                // At an absolute minimum, the data field must be at least 85 bytes
                // <revert(1), to_address(20), value(32), data_length(32)>
                require(data.length >= 85, invalidLengthMessage);
        
                // Forward the call onto its actual target. Note that the target address can be `self` here, which is
                // actually the required flow for modifying the configuration of the authorized keys and recovery address.
                //
                // The assembly code below loads data directly from memory, so the enclosing function must be marked `internal`
                assembly {
                    // A cursor pointing to the revert flag, starts after the length field of the data object
                    let memPtr := add(data, 32)
        
                    // The revert flag is the leftmost byte from memPtr
                    let revertFlag := byte(0, mload(memPtr))
        
                    // A pointer to the end of the data object
                    let endPtr := add(memPtr, mload(data))
        
                    // Now, memPtr is a cursor pointing to the begining of the current sub-operation
                    memPtr := add(memPtr, 1)
        
                    // Loop through data, parsing out the various sub-operations
                    for { } lt(memPtr, endPtr) { } {
                        // Load the length of the call data of the current operation
                        // 52 = to(20) + value(32)
                        let len := mload(add(memPtr, 52))
                        
                        // Compute a pointer to the end of the current operation
                        // 84 = to(20) + value(32) + size(32)
                        let opEnd := add(len, add(memPtr, 84))
        
                        // Bail if the current operation's data overruns the end of the enclosing data buffer
                        // NOTE: Comment out this bit of code and uncomment the next section if you want
                        // the solidity-coverage tool to work.
                        // See https://github.com/sc-forks/solidity-coverage/issues/287
                        if gt(opEnd, endPtr) {
                            // The computed end of this operation goes past the end of the data buffer. Not good!
                            revert(add(invalidLengthMessage, 32), mload(invalidLengthMessage))
                        }
                        // NOTE: Code that is compatible with solidity-coverage
                        // switch gt(opEnd, endPtr)
                        // case 1 {
                        //     revert(add(invalidLengthMessage, 32), mload(invalidLengthMessage))
                        // }
        
                        // This line of code packs in a lot of functionality!
                        //  - load the target address from memPtr, the address is only 20-bytes but mload always grabs 32-bytes,
                        //    so we have to divide the result by 2^96 to effectively right-shift by 12 bytes.
                        //  - load the value field, stored at memPtr+20
                        //  - pass a pointer to the call data, stored at memPtr+84
                        //  - use the previously loaded len field as the size of the call data
                        //  - make the call (passing all remaining gas to the child call)
                        //  - check the result (0 == reverted)
                        if eq(0, call(gas, div(mload(memPtr), exp(2, 96)), mload(add(memPtr, 20)), add(memPtr, 84), len, 0, 0)) {
                            
                            switch revertFlag
                            case 1 {
                                revert(add(callFailed, 32), mload(callFailed))
                            }
                            default {
                                // mark this operation as failed
                                // create the appropriate bit, 'or' with previous
                                result := or(result, exp(2, numOps))
                            }
                        }
        
                        // increment our counter
                        numOps := add(numOps, 1)
                     
                        // Update mem pointer to point to the next sub-operation
                        memPtr := opEnd
                    }
                }
        
                // emit single event upon success
                emit InvocationSuccess(operationHash, result, numOps);
            }
        }
        
        // File: contracts/Wallet/CloneableWallet.sol
        
        pragma solidity ^0.4.24;
        
        
        
        /// @title Cloneable Wallet
        /// @notice This contract represents a complete but non working wallet.  
        ///  It is meant to be deployed and serve as the contract that you clone
        ///  in an EIP 1167 clone setup.
        /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md
        /// @dev Currently, we are seeing approximatley 933 gas overhead for using
        ///  the clone wallet; use `FullWallet` if you think users will overtake
        ///  the transaction threshold over the lifetime of the wallet.
        contract CloneableWallet is CoreWallet {
        
            /// @dev An empty constructor that deploys a NON-FUNCTIONAL version
            ///  of `CoreWallet`
            constructor () public {
                initialized = true;
            }
        }

        File 2 of 4: KittyCore
        pragma solidity ^0.4.11;
        
        
        /**
         * @title Ownable
         * @dev The Ownable contract has an owner address, and provides basic authorization control
         * functions, this simplifies the implementation of "user permissions".
         */
        contract Ownable {
          address public owner;
        
        
          /**
           * @dev The Ownable constructor sets the original `owner` of the contract to the sender
           * account.
           */
          function Ownable() {
            owner = msg.sender;
          }
        
        
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
            require(msg.sender == owner);
            _;
          }
        
        
          /**
           * @dev Allows the current owner to transfer control of the contract to a newOwner.
           * @param newOwner The address to transfer ownership to.
           */
          function transferOwnership(address newOwner) onlyOwner {
            if (newOwner != address(0)) {
              owner = newOwner;
            }
          }
        
        }
        
        
        
        /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
        /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
        contract ERC721 {
            // Required methods
            function totalSupply() public view returns (uint256 total);
            function balanceOf(address _owner) public view returns (uint256 balance);
            function ownerOf(uint256 _tokenId) external view returns (address owner);
            function approve(address _to, uint256 _tokenId) external;
            function transfer(address _to, uint256 _tokenId) external;
            function transferFrom(address _from, address _to, uint256 _tokenId) external;
        
            // Events
            event Transfer(address from, address to, uint256 tokenId);
            event Approval(address owner, address approved, uint256 tokenId);
        
            // Optional
            // function name() public view returns (string name);
            // function symbol() public view returns (string symbol);
            // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
            // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
        
            // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
            function supportsInterface(bytes4 _interfaceID) external view returns (bool);
        }
        
        
        // // Auction wrapper functions
        
        
        // Auction wrapper functions
        
        
        
        
        
        
        
        /// @title SEKRETOOOO
        contract GeneScienceInterface {
            /// @dev simply a boolean to indicate this is the contract we expect to be
            function isGeneScience() public pure returns (bool);
        
            /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
            /// @param genes1 genes of mom
            /// @param genes2 genes of sire
            /// @return the genes that are supposed to be passed down the child
            function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
        }
        
        
        
        
        
        
        
        /// @title A facet of KittyCore that manages special access privileges.
        /// @author Axiom Zen (https://www.axiomzen.co)
        /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
        contract KittyAccessControl {
            // This facet controls access control for CryptoKitties. There are four roles managed here:
            //
            //     - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
            //         contracts. It is also the only role that can unpause the smart contract. It is initially
            //         set to the address that created the smart contract in the KittyCore constructor.
            //
            //     - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts.
            //
            //     - The COO: The COO can release gen0 kitties to auction, and mint promo cats.
            //
            // It should be noted that these roles are distinct without overlap in their access abilities, the
            // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
            // address to any role, the CEO address itself doesn't have the ability to act in those roles. This
            // restriction is intentional so that we aren't tempted to use the CEO address frequently out of
            // convenience. The less we use an address, the less likely it is that we somehow compromise the
            // account.
        
            /// @dev Emited when contract is upgraded - See README.md for updgrade plan
            event ContractUpgrade(address newContract);
        
            // The addresses of the accounts (or contracts) that can execute actions within each roles.
            address public ceoAddress;
            address public cfoAddress;
            address public cooAddress;
        
            // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
            bool public paused = false;
        
            /// @dev Access modifier for CEO-only functionality
            modifier onlyCEO() {
                require(msg.sender == ceoAddress);
                _;
            }
        
            /// @dev Access modifier for CFO-only functionality
            modifier onlyCFO() {
                require(msg.sender == cfoAddress);
                _;
            }
        
            /// @dev Access modifier for COO-only functionality
            modifier onlyCOO() {
                require(msg.sender == cooAddress);
                _;
            }
        
            modifier onlyCLevel() {
                require(
                    msg.sender == cooAddress ||
                    msg.sender == ceoAddress ||
                    msg.sender == cfoAddress
                );
                _;
            }
        
            /// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
            /// @param _newCEO The address of the new CEO
            function setCEO(address _newCEO) external onlyCEO {
                require(_newCEO != address(0));
        
                ceoAddress = _newCEO;
            }
        
            /// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
            /// @param _newCFO The address of the new CFO
            function setCFO(address _newCFO) external onlyCEO {
                require(_newCFO != address(0));
        
                cfoAddress = _newCFO;
            }
        
            /// @dev Assigns a new address to act as the COO. Only available to the current CEO.
            /// @param _newCOO The address of the new COO
            function setCOO(address _newCOO) external onlyCEO {
                require(_newCOO != address(0));
        
                cooAddress = _newCOO;
            }
        
            /*** Pausable functionality adapted from OpenZeppelin ***/
        
            /// @dev Modifier to allow actions only when the contract IS NOT paused
            modifier whenNotPaused() {
                require(!paused);
                _;
            }
        
            /// @dev Modifier to allow actions only when the contract IS paused
            modifier whenPaused {
                require(paused);
                _;
            }
        
            /// @dev Called by any "C-level" role to pause the contract. Used only when
            ///  a bug or exploit is detected and we need to limit damage.
            function pause() external onlyCLevel whenNotPaused {
                paused = true;
            }
        
            /// @dev Unpauses the smart contract. Can only be called by the CEO, since
            ///  one reason we may pause the contract is when CFO or COO accounts are
            ///  compromised.
            /// @notice This is public rather than external so it can be called by
            ///  derived contracts.
            function unpause() public onlyCEO whenPaused {
                // can't unpause if contract was upgraded
                paused = false;
            }
        }
        
        
        
        
        /// @title Base contract for CryptoKitties. Holds all common structs, events and base variables.
        /// @author Axiom Zen (https://www.axiomzen.co)
        /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
        contract KittyBase is KittyAccessControl {
            /*** EVENTS ***/
        
            /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously
            ///  includes any time a cat is created through the giveBirth method, but it is also called
            ///  when a new gen0 cat is created.
            event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes);
        
            /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten
            ///  ownership is assigned, including births.
            event Transfer(address from, address to, uint256 tokenId);
        
            /*** DATA TYPES ***/
        
            /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy
            ///  of this structure, so great care was taken to ensure that it fits neatly into
            ///  exactly two 256-bit words. Note that the order of the members in this structure
            ///  is important because of the byte-packing rules used by Ethereum.
            ///  Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
            struct Kitty {
                // The Kitty's genetic code is packed into these 256-bits, the format is
                // sooper-sekret! A cat's genes never change.
                uint256 genes;
        
                // The timestamp from the block when this cat came into existence.
                uint64 birthTime;
        
                // The minimum timestamp after which this cat can engage in breeding
                // activities again. This same timestamp is used for the pregnancy
                // timer (for matrons) as well as the siring cooldown.
                uint64 cooldownEndBlock;
        
                // The ID of the parents of this kitty, set to 0 for gen0 cats.
                // Note that using 32-bit unsigned integers limits us to a "mere"
                // 4 billion cats. This number might seem small until you realize
                // that Ethereum currently has a limit of about 500 million
                // transactions per year! So, this definitely won't be a problem
                // for several years (even as Ethereum learns to scale).
                uint32 matronId;
                uint32 sireId;
        
                // Set to the ID of the sire cat for matrons that are pregnant,
                // zero otherwise. A non-zero value here is how we know a cat
                // is pregnant. Used to retrieve the genetic material for the new
                // kitten when the birth transpires.
                uint32 siringWithId;
        
                // Set to the index in the cooldown array (see below) that represents
                // the current cooldown duration for this Kitty. This starts at zero
                // for gen0 cats, and is initialized to floor(generation/2) for others.
                // Incremented by one for each successful breeding action, regardless
                // of whether this cat is acting as matron or sire.
                uint16 cooldownIndex;
        
                // The "generation number" of this cat. Cats minted by the CK contract
                // for sale are called "gen0" and have a generation number of 0. The
                // generation number of all other cats is the larger of the two generation
                // numbers of their parents, plus one.
                // (i.e. max(matron.generation, sire.generation) + 1)
                uint16 generation;
            }
        
            /*** CONSTANTS ***/
        
            /// @dev A lookup table indicating the cooldown duration after any successful
            ///  breeding action, called "pregnancy time" for matrons and "siring cooldown"
            ///  for sires. Designed such that the cooldown roughly doubles each time a cat
            ///  is bred, encouraging owners not to just keep breeding the same cat over
            ///  and over again. Caps out at one week (a cat can breed an unbounded number
            ///  of times, and the maximum cooldown is always seven days).
            uint32[14] public cooldowns = [
                uint32(1 minutes),
                uint32(2 minutes),
                uint32(5 minutes),
                uint32(10 minutes),
                uint32(30 minutes),
                uint32(1 hours),
                uint32(2 hours),
                uint32(4 hours),
                uint32(8 hours),
                uint32(16 hours),
                uint32(1 days),
                uint32(2 days),
                uint32(4 days),
                uint32(7 days)
            ];
        
            // An approximation of currently how many seconds are in between blocks.
            uint256 public secondsPerBlock = 15;
        
            /*** STORAGE ***/
        
            /// @dev An array containing the Kitty struct for all Kitties in existence. The ID
            ///  of each cat is actually an index into this array. Note that ID 0 is a negacat,
            ///  the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre
            ///  creature that is both matron and sire... to itself! Has an invalid genetic code.
            ///  In other words, cat ID 0 is invalid... ;-)
            Kitty[] kitties;
        
            /// @dev A mapping from cat IDs to the address that owns them. All cats have
            ///  some valid owner address, even gen0 cats are created with a non-zero owner.
            mapping (uint256 => address) public kittyIndexToOwner;
        
            // @dev A mapping from owner address to count of tokens that address owns.
            //  Used internally inside balanceOf() to resolve ownership count.
            mapping (address => uint256) ownershipTokenCount;
        
            /// @dev A mapping from KittyIDs to an address that has been approved to call
            ///  transferFrom(). Each Kitty can only have one approved address for transfer
            ///  at any time. A zero value means no approval is outstanding.
            mapping (uint256 => address) public kittyIndexToApproved;
        
            /// @dev A mapping from KittyIDs to an address that has been approved to use
            ///  this Kitty for siring via breedWith(). Each Kitty can only have one approved
            ///  address for siring at any time. A zero value means no approval is outstanding.
            mapping (uint256 => address) public sireAllowedToAddress;
        
            /// @dev The address of the ClockAuction contract that handles sales of Kitties. This
            ///  same contract handles both peer-to-peer sales as well as the gen0 sales which are
            ///  initiated every 15 minutes.
            SaleClockAuction public saleAuction;
        
            /// @dev The address of a custom ClockAuction subclassed contract that handles siring
            ///  auctions. Needs to be separate from saleAuction because the actions taken on success
            ///  after a sales and siring auction are quite different.
            SiringClockAuction public siringAuction;
        
            /// @dev Assigns ownership of a specific Kitty to an address.
            function _transfer(address _from, address _to, uint256 _tokenId) internal {
                // Since the number of kittens is capped to 2^32 we can't overflow this
                ownershipTokenCount[_to]++;
                // transfer ownership
                kittyIndexToOwner[_tokenId] = _to;
                // When creating new kittens _from is 0x0, but we can't account that address.
                if (_from != address(0)) {
                    ownershipTokenCount[_from]--;
                    // once the kitten is transferred also clear sire allowances
                    delete sireAllowedToAddress[_tokenId];
                    // clear any previously approved ownership exchange
                    delete kittyIndexToApproved[_tokenId];
                }
                // Emit the transfer event.
                Transfer(_from, _to, _tokenId);
            }
        
            /// @dev An internal method that creates a new kitty and stores it. This
            ///  method doesn't do any checking and should only be called when the
            ///  input data is known to be valid. Will generate both a Birth event
            ///  and a Transfer event.
            /// @param _matronId The kitty ID of the matron of this cat (zero for gen0)
            /// @param _sireId The kitty ID of the sire of this cat (zero for gen0)
            /// @param _generation The generation number of this cat, must be computed by caller.
            /// @param _genes The kitty's genetic code.
            /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0)
            function _createKitty(
                uint256 _matronId,
                uint256 _sireId,
                uint256 _generation,
                uint256 _genes,
                address _owner
            )
                internal
                returns (uint)
            {
                // These requires are not strictly necessary, our calling code should make
                // sure that these conditions are never broken. However! _createKitty() is already
                // an expensive call (for storage), and it doesn't hurt to be especially careful
                // to ensure our data structures are always valid.
                require(_matronId == uint256(uint32(_matronId)));
                require(_sireId == uint256(uint32(_sireId)));
                require(_generation == uint256(uint16(_generation)));
        
                // New kitty starts with the same cooldown as parent gen/2
                uint16 cooldownIndex = uint16(_generation / 2);
                if (cooldownIndex > 13) {
                    cooldownIndex = 13;
                }
        
                Kitty memory _kitty = Kitty({
                    genes: _genes,
                    birthTime: uint64(now),
                    cooldownEndBlock: 0,
                    matronId: uint32(_matronId),
                    sireId: uint32(_sireId),
                    siringWithId: 0,
                    cooldownIndex: cooldownIndex,
                    generation: uint16(_generation)
                });
                uint256 newKittenId = kitties.push(_kitty) - 1;
        
                // It's probably never going to happen, 4 billion cats is A LOT, but
                // let's just be 100% sure we never let this happen.
                require(newKittenId == uint256(uint32(newKittenId)));
        
                // emit the birth event
                Birth(
                    _owner,
                    newKittenId,
                    uint256(_kitty.matronId),
                    uint256(_kitty.sireId),
                    _kitty.genes
                );
        
                // This will assign ownership, and also emit the Transfer event as
                // per ERC721 draft
                _transfer(0, _owner, newKittenId);
        
                return newKittenId;
            }
        
            // Any C-level can fix how many seconds per blocks are currently observed.
            function setSecondsPerBlock(uint256 secs) external onlyCLevel {
                require(secs < cooldowns[0]);
                secondsPerBlock = secs;
            }
        }
        
        
        
        
        
        /// @title The external contract that is responsible for generating metadata for the kitties,
        ///  it has one function that will return the data as bytes.
        contract ERC721Metadata {
            /// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
            function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
                if (_tokenId == 1) {
                    buffer[0] = "Hello World! :D";
                    count = 15;
                } else if (_tokenId == 2) {
                    buffer[0] = "I would definitely choose a medi";
                    buffer[1] = "um length string.";
                    count = 49;
                } else if (_tokenId == 3) {
                    buffer[0] = "Lorem ipsum dolor sit amet, mi e";
                    buffer[1] = "st accumsan dapibus augue lorem,";
                    buffer[2] = " tristique vestibulum id, libero";
                    buffer[3] = " suscipit varius sapien aliquam.";
                    count = 128;
                }
            }
        }
        
        
        /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant.
        /// @author Axiom Zen (https://www.axiomzen.co)
        /// @dev Ref: https://github.com/ethereum/EIPs/issues/721
        ///  See the KittyCore contract documentation to understand how the various contract facets are arranged.
        contract KittyOwnership is KittyBase, ERC721 {
        
            /// @notice Name and symbol of the non fungible token, as defined in ERC721.
            string public constant name = "CryptoKitties";
            string public constant symbol = "CK";
        
            // The contract that will return kitty metadata
            ERC721Metadata public erc721Metadata;
        
            bytes4 constant InterfaceSignature_ERC165 =
                bytes4(keccak256('supportsInterface(bytes4)'));
        
            bytes4 constant InterfaceSignature_ERC721 =
                bytes4(keccak256('name()')) ^
                bytes4(keccak256('symbol()')) ^
                bytes4(keccak256('totalSupply()')) ^
                bytes4(keccak256('balanceOf(address)')) ^
                bytes4(keccak256('ownerOf(uint256)')) ^
                bytes4(keccak256('approve(address,uint256)')) ^
                bytes4(keccak256('transfer(address,uint256)')) ^
                bytes4(keccak256('transferFrom(address,address,uint256)')) ^
                bytes4(keccak256('tokensOfOwner(address)')) ^
                bytes4(keccak256('tokenMetadata(uint256,string)'));
        
            /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
            ///  Returns true for any standardized interfaces implemented by this contract. We implement
            ///  ERC-165 (obviously!) and ERC-721.
            function supportsInterface(bytes4 _interfaceID) external view returns (bool)
            {
                // DEBUG ONLY
                //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
        
                return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
            }
        
            /// @dev Set the address of the sibling contract that tracks metadata.
            ///  CEO only.
            function setMetadataAddress(address _contractAddress) public onlyCEO {
                erc721Metadata = ERC721Metadata(_contractAddress);
            }
        
            // Internal utility functions: These functions all assume that their input arguments
            // are valid. We leave it to public methods to sanitize their inputs and follow
            // the required logic.
        
            /// @dev Checks if a given address is the current owner of a particular Kitty.
            /// @param _claimant the address we are validating against.
            /// @param _tokenId kitten id, only valid when > 0
            function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
                return kittyIndexToOwner[_tokenId] == _claimant;
            }
        
            /// @dev Checks if a given address currently has transferApproval for a particular Kitty.
            /// @param _claimant the address we are confirming kitten is approved for.
            /// @param _tokenId kitten id, only valid when > 0
            function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
                return kittyIndexToApproved[_tokenId] == _claimant;
            }
        
            /// @dev Marks an address as being approved for transferFrom(), overwriting any previous
            ///  approval. Setting _approved to address(0) clears all transfer approval.
            ///  NOTE: _approve() does NOT send the Approval event. This is intentional because
            ///  _approve() and transferFrom() are used together for putting Kitties on auction, and
            ///  there is no value in spamming the log with Approval events in that case.
            function _approve(uint256 _tokenId, address _approved) internal {
                kittyIndexToApproved[_tokenId] = _approved;
            }
        
            /// @notice Returns the number of Kitties owned by a specific address.
            /// @param _owner The owner address to check.
            /// @dev Required for ERC-721 compliance
            function balanceOf(address _owner) public view returns (uint256 count) {
                return ownershipTokenCount[_owner];
            }
        
            /// @notice Transfers a Kitty to another address. If transferring to a smart
            ///  contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
            ///  CryptoKitties specifically) or your Kitty may be lost forever. Seriously.
            /// @param _to The address of the recipient, can be a user or contract.
            /// @param _tokenId The ID of the Kitty to transfer.
            /// @dev Required for ERC-721 compliance.
            function transfer(
                address _to,
                uint256 _tokenId
            )
                external
                whenNotPaused
            {
                // Safety check to prevent against an unexpected 0x0 default.
                require(_to != address(0));
                // Disallow transfers to this contract to prevent accidental misuse.
                // The contract should never own any kitties (except very briefly
                // after a gen0 cat is created and before it goes on auction).
                require(_to != address(this));
                // Disallow transfers to the auction contracts to prevent accidental
                // misuse. Auction contracts should only take ownership of kitties
                // through the allow + transferFrom flow.
                require(_to != address(saleAuction));
                require(_to != address(siringAuction));
        
                // You can only send your own cat.
                require(_owns(msg.sender, _tokenId));
        
                // Reassign ownership, clear pending approvals, emit Transfer event.
                _transfer(msg.sender, _to, _tokenId);
            }
        
            /// @notice Grant another address the right to transfer a specific Kitty via
            ///  transferFrom(). This is the preferred flow for transfering NFTs to contracts.
            /// @param _to The address to be granted transfer approval. Pass address(0) to
            ///  clear all approvals.
            /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
            /// @dev Required for ERC-721 compliance.
            function approve(
                address _to,
                uint256 _tokenId
            )
                external
                whenNotPaused
            {
                // Only an owner can grant transfer approval.
                require(_owns(msg.sender, _tokenId));
        
                // Register the approval (replacing any previous approval).
                _approve(_tokenId, _to);
        
                // Emit approval event.
                Approval(msg.sender, _to, _tokenId);
            }
        
            /// @notice Transfer a Kitty owned by another address, for which the calling address
            ///  has previously been granted transfer approval by the owner.
            /// @param _from The address that owns the Kitty to be transfered.
            /// @param _to The address that should take ownership of the Kitty. Can be any address,
            ///  including the caller.
            /// @param _tokenId The ID of the Kitty to be transferred.
            /// @dev Required for ERC-721 compliance.
            function transferFrom(
                address _from,
                address _to,
                uint256 _tokenId
            )
                external
                whenNotPaused
            {
                // Safety check to prevent against an unexpected 0x0 default.
                require(_to != address(0));
                // Disallow transfers to this contract to prevent accidental misuse.
                // The contract should never own any kitties (except very briefly
                // after a gen0 cat is created and before it goes on auction).
                require(_to != address(this));
                // Check for approval and valid ownership
                require(_approvedFor(msg.sender, _tokenId));
                require(_owns(_from, _tokenId));
        
                // Reassign ownership (also clears pending approvals and emits Transfer event).
                _transfer(_from, _to, _tokenId);
            }
        
            /// @notice Returns the total number of Kitties currently in existence.
            /// @dev Required for ERC-721 compliance.
            function totalSupply() public view returns (uint) {
                return kitties.length - 1;
            }
        
            /// @notice Returns the address currently assigned ownership of a given Kitty.
            /// @dev Required for ERC-721 compliance.
            function ownerOf(uint256 _tokenId)
                external
                view
                returns (address owner)
            {
                owner = kittyIndexToOwner[_tokenId];
        
                require(owner != address(0));
            }
        
            /// @notice Returns a list of all Kitty IDs assigned to an address.
            /// @param _owner The owner whose Kitties we are interested in.
            /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
            ///  expensive (it walks the entire Kitty array looking for cats belonging to owner),
            ///  but it also returns a dynamic array, which is only supported for web3 calls, and
            ///  not contract-to-contract calls.
            function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
                uint256 tokenCount = balanceOf(_owner);
        
                if (tokenCount == 0) {
                    // Return an empty array
                    return new uint256[](0);
                } else {
                    uint256[] memory result = new uint256[](tokenCount);
                    uint256 totalCats = totalSupply();
                    uint256 resultIndex = 0;
        
                    // We count on the fact that all cats have IDs starting at 1 and increasing
                    // sequentially up to the totalCat count.
                    uint256 catId;
        
                    for (catId = 1; catId <= totalCats; catId++) {
                        if (kittyIndexToOwner[catId] == _owner) {
                            result[resultIndex] = catId;
                            resultIndex++;
                        }
                    }
        
                    return result;
                }
            }
        
            /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
            ///  This method is licenced under the Apache License.
            ///  Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
            function _memcpy(uint _dest, uint _src, uint _len) private view {
                // Copy word-length chunks while possible
                for(; _len >= 32; _len -= 32) {
                    assembly {
                        mstore(_dest, mload(_src))
                    }
                    _dest += 32;
                    _src += 32;
                }
        
                // Copy remaining bytes
                uint256 mask = 256 ** (32 - _len) - 1;
                assembly {
                    let srcpart := and(mload(_src), not(mask))
                    let destpart := and(mload(_dest), mask)
                    mstore(_dest, or(destpart, srcpart))
                }
            }
        
            /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
            ///  This method is licenced under the Apache License.
            ///  Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
            function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
                var outputString = new string(_stringLength);
                uint256 outputPtr;
                uint256 bytesPtr;
        
                assembly {
                    outputPtr := add(outputString, 32)
                    bytesPtr := _rawBytes
                }
        
                _memcpy(outputPtr, bytesPtr, _stringLength);
        
                return outputString;
            }
        
            /// @notice Returns a URI pointing to a metadata package for this token conforming to
            ///  ERC-721 (https://github.com/ethereum/EIPs/issues/721)
            /// @param _tokenId The ID number of the Kitty whose metadata should be returned.
            function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
                require(erc721Metadata != address(0));
                bytes32[4] memory buffer;
                uint256 count;
                (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
        
                return _toString(buffer, count);
            }
        }
        
        
        
        /// @title A facet of KittyCore that manages Kitty siring, gestation, and birth.
        /// @author Axiom Zen (https://www.axiomzen.co)
        /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
        contract KittyBreeding is KittyOwnership {
        
            /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy
            ///  timer begins for the matron.
            event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
        
            /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
            ///  the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
            ///  the COO role as the gas price changes.
            uint256 public autoBirthFee = 2 finney;
        
            // Keeps track of number of pregnant kitties.
            uint256 public pregnantKitties;
        
            /// @dev The address of the sibling contract that is used to implement the sooper-sekret
            ///  genetic combination algorithm.
            GeneScienceInterface public geneScience;
        
            /// @dev Update the address of the genetic contract, can only be called by the CEO.
            /// @param _address An address of a GeneScience contract instance to be used from this point forward.
            function setGeneScienceAddress(address _address) external onlyCEO {
                GeneScienceInterface candidateContract = GeneScienceInterface(_address);
        
                // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
                require(candidateContract.isGeneScience());
        
                // Set the new contract address
                geneScience = candidateContract;
            }
        
            /// @dev Checks that a given kitten is able to breed. Requires that the
            ///  current cooldown is finished (for sires) and also checks that there is
            ///  no pending pregnancy.
            function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
                // In addition to checking the cooldownEndBlock, we also need to check to see if
                // the cat has a pending birth; there can be some period of time between the end
                // of the pregnacy timer and the birth event.
                return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number));
            }
        
            /// @dev Check if a sire has authorized breeding with this matron. True if both sire
            ///  and matron have the same owner, or if the sire has given siring permission to
            ///  the matron's owner (via approveSiring()).
            function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
                address matronOwner = kittyIndexToOwner[_matronId];
                address sireOwner = kittyIndexToOwner[_sireId];
        
                // Siring is okay if they have same owner, or if the matron's owner was given
                // permission to breed with this sire.
                return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
            }
        
            /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex.
            ///  Also increments the cooldownIndex (unless it has hit the cap).
            /// @param _kitten A reference to the Kitty in storage which needs its timer started.
            function _triggerCooldown(Kitty storage _kitten) internal {
                // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
                _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number);
        
                // Increment the breeding count, clamping it at 13, which is the length of the
                // cooldowns array. We could check the array size dynamically, but hard-coding
                // this as a constant saves gas. Yay, Solidity!
                if (_kitten.cooldownIndex < 13) {
                    _kitten.cooldownIndex += 1;
                }
            }
        
            /// @notice Grants approval to another user to sire with one of your Kitties.
            /// @param _addr The address that will be able to sire with your Kitty. Set to
            ///  address(0) to clear all siring approvals for this Kitty.
            /// @param _sireId A Kitty that you own that _addr will now be able to sire with.
            function approveSiring(address _addr, uint256 _sireId)
                external
                whenNotPaused
            {
                require(_owns(msg.sender, _sireId));
                sireAllowedToAddress[_sireId] = _addr;
            }
        
            /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
            ///  be called by the COO address. (This fee is used to offset the gas cost incurred
            ///  by the autobirth daemon).
            function setAutoBirthFee(uint256 val) external onlyCOO {
                autoBirthFee = val;
            }
        
            /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation
            ///  period has passed.
            function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) {
                return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
            }
        
            /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or
            ///  in the middle of a siring cooldown).
            /// @param _kittyId reference the id of the kitten, any user can inquire about it
            function isReadyToBreed(uint256 _kittyId)
                public
                view
                returns (bool)
            {
                require(_kittyId > 0);
                Kitty storage kit = kitties[_kittyId];
                return _isReadyToBreed(kit);
            }
        
            /// @dev Checks whether a kitty is currently pregnant.
            /// @param _kittyId reference the id of the kitten, any user can inquire about it
            function isPregnant(uint256 _kittyId)
                public
                view
                returns (bool)
            {
                require(_kittyId > 0);
                // A kitty is pregnant if and only if this field is set
                return kitties[_kittyId].siringWithId != 0;
            }
        
            /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
            ///  check ownership permissions (that is up to the caller).
            /// @param _matron A reference to the Kitty struct of the potential matron.
            /// @param _matronId The matron's ID.
            /// @param _sire A reference to the Kitty struct of the potential sire.
            /// @param _sireId The sire's ID
            function _isValidMatingPair(
                Kitty storage _matron,
                uint256 _matronId,
                Kitty storage _sire,
                uint256 _sireId
            )
                private
                view
                returns(bool)
            {
                // A Kitty can't breed with itself!
                if (_matronId == _sireId) {
                    return false;
                }
        
                // Kitties can't breed with their parents.
                if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
                    return false;
                }
                if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
                    return false;
                }
        
                // We can short circuit the sibling check (below) if either cat is
                // gen zero (has a matron ID of zero).
                if (_sire.matronId == 0 || _matron.matronId == 0) {
                    return true;
                }
        
                // Kitties can't breed with full or half siblings.
                if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
                    return false;
                }
                if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
                    return false;
                }
        
                // Everything seems cool! Let's get DTF.
                return true;
            }
        
            /// @dev Internal check to see if a given sire and matron are a valid mating pair for
            ///  breeding via auction (i.e. skips ownership and siring approval checks).
            function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
                internal
                view
                returns (bool)
            {
                Kitty storage matron = kitties[_matronId];
                Kitty storage sire = kitties[_sireId];
                return _isValidMatingPair(matron, _matronId, sire, _sireId);
            }
        
            /// @notice Checks to see if two cats can breed together, including checks for
            ///  ownership and siring approvals. Does NOT check that both cats are ready for
            ///  breeding (i.e. breedWith could still fail until the cooldowns are finished).
            ///  TODO: Shouldn't this check pregnancy and cooldowns?!?
            /// @param _matronId The ID of the proposed matron.
            /// @param _sireId The ID of the proposed sire.
            function canBreedWith(uint256 _matronId, uint256 _sireId)
                external
                view
                returns(bool)
            {
                require(_matronId > 0);
                require(_sireId > 0);
                Kitty storage matron = kitties[_matronId];
                Kitty storage sire = kitties[_sireId];
                return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
                    _isSiringPermitted(_sireId, _matronId);
            }
        
            /// @dev Internal utility function to initiate breeding, assumes that all breeding
            ///  requirements have been checked.
            function _breedWith(uint256 _matronId, uint256 _sireId) internal {
                // Grab a reference to the Kitties from storage.
                Kitty storage sire = kitties[_sireId];
                Kitty storage matron = kitties[_matronId];
        
                // Mark the matron as pregnant, keeping track of who the sire is.
                matron.siringWithId = uint32(_sireId);
        
                // Trigger the cooldown for both parents.
                _triggerCooldown(sire);
                _triggerCooldown(matron);
        
                // Clear siring permission for both parents. This may not be strictly necessary
                // but it's likely to avoid confusion!
                delete sireAllowedToAddress[_matronId];
                delete sireAllowedToAddress[_sireId];
        
                // Every time a kitty gets pregnant, counter is incremented.
                pregnantKitties++;
        
                // Emit the pregnancy event.
                Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
            }
        
            /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you
            ///  have previously been given Siring approval. Will either make your cat pregnant, or will
            ///  fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
            /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful)
            /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful)
            function breedWithAuto(uint256 _matronId, uint256 _sireId)
                external
                payable
                whenNotPaused
            {
                // Checks for payment.
                require(msg.value >= autoBirthFee);
        
                // Caller must own the matron.
                require(_owns(msg.sender, _matronId));
        
                // Neither sire nor matron are allowed to be on auction during a normal
                // breeding operation, but we don't need to check that explicitly.
                // For matron: The caller of this function can't be the owner of the matron
                //   because the owner of a Kitty on auction is the auction house, and the
                //   auction house will never call breedWith().
                // For sire: Similarly, a sire on auction will be owned by the auction house
                //   and the act of transferring ownership will have cleared any oustanding
                //   siring approval.
                // Thus we don't need to spend gas explicitly checking to see if either cat
                // is on auction.
        
                // Check that matron and sire are both owned by caller, or that the sire
                // has given siring permission to caller (i.e. matron's owner).
                // Will fail for _sireId = 0
                require(_isSiringPermitted(_sireId, _matronId));
        
                // Grab a reference to the potential matron
                Kitty storage matron = kitties[_matronId];
        
                // Make sure matron isn't pregnant, or in the middle of a siring cooldown
                require(_isReadyToBreed(matron));
        
                // Grab a reference to the potential sire
                Kitty storage sire = kitties[_sireId];
        
                // Make sure sire isn't pregnant, or in the middle of a siring cooldown
                require(_isReadyToBreed(sire));
        
                // Test that these cats are a valid mating pair.
                require(_isValidMatingPair(
                    matron,
                    _matronId,
                    sire,
                    _sireId
                ));
        
                // All checks passed, kitty gets pregnant!
                _breedWith(_matronId, _sireId);
            }
        
            /// @notice Have a pregnant Kitty give birth!
            /// @param _matronId A Kitty ready to give birth.
            /// @return The Kitty ID of the new kitten.
            /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed,
            ///  combines the genes of the two parents to create a new kitten. The new Kitty is assigned
            ///  to the current owner of the matron. Upon successful completion, both the matron and the
            ///  new kitten will be ready to breed again. Note that anyone can call this function (if they
            ///  are willing to pay the gas!), but the new kitten always goes to the mother's owner.
            function giveBirth(uint256 _matronId)
                external
                whenNotPaused
                returns(uint256)
            {
                // Grab a reference to the matron in storage.
                Kitty storage matron = kitties[_matronId];
        
                // Check that the matron is a valid cat.
                require(matron.birthTime != 0);
        
                // Check that the matron is pregnant, and that its time has come!
                require(_isReadyToGiveBirth(matron));
        
                // Grab a reference to the sire in storage.
                uint256 sireId = matron.siringWithId;
                Kitty storage sire = kitties[sireId];
        
                // Determine the higher generation number of the two parents
                uint16 parentGen = matron.generation;
                if (sire.generation > matron.generation) {
                    parentGen = sire.generation;
                }
        
                // Call the sooper-sekret gene mixing operation.
                uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
        
                // Make the new kitten!
                address owner = kittyIndexToOwner[_matronId];
                uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner);
        
                // Clear the reference to sire from the matron (REQUIRED! Having siringWithId
                // set is what marks a matron as being pregnant.)
                delete matron.siringWithId;
        
                // Every time a kitty gives birth counter is decremented.
                pregnantKitties--;
        
                // Send the balance fee to the person who made birth happen.
                msg.sender.send(autoBirthFee);
        
                // return the new kitten's ID
                return kittenId;
            }
        }
        
        
        
        
        
        
        
        
        
        
        /// @title Auction Core
        /// @dev Contains models, variables, and internal methods for the auction.
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract ClockAuctionBase {
        
            // Represents an auction on an NFT
            struct Auction {
                // Current owner of NFT
                address seller;
                // Price (in wei) at beginning of auction
                uint128 startingPrice;
                // Price (in wei) at end of auction
                uint128 endingPrice;
                // Duration (in seconds) of auction
                uint64 duration;
                // Time when auction started
                // NOTE: 0 if this auction has been concluded
                uint64 startedAt;
            }
        
            // Reference to contract tracking NFT ownership
            ERC721 public nonFungibleContract;
        
            // Cut owner takes on each auction, measured in basis points (1/100 of a percent).
            // Values 0-10,000 map to 0%-100%
            uint256 public ownerCut;
        
            // Map from token ID to their corresponding auction.
            mapping (uint256 => Auction) tokenIdToAuction;
        
            event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
            event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
            event AuctionCancelled(uint256 tokenId);
        
            /// @dev Returns true if the claimant owns the token.
            /// @param _claimant - Address claiming to own the token.
            /// @param _tokenId - ID of token whose ownership to verify.
            function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
                return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
            }
        
            /// @dev Escrows the NFT, assigning ownership to this contract.
            /// Throws if the escrow fails.
            /// @param _owner - Current owner address of token to escrow.
            /// @param _tokenId - ID of token whose approval to verify.
            function _escrow(address _owner, uint256 _tokenId) internal {
                // it will throw if transfer fails
                nonFungibleContract.transferFrom(_owner, this, _tokenId);
            }
        
            /// @dev Transfers an NFT owned by this contract to another address.
            /// Returns true if the transfer succeeds.
            /// @param _receiver - Address to transfer NFT to.
            /// @param _tokenId - ID of token to transfer.
            function _transfer(address _receiver, uint256 _tokenId) internal {
                // it will throw if transfer fails
                nonFungibleContract.transfer(_receiver, _tokenId);
            }
        
            /// @dev Adds an auction to the list of open auctions. Also fires the
            ///  AuctionCreated event.
            /// @param _tokenId The ID of the token to be put on auction.
            /// @param _auction Auction to add.
            function _addAuction(uint256 _tokenId, Auction _auction) internal {
                // Require that all auctions have a duration of
                // at least one minute. (Keeps our math from getting hairy!)
                require(_auction.duration >= 1 minutes);
        
                tokenIdToAuction[_tokenId] = _auction;
        
                AuctionCreated(
                    uint256(_tokenId),
                    uint256(_auction.startingPrice),
                    uint256(_auction.endingPrice),
                    uint256(_auction.duration)
                );
            }
        
            /// @dev Cancels an auction unconditionally.
            function _cancelAuction(uint256 _tokenId, address _seller) internal {
                _removeAuction(_tokenId);
                _transfer(_seller, _tokenId);
                AuctionCancelled(_tokenId);
            }
        
            /// @dev Computes the price and transfers winnings.
            /// Does NOT transfer ownership of token.
            function _bid(uint256 _tokenId, uint256 _bidAmount)
                internal
                returns (uint256)
            {
                // Get a reference to the auction struct
                Auction storage auction = tokenIdToAuction[_tokenId];
        
                // Explicitly check that this auction is currently live.
                // (Because of how Ethereum mappings work, we can't just count
                // on the lookup above failing. An invalid _tokenId will just
                // return an auction object that is all zeros.)
                require(_isOnAuction(auction));
        
                // Check that the bid is greater than or equal to the current price
                uint256 price = _currentPrice(auction);
                require(_bidAmount >= price);
        
                // Grab a reference to the seller before the auction struct
                // gets deleted.
                address seller = auction.seller;
        
                // The bid is good! Remove the auction before sending the fees
                // to the sender so we can't have a reentrancy attack.
                _removeAuction(_tokenId);
        
                // Transfer proceeds to seller (if there are any!)
                if (price > 0) {
                    // Calculate the auctioneer's cut.
                    // (NOTE: _computeCut() is guaranteed to return a
                    // value <= price, so this subtraction can't go negative.)
                    uint256 auctioneerCut = _computeCut(price);
                    uint256 sellerProceeds = price - auctioneerCut;
        
                    // NOTE: Doing a transfer() in the middle of a complex
                    // method like this is generally discouraged because of
                    // reentrancy attacks and DoS attacks if the seller is
                    // a contract with an invalid fallback function. We explicitly
                    // guard against reentrancy attacks by removing the auction
                    // before calling transfer(), and the only thing the seller
                    // can DoS is the sale of their own asset! (And if it's an
                    // accident, they can call cancelAuction(). )
                    seller.transfer(sellerProceeds);
                }
        
                // Calculate any excess funds included with the bid. If the excess
                // is anything worth worrying about, transfer it back to bidder.
                // NOTE: We checked above that the bid amount is greater than or
                // equal to the price so this cannot underflow.
                uint256 bidExcess = _bidAmount - price;
        
                // Return the funds. Similar to the previous transfer, this is
                // not susceptible to a re-entry attack because the auction is
                // removed before any transfers occur.
                msg.sender.transfer(bidExcess);
        
                // Tell the world!
                AuctionSuccessful(_tokenId, price, msg.sender);
        
                return price;
            }
        
            /// @dev Removes an auction from the list of open auctions.
            /// @param _tokenId - ID of NFT on auction.
            function _removeAuction(uint256 _tokenId) internal {
                delete tokenIdToAuction[_tokenId];
            }
        
            /// @dev Returns true if the NFT is on auction.
            /// @param _auction - Auction to check.
            function _isOnAuction(Auction storage _auction) internal view returns (bool) {
                return (_auction.startedAt > 0);
            }
        
            /// @dev Returns current price of an NFT on auction. Broken into two
            ///  functions (this one, that computes the duration from the auction
            ///  structure, and the other that does the price computation) so we
            ///  can easily test that the price computation works correctly.
            function _currentPrice(Auction storage _auction)
                internal
                view
                returns (uint256)
            {
                uint256 secondsPassed = 0;
        
                // A bit of insurance against negative values (or wraparound).
                // Probably not necessary (since Ethereum guarnatees that the
                // now variable doesn't ever go backwards).
                if (now > _auction.startedAt) {
                    secondsPassed = now - _auction.startedAt;
                }
        
                return _computeCurrentPrice(
                    _auction.startingPrice,
                    _auction.endingPrice,
                    _auction.duration,
                    secondsPassed
                );
            }
        
            /// @dev Computes the current price of an auction. Factored out
            ///  from _currentPrice so we can run extensive unit tests.
            ///  When testing, make this function public and turn on
            ///  `Current price computation` test suite.
            function _computeCurrentPrice(
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                uint256 _secondsPassed
            )
                internal
                pure
                returns (uint256)
            {
                // NOTE: We don't use SafeMath (or similar) in this function because
                //  all of our public functions carefully cap the maximum values for
                //  time (at 64-bits) and currency (at 128-bits). _duration is
                //  also known to be non-zero (see the require() statement in
                //  _addAuction())
                if (_secondsPassed >= _duration) {
                    // We've reached the end of the dynamic pricing portion
                    // of the auction, just return the end price.
                    return _endingPrice;
                } else {
                    // Starting price can be higher than ending price (and often is!), so
                    // this delta can be negative.
                    int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
        
                    // This multiplication can't overflow, _secondsPassed will easily fit within
                    // 64-bits, and totalPriceChange will easily fit within 128-bits, their product
                    // will always fit within 256-bits.
                    int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
        
                    // currentPriceChange can be negative, but if so, will have a magnitude
                    // less that _startingPrice. Thus, this result will always end up positive.
                    int256 currentPrice = int256(_startingPrice) + currentPriceChange;
        
                    return uint256(currentPrice);
                }
            }
        
            /// @dev Computes owner's cut of a sale.
            /// @param _price - Sale price of NFT.
            function _computeCut(uint256 _price) internal view returns (uint256) {
                // NOTE: We don't use SafeMath (or similar) in this function because
                //  all of our entry functions carefully cap the maximum values for
                //  currency (at 128-bits), and ownerCut <= 10000 (see the require()
                //  statement in the ClockAuction constructor). The result of this
                //  function is always guaranteed to be <= _price.
                return _price * ownerCut / 10000;
            }
        
        }
        
        
        
        
        
        
        
        /**
         * @title Pausable
         * @dev Base contract which allows children to implement an emergency stop mechanism.
         */
        contract Pausable is Ownable {
          event Pause();
          event Unpause();
        
          bool public paused = false;
        
        
          /**
           * @dev modifier to allow actions only when the contract IS paused
           */
          modifier whenNotPaused() {
            require(!paused);
            _;
          }
        
          /**
           * @dev modifier to allow actions only when the contract IS NOT paused
           */
          modifier whenPaused {
            require(paused);
            _;
          }
        
          /**
           * @dev called by the owner to pause, triggers stopped state
           */
          function pause() onlyOwner whenNotPaused returns (bool) {
            paused = true;
            Pause();
            return true;
          }
        
          /**
           * @dev called by the owner to unpause, returns to normal state
           */
          function unpause() onlyOwner whenPaused returns (bool) {
            paused = false;
            Unpause();
            return true;
          }
        }
        
        
        /// @title Clock auction for non-fungible tokens.
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract ClockAuction is Pausable, ClockAuctionBase {
        
            /// @dev The ERC-165 interface signature for ERC-721.
            ///  Ref: https://github.com/ethereum/EIPs/issues/165
            ///  Ref: https://github.com/ethereum/EIPs/issues/721
            bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
        
            /// @dev Constructor creates a reference to the NFT ownership contract
            ///  and verifies the owner cut is in the valid range.
            /// @param _nftAddress - address of a deployed contract implementing
            ///  the Nonfungible Interface.
            /// @param _cut - percent cut the owner takes on each auction, must be
            ///  between 0-10,000.
            function ClockAuction(address _nftAddress, uint256 _cut) public {
                require(_cut <= 10000);
                ownerCut = _cut;
        
                ERC721 candidateContract = ERC721(_nftAddress);
                require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
                nonFungibleContract = candidateContract;
            }
        
            /// @dev Remove all Ether from the contract, which is the owner's cuts
            ///  as well as any Ether sent directly to the contract address.
            ///  Always transfers to the NFT contract, but can be called either by
            ///  the owner or the NFT contract.
            function withdrawBalance() external {
                address nftAddress = address(nonFungibleContract);
        
                require(
                    msg.sender == owner ||
                    msg.sender == nftAddress
                );
                // We are using this boolean method to make sure that even if one fails it will still work
                bool res = nftAddress.send(this.balance);
            }
        
            /// @dev Creates and begins a new auction.
            /// @param _tokenId - ID of token to auction, sender must be owner.
            /// @param _startingPrice - Price of item (in wei) at beginning of auction.
            /// @param _endingPrice - Price of item (in wei) at end of auction.
            /// @param _duration - Length of time to move between starting
            ///  price and ending price (in seconds).
            /// @param _seller - Seller, if not the message sender
            function createAuction(
                uint256 _tokenId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                address _seller
            )
                external
                whenNotPaused
            {
                // Sanity check that no inputs overflow how many bits we've allocated
                // to store them in the auction struct.
                require(_startingPrice == uint256(uint128(_startingPrice)));
                require(_endingPrice == uint256(uint128(_endingPrice)));
                require(_duration == uint256(uint64(_duration)));
        
                require(_owns(msg.sender, _tokenId));
                _escrow(msg.sender, _tokenId);
                Auction memory auction = Auction(
                    _seller,
                    uint128(_startingPrice),
                    uint128(_endingPrice),
                    uint64(_duration),
                    uint64(now)
                );
                _addAuction(_tokenId, auction);
            }
        
            /// @dev Bids on an open auction, completing the auction and transferring
            ///  ownership of the NFT if enough Ether is supplied.
            /// @param _tokenId - ID of token to bid on.
            function bid(uint256 _tokenId)
                external
                payable
                whenNotPaused
            {
                // _bid will throw if the bid or funds transfer fails
                _bid(_tokenId, msg.value);
                _transfer(msg.sender, _tokenId);
            }
        
            /// @dev Cancels an auction that hasn't been won yet.
            ///  Returns the NFT to original owner.
            /// @notice This is a state-modifying function that can
            ///  be called while the contract is paused.
            /// @param _tokenId - ID of token on auction
            function cancelAuction(uint256 _tokenId)
                external
            {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                address seller = auction.seller;
                require(msg.sender == seller);
                _cancelAuction(_tokenId, seller);
            }
        
            /// @dev Cancels an auction when the contract is paused.
            ///  Only the owner may do this, and NFTs are returned to
            ///  the seller. This should only be used in emergencies.
            /// @param _tokenId - ID of the NFT on auction to cancel.
            function cancelAuctionWhenPaused(uint256 _tokenId)
                whenPaused
                onlyOwner
                external
            {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                _cancelAuction(_tokenId, auction.seller);
            }
        
            /// @dev Returns auction info for an NFT on auction.
            /// @param _tokenId - ID of NFT on auction.
            function getAuction(uint256 _tokenId)
                external
                view
                returns
            (
                address seller,
                uint256 startingPrice,
                uint256 endingPrice,
                uint256 duration,
                uint256 startedAt
            ) {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                return (
                    auction.seller,
                    auction.startingPrice,
                    auction.endingPrice,
                    auction.duration,
                    auction.startedAt
                );
            }
        
            /// @dev Returns the current price of an auction.
            /// @param _tokenId - ID of the token price we are checking.
            function getCurrentPrice(uint256 _tokenId)
                external
                view
                returns (uint256)
            {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                return _currentPrice(auction);
            }
        
        }
        
        
        /// @title Reverse auction modified for siring
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract SiringClockAuction is ClockAuction {
        
            // @dev Sanity check that allows us to ensure that we are pointing to the
            //  right auction in our setSiringAuctionAddress() call.
            bool public isSiringClockAuction = true;
        
            // Delegate constructor
            function SiringClockAuction(address _nftAddr, uint256 _cut) public
                ClockAuction(_nftAddr, _cut) {}
        
            /// @dev Creates and begins a new auction. Since this function is wrapped,
            /// require sender to be KittyCore contract.
            /// @param _tokenId - ID of token to auction, sender must be owner.
            /// @param _startingPrice - Price of item (in wei) at beginning of auction.
            /// @param _endingPrice - Price of item (in wei) at end of auction.
            /// @param _duration - Length of auction (in seconds).
            /// @param _seller - Seller, if not the message sender
            function createAuction(
                uint256 _tokenId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                address _seller
            )
                external
            {
                // Sanity check that no inputs overflow how many bits we've allocated
                // to store them in the auction struct.
                require(_startingPrice == uint256(uint128(_startingPrice)));
                require(_endingPrice == uint256(uint128(_endingPrice)));
                require(_duration == uint256(uint64(_duration)));
        
                require(msg.sender == address(nonFungibleContract));
                _escrow(_seller, _tokenId);
                Auction memory auction = Auction(
                    _seller,
                    uint128(_startingPrice),
                    uint128(_endingPrice),
                    uint64(_duration),
                    uint64(now)
                );
                _addAuction(_tokenId, auction);
            }
        
            /// @dev Places a bid for siring. Requires the sender
            /// is the KittyCore contract because all bid methods
            /// should be wrapped. Also returns the kitty to the
            /// seller rather than the winner.
            function bid(uint256 _tokenId)
                external
                payable
            {
                require(msg.sender == address(nonFungibleContract));
                address seller = tokenIdToAuction[_tokenId].seller;
                // _bid checks that token ID is valid and will throw if bid fails
                _bid(_tokenId, msg.value);
                // We transfer the kitty back to the seller, the winner will get
                // the offspring
                _transfer(seller, _tokenId);
            }
        
        }
        
        
        
        
        
        /// @title Clock auction modified for sale of kitties
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract SaleClockAuction is ClockAuction {
        
            // @dev Sanity check that allows us to ensure that we are pointing to the
            //  right auction in our setSaleAuctionAddress() call.
            bool public isSaleClockAuction = true;
        
            // Tracks last 5 sale price of gen0 kitty sales
            uint256 public gen0SaleCount;
            uint256[5] public lastGen0SalePrices;
        
            // Delegate constructor
            function SaleClockAuction(address _nftAddr, uint256 _cut) public
                ClockAuction(_nftAddr, _cut) {}
        
            /// @dev Creates and begins a new auction.
            /// @param _tokenId - ID of token to auction, sender must be owner.
            /// @param _startingPrice - Price of item (in wei) at beginning of auction.
            /// @param _endingPrice - Price of item (in wei) at end of auction.
            /// @param _duration - Length of auction (in seconds).
            /// @param _seller - Seller, if not the message sender
            function createAuction(
                uint256 _tokenId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                address _seller
            )
                external
            {
                // Sanity check that no inputs overflow how many bits we've allocated
                // to store them in the auction struct.
                require(_startingPrice == uint256(uint128(_startingPrice)));
                require(_endingPrice == uint256(uint128(_endingPrice)));
                require(_duration == uint256(uint64(_duration)));
        
                require(msg.sender == address(nonFungibleContract));
                _escrow(_seller, _tokenId);
                Auction memory auction = Auction(
                    _seller,
                    uint128(_startingPrice),
                    uint128(_endingPrice),
                    uint64(_duration),
                    uint64(now)
                );
                _addAuction(_tokenId, auction);
            }
        
            /// @dev Updates lastSalePrice if seller is the nft contract
            /// Otherwise, works the same as default bid method.
            function bid(uint256 _tokenId)
                external
                payable
            {
                // _bid verifies token ID size
                address seller = tokenIdToAuction[_tokenId].seller;
                uint256 price = _bid(_tokenId, msg.value);
                _transfer(msg.sender, _tokenId);
        
                // If not a gen0 auction, exit
                if (seller == address(nonFungibleContract)) {
                    // Track gen0 sale prices
                    lastGen0SalePrices[gen0SaleCount % 5] = price;
                    gen0SaleCount++;
                }
            }
        
            function averageGen0SalePrice() external view returns (uint256) {
                uint256 sum = 0;
                for (uint256 i = 0; i < 5; i++) {
                    sum += lastGen0SalePrices[i];
                }
                return sum / 5;
            }
        
        }
        
        
        /// @title Handles creating auctions for sale and siring of kitties.
        ///  This wrapper of ReverseAuction exists only so that users can create
        ///  auctions with only one transaction.
        contract KittyAuction is KittyBreeding {
        
            // @notice The auction contract variables are defined in KittyBase to allow
            //  us to refer to them in KittyOwnership to prevent accidental transfers.
            // `saleAuction` refers to the auction for gen0 and p2p sale of kitties.
            // `siringAuction` refers to the auction for siring rights of kitties.
        
            /// @dev Sets the reference to the sale auction.
            /// @param _address - Address of sale contract.
            function setSaleAuctionAddress(address _address) external onlyCEO {
                SaleClockAuction candidateContract = SaleClockAuction(_address);
        
                // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
                require(candidateContract.isSaleClockAuction());
        
                // Set the new contract address
                saleAuction = candidateContract;
            }
        
            /// @dev Sets the reference to the siring auction.
            /// @param _address - Address of siring contract.
            function setSiringAuctionAddress(address _address) external onlyCEO {
                SiringClockAuction candidateContract = SiringClockAuction(_address);
        
                // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
                require(candidateContract.isSiringClockAuction());
        
                // Set the new contract address
                siringAuction = candidateContract;
            }
        
            /// @dev Put a kitty up for auction.
            ///  Does some ownership trickery to create auctions in one tx.
            function createSaleAuction(
                uint256 _kittyId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration
            )
                external
                whenNotPaused
            {
                // Auction contract checks input sizes
                // If kitty is already on any auction, this will throw
                // because it will be owned by the auction contract.
                require(_owns(msg.sender, _kittyId));
                // Ensure the kitty is not pregnant to prevent the auction
                // contract accidentally receiving ownership of the child.
                // NOTE: the kitty IS allowed to be in a cooldown.
                require(!isPregnant(_kittyId));
                _approve(_kittyId, saleAuction);
                // Sale auction throws if inputs are invalid and clears
                // transfer and sire approval after escrowing the kitty.
                saleAuction.createAuction(
                    _kittyId,
                    _startingPrice,
                    _endingPrice,
                    _duration,
                    msg.sender
                );
            }
        
            /// @dev Put a kitty up for auction to be sire.
            ///  Performs checks to ensure the kitty can be sired, then
            ///  delegates to reverse auction.
            function createSiringAuction(
                uint256 _kittyId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration
            )
                external
                whenNotPaused
            {
                // Auction contract checks input sizes
                // If kitty is already on any auction, this will throw
                // because it will be owned by the auction contract.
                require(_owns(msg.sender, _kittyId));
                require(isReadyToBreed(_kittyId));
                _approve(_kittyId, siringAuction);
                // Siring auction throws if inputs are invalid and clears
                // transfer and sire approval after escrowing the kitty.
                siringAuction.createAuction(
                    _kittyId,
                    _startingPrice,
                    _endingPrice,
                    _duration,
                    msg.sender
                );
            }
        
            /// @dev Completes a siring auction by bidding.
            ///  Immediately breeds the winning matron with the sire on auction.
            /// @param _sireId - ID of the sire on auction.
            /// @param _matronId - ID of the matron owned by the bidder.
            function bidOnSiringAuction(
                uint256 _sireId,
                uint256 _matronId
            )
                external
                payable
                whenNotPaused
            {
                // Auction contract checks input sizes
                require(_owns(msg.sender, _matronId));
                require(isReadyToBreed(_matronId));
                require(_canBreedWithViaAuction(_matronId, _sireId));
        
                // Define the current price of the auction.
                uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
                require(msg.value >= currentPrice + autoBirthFee);
        
                // Siring auction will throw if the bid fails.
                siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
                _breedWith(uint32(_matronId), uint32(_sireId));
            }
        
            /// @dev Transfers the balance of the sale auction contract
            /// to the KittyCore contract. We use two-step withdrawal to
            /// prevent two transfer calls in the auction bid function.
            function withdrawAuctionBalances() external onlyCLevel {
                saleAuction.withdrawBalance();
                siringAuction.withdrawBalance();
            }
        }
        
        
        /// @title all functions related to creating kittens
        contract KittyMinting is KittyAuction {
        
            // Limits the number of cats the contract owner can ever create.
            uint256 public constant PROMO_CREATION_LIMIT = 5000;
            uint256 public constant GEN0_CREATION_LIMIT = 45000;
        
            // Constants for gen0 auctions.
            uint256 public constant GEN0_STARTING_PRICE = 10 finney;
            uint256 public constant GEN0_AUCTION_DURATION = 1 days;
        
            // Counts the number of cats the contract owner has created.
            uint256 public promoCreatedCount;
            uint256 public gen0CreatedCount;
        
            /// @dev we can create promo kittens, up to a limit. Only callable by COO
            /// @param _genes the encoded genes of the kitten to be created, any value is accepted
            /// @param _owner the future owner of the created kittens. Default to contract COO
            function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
                address kittyOwner = _owner;
                if (kittyOwner == address(0)) {
                     kittyOwner = cooAddress;
                }
                require(promoCreatedCount < PROMO_CREATION_LIMIT);
        
                promoCreatedCount++;
                _createKitty(0, 0, 0, _genes, kittyOwner);
            }
        
            /// @dev Creates a new gen0 kitty with the given genes and
            ///  creates an auction for it.
            function createGen0Auction(uint256 _genes) external onlyCOO {
                require(gen0CreatedCount < GEN0_CREATION_LIMIT);
        
                uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this));
                _approve(kittyId, saleAuction);
        
                saleAuction.createAuction(
                    kittyId,
                    _computeNextGen0Price(),
                    0,
                    GEN0_AUCTION_DURATION,
                    address(this)
                );
        
                gen0CreatedCount++;
            }
        
            /// @dev Computes the next gen0 auction starting price, given
            ///  the average of the past 5 prices + 50%.
            function _computeNextGen0Price() internal view returns (uint256) {
                uint256 avePrice = saleAuction.averageGen0SalePrice();
        
                // Sanity check to ensure we don't overflow arithmetic
                require(avePrice == uint256(uint128(avePrice)));
        
                uint256 nextPrice = avePrice + (avePrice / 2);
        
                // We never auction for less than starting price
                if (nextPrice < GEN0_STARTING_PRICE) {
                    nextPrice = GEN0_STARTING_PRICE;
                }
        
                return nextPrice;
            }
        }
        
        
        /// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain.
        /// @author Axiom Zen (https://www.axiomzen.co)
        /// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost.
        contract KittyCore is KittyMinting {
        
            // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections,
            // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
            // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
            // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
            // them in their own contracts, we can upgrade them without disrupting the main contract that tracks
            // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of
            // the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
            // Don't worry, I'm sure someone will reverse engineer it soon enough!
            //
            // Secondly, we break the core contract into multiple files using inheritence, one for each major
            // facet of functionality of CK. This allows us to keep related code bundled together while still
            // avoiding a single giant file with everything in it. The breakdown is as follows:
            //
            //      - KittyBase: This is where we define the most fundamental code shared throughout the core
            //             functionality. This includes our main data storage, constants and data types, plus
            //             internal functions for managing these items.
            //
            //      - KittyAccessControl: This contract manages the various addresses and constraints for operations
            //             that can be executed only by specific roles. Namely CEO, CFO and COO.
            //
            //      - KittyOwnership: This provides the methods required for basic non-fungible token
            //             transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
            //
            //      - KittyBreeding: This file contains the methods necessary to breed cats together, including
            //             keeping track of siring offers, and relies on an external genetic combination contract.
            //
            //      - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring
            //             services. The actual auction functionality is handled in two sibling contracts (one
            //             for sales and one for siring), while auction creation and bidding is mostly mediated
            //             through this facet of the core contract.
            //
            //      - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats.
            //             We can make up to 5000 "promo" cats that can be given away (especially important when
            //             the community is new), and all others can only be created and then immediately put up
            //             for auction via an algorithmically determined starting price. Regardless of how they
            //             are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
            //             community to breed, breed, breed!
        
            // Set in case the core contract is broken and an upgrade is required
            address public newContractAddress;
        
            /// @notice Creates the main CryptoKitties smart contract instance.
            function KittyCore() public {
                // Starts paused.
                paused = true;
        
                // the creator of the contract is the initial CEO
                ceoAddress = msg.sender;
        
                // the creator of the contract is also the initial COO
                cooAddress = msg.sender;
        
                // start with the mythical kitten 0 - so we don't have generation-0 parent issues
                _createKitty(0, 0, 0, uint256(-1), address(0));
            }
        
            /// @dev Used to mark the smart contract as upgraded, in case there is a serious
            ///  breaking bug. This method does nothing but keep track of the new contract and
            ///  emit a message indicating that the new address is set. It's up to clients of this
            ///  contract to update to the new contract address in that case. (This contract will
            ///  be paused indefinitely if such an upgrade takes place.)
            /// @param _v2Address new address
            function setNewAddress(address _v2Address) external onlyCEO whenPaused {
                // See README.md for updgrade plan
                newContractAddress = _v2Address;
                ContractUpgrade(_v2Address);
            }
        
            /// @notice No tipping!
            /// @dev Reject all Ether from being sent here, unless it's from one of the
            ///  two auction contracts. (Hopefully, we can prevent user accidents.)
            function() external payable {
                require(
                    msg.sender == address(saleAuction) ||
                    msg.sender == address(siringAuction)
                );
            }
        
            /// @notice Returns all the relevant information about a specific kitty.
            /// @param _id The ID of the kitty of interest.
            function getKitty(uint256 _id)
                external
                view
                returns (
                bool isGestating,
                bool isReady,
                uint256 cooldownIndex,
                uint256 nextActionAt,
                uint256 siringWithId,
                uint256 birthTime,
                uint256 matronId,
                uint256 sireId,
                uint256 generation,
                uint256 genes
            ) {
                Kitty storage kit = kitties[_id];
        
                // if this variable is 0 then it's not gestating
                isGestating = (kit.siringWithId != 0);
                isReady = (kit.cooldownEndBlock <= block.number);
                cooldownIndex = uint256(kit.cooldownIndex);
                nextActionAt = uint256(kit.cooldownEndBlock);
                siringWithId = uint256(kit.siringWithId);
                birthTime = uint256(kit.birthTime);
                matronId = uint256(kit.matronId);
                sireId = uint256(kit.sireId);
                generation = uint256(kit.generation);
                genes = kit.genes;
            }
        
            /// @dev Override unpause so it requires all external contract addresses
            ///  to be set before contract can be unpaused. Also, we can't have
            ///  newContractAddress set either, because then the contract was upgraded.
            /// @notice This is public rather than external so we can call super.unpause
            ///  without using an expensive CALL.
            function unpause() public onlyCEO whenPaused {
                require(saleAuction != address(0));
                require(siringAuction != address(0));
                require(geneScience != address(0));
                require(newContractAddress == address(0));
        
                // Actually unpause the contract.
                super.unpause();
            }
        
            // @dev Allows the CFO to capture the balance available to the contract.
            function withdrawBalance() external onlyCFO {
                uint256 balance = this.balance;
                // Subtract all the currently pregnant kittens we have, plus 1 of margin.
                uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee;
        
                if (balance > subtractFees) {
                    cfoAddress.send(balance - subtractFees);
                }
            }
        }

        File 3 of 4: SaleClockAuction
        pragma solidity ^0.4.11;
        
        
        /**
         * @title Ownable
         * @dev The Ownable contract has an owner address, and provides basic authorization control
         * functions, this simplifies the implementation of "user permissions".
         */
        contract Ownable {
          address public owner;
        
        
          /**
           * @dev The Ownable constructor sets the original `owner` of the contract to the sender
           * account.
           */
          function Ownable() {
            owner = msg.sender;
          }
        
        
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
            require(msg.sender == owner);
            _;
          }
        
        
          /**
           * @dev Allows the current owner to transfer control of the contract to a newOwner.
           * @param newOwner The address to transfer ownership to.
           */
          function transferOwnership(address newOwner) onlyOwner {
            if (newOwner != address(0)) {
              owner = newOwner;
            }
          }
        
        }
        
        
        
        /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
        /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
        contract ERC721 {
            // Required methods
            function totalSupply() public view returns (uint256 total);
            function balanceOf(address _owner) public view returns (uint256 balance);
            function ownerOf(uint256 _tokenId) external view returns (address owner);
            function approve(address _to, uint256 _tokenId) external;
            function transfer(address _to, uint256 _tokenId) external;
            function transferFrom(address _from, address _to, uint256 _tokenId) external;
        
            // Events
            event Transfer(address from, address to, uint256 tokenId);
            event Approval(address owner, address approved, uint256 tokenId);
        
            // Optional
            // function name() public view returns (string name);
            // function symbol() public view returns (string symbol);
            // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
            // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
        
            // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
            function supportsInterface(bytes4 _interfaceID) external view returns (bool);
        }
        
        
        
        
        
        
        
        
        
        /// @title Auction Core
        /// @dev Contains models, variables, and internal methods for the auction.
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract ClockAuctionBase {
        
            // Represents an auction on an NFT
            struct Auction {
                // Current owner of NFT
                address seller;
                // Price (in wei) at beginning of auction
                uint128 startingPrice;
                // Price (in wei) at end of auction
                uint128 endingPrice;
                // Duration (in seconds) of auction
                uint64 duration;
                // Time when auction started
                // NOTE: 0 if this auction has been concluded
                uint64 startedAt;
            }
        
            // Reference to contract tracking NFT ownership
            ERC721 public nonFungibleContract;
        
            // Cut owner takes on each auction, measured in basis points (1/100 of a percent).
            // Values 0-10,000 map to 0%-100%
            uint256 public ownerCut;
        
            // Map from token ID to their corresponding auction.
            mapping (uint256 => Auction) tokenIdToAuction;
        
            event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
            event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
            event AuctionCancelled(uint256 tokenId);
        
            /// @dev Returns true if the claimant owns the token.
            /// @param _claimant - Address claiming to own the token.
            /// @param _tokenId - ID of token whose ownership to verify.
            function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
                return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
            }
        
            /// @dev Escrows the NFT, assigning ownership to this contract.
            /// Throws if the escrow fails.
            /// @param _owner - Current owner address of token to escrow.
            /// @param _tokenId - ID of token whose approval to verify.
            function _escrow(address _owner, uint256 _tokenId) internal {
                // it will throw if transfer fails
                nonFungibleContract.transferFrom(_owner, this, _tokenId);
            }
        
            /// @dev Transfers an NFT owned by this contract to another address.
            /// Returns true if the transfer succeeds.
            /// @param _receiver - Address to transfer NFT to.
            /// @param _tokenId - ID of token to transfer.
            function _transfer(address _receiver, uint256 _tokenId) internal {
                // it will throw if transfer fails
                nonFungibleContract.transfer(_receiver, _tokenId);
            }
        
            /// @dev Adds an auction to the list of open auctions. Also fires the
            ///  AuctionCreated event.
            /// @param _tokenId The ID of the token to be put on auction.
            /// @param _auction Auction to add.
            function _addAuction(uint256 _tokenId, Auction _auction) internal {
                // Require that all auctions have a duration of
                // at least one minute. (Keeps our math from getting hairy!)
                require(_auction.duration >= 1 minutes);
        
                tokenIdToAuction[_tokenId] = _auction;
        
                AuctionCreated(
                    uint256(_tokenId),
                    uint256(_auction.startingPrice),
                    uint256(_auction.endingPrice),
                    uint256(_auction.duration)
                );
            }
        
            /// @dev Cancels an auction unconditionally.
            function _cancelAuction(uint256 _tokenId, address _seller) internal {
                _removeAuction(_tokenId);
                _transfer(_seller, _tokenId);
                AuctionCancelled(_tokenId);
            }
        
            /// @dev Computes the price and transfers winnings.
            /// Does NOT transfer ownership of token.
            function _bid(uint256 _tokenId, uint256 _bidAmount)
                internal
                returns (uint256)
            {
                // Get a reference to the auction struct
                Auction storage auction = tokenIdToAuction[_tokenId];
        
                // Explicitly check that this auction is currently live.
                // (Because of how Ethereum mappings work, we can't just count
                // on the lookup above failing. An invalid _tokenId will just
                // return an auction object that is all zeros.)
                require(_isOnAuction(auction));
        
                // Check that the bid is greater than or equal to the current price
                uint256 price = _currentPrice(auction);
                require(_bidAmount >= price);
        
                // Grab a reference to the seller before the auction struct
                // gets deleted.
                address seller = auction.seller;
        
                // The bid is good! Remove the auction before sending the fees
                // to the sender so we can't have a reentrancy attack.
                _removeAuction(_tokenId);
        
                // Transfer proceeds to seller (if there are any!)
                if (price > 0) {
                    // Calculate the auctioneer's cut.
                    // (NOTE: _computeCut() is guaranteed to return a
                    // value <= price, so this subtraction can't go negative.)
                    uint256 auctioneerCut = _computeCut(price);
                    uint256 sellerProceeds = price - auctioneerCut;
        
                    // NOTE: Doing a transfer() in the middle of a complex
                    // method like this is generally discouraged because of
                    // reentrancy attacks and DoS attacks if the seller is
                    // a contract with an invalid fallback function. We explicitly
                    // guard against reentrancy attacks by removing the auction
                    // before calling transfer(), and the only thing the seller
                    // can DoS is the sale of their own asset! (And if it's an
                    // accident, they can call cancelAuction(). )
                    seller.transfer(sellerProceeds);
                }
        
                // Calculate any excess funds included with the bid. If the excess
                // is anything worth worrying about, transfer it back to bidder.
                // NOTE: We checked above that the bid amount is greater than or
                // equal to the price so this cannot underflow.
                uint256 bidExcess = _bidAmount - price;
        
                // Return the funds. Similar to the previous transfer, this is
                // not susceptible to a re-entry attack because the auction is
                // removed before any transfers occur.
                msg.sender.transfer(bidExcess);
        
                // Tell the world!
                AuctionSuccessful(_tokenId, price, msg.sender);
        
                return price;
            }
        
            /// @dev Removes an auction from the list of open auctions.
            /// @param _tokenId - ID of NFT on auction.
            function _removeAuction(uint256 _tokenId) internal {
                delete tokenIdToAuction[_tokenId];
            }
        
            /// @dev Returns true if the NFT is on auction.
            /// @param _auction - Auction to check.
            function _isOnAuction(Auction storage _auction) internal view returns (bool) {
                return (_auction.startedAt > 0);
            }
        
            /// @dev Returns current price of an NFT on auction. Broken into two
            ///  functions (this one, that computes the duration from the auction
            ///  structure, and the other that does the price computation) so we
            ///  can easily test that the price computation works correctly.
            function _currentPrice(Auction storage _auction)
                internal
                view
                returns (uint256)
            {
                uint256 secondsPassed = 0;
        
                // A bit of insurance against negative values (or wraparound).
                // Probably not necessary (since Ethereum guarnatees that the
                // now variable doesn't ever go backwards).
                if (now > _auction.startedAt) {
                    secondsPassed = now - _auction.startedAt;
                }
        
                return _computeCurrentPrice(
                    _auction.startingPrice,
                    _auction.endingPrice,
                    _auction.duration,
                    secondsPassed
                );
            }
        
            /// @dev Computes the current price of an auction. Factored out
            ///  from _currentPrice so we can run extensive unit tests.
            ///  When testing, make this function public and turn on
            ///  `Current price computation` test suite.
            function _computeCurrentPrice(
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                uint256 _secondsPassed
            )
                internal
                pure
                returns (uint256)
            {
                // NOTE: We don't use SafeMath (or similar) in this function because
                //  all of our public functions carefully cap the maximum values for
                //  time (at 64-bits) and currency (at 128-bits). _duration is
                //  also known to be non-zero (see the require() statement in
                //  _addAuction())
                if (_secondsPassed >= _duration) {
                    // We've reached the end of the dynamic pricing portion
                    // of the auction, just return the end price.
                    return _endingPrice;
                } else {
                    // Starting price can be higher than ending price (and often is!), so
                    // this delta can be negative.
                    int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
        
                    // This multiplication can't overflow, _secondsPassed will easily fit within
                    // 64-bits, and totalPriceChange will easily fit within 128-bits, their product
                    // will always fit within 256-bits.
                    int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
        
                    // currentPriceChange can be negative, but if so, will have a magnitude
                    // less that _startingPrice. Thus, this result will always end up positive.
                    int256 currentPrice = int256(_startingPrice) + currentPriceChange;
        
                    return uint256(currentPrice);
                }
            }
        
            /// @dev Computes owner's cut of a sale.
            /// @param _price - Sale price of NFT.
            function _computeCut(uint256 _price) internal view returns (uint256) {
                // NOTE: We don't use SafeMath (or similar) in this function because
                //  all of our entry functions carefully cap the maximum values for
                //  currency (at 128-bits), and ownerCut <= 10000 (see the require()
                //  statement in the ClockAuction constructor). The result of this
                //  function is always guaranteed to be <= _price.
                return _price * ownerCut / 10000;
            }
        
        }
        
        
        
        
        
        
        
        /**
         * @title Pausable
         * @dev Base contract which allows children to implement an emergency stop mechanism.
         */
        contract Pausable is Ownable {
          event Pause();
          event Unpause();
        
          bool public paused = false;
        
        
          /**
           * @dev modifier to allow actions only when the contract IS paused
           */
          modifier whenNotPaused() {
            require(!paused);
            _;
          }
        
          /**
           * @dev modifier to allow actions only when the contract IS NOT paused
           */
          modifier whenPaused {
            require(paused);
            _;
          }
        
          /**
           * @dev called by the owner to pause, triggers stopped state
           */
          function pause() onlyOwner whenNotPaused returns (bool) {
            paused = true;
            Pause();
            return true;
          }
        
          /**
           * @dev called by the owner to unpause, returns to normal state
           */
          function unpause() onlyOwner whenPaused returns (bool) {
            paused = false;
            Unpause();
            return true;
          }
        }
        
        
        /// @title Clock auction for non-fungible tokens.
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract ClockAuction is Pausable, ClockAuctionBase {
        
            /// @dev The ERC-165 interface signature for ERC-721.
            ///  Ref: https://github.com/ethereum/EIPs/issues/165
            ///  Ref: https://github.com/ethereum/EIPs/issues/721
            bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
        
            /// @dev Constructor creates a reference to the NFT ownership contract
            ///  and verifies the owner cut is in the valid range.
            /// @param _nftAddress - address of a deployed contract implementing
            ///  the Nonfungible Interface.
            /// @param _cut - percent cut the owner takes on each auction, must be
            ///  between 0-10,000.
            function ClockAuction(address _nftAddress, uint256 _cut) public {
                require(_cut <= 10000);
                ownerCut = _cut;
        
                ERC721 candidateContract = ERC721(_nftAddress);
                require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
                nonFungibleContract = candidateContract;
            }
        
            /// @dev Remove all Ether from the contract, which is the owner's cuts
            ///  as well as any Ether sent directly to the contract address.
            ///  Always transfers to the NFT contract, but can be called either by
            ///  the owner or the NFT contract.
            function withdrawBalance() external {
                address nftAddress = address(nonFungibleContract);
        
                require(
                    msg.sender == owner ||
                    msg.sender == nftAddress
                );
                // We are using this boolean method to make sure that even if one fails it will still work
                bool res = nftAddress.send(this.balance);
            }
        
            /// @dev Creates and begins a new auction.
            /// @param _tokenId - ID of token to auction, sender must be owner.
            /// @param _startingPrice - Price of item (in wei) at beginning of auction.
            /// @param _endingPrice - Price of item (in wei) at end of auction.
            /// @param _duration - Length of time to move between starting
            ///  price and ending price (in seconds).
            /// @param _seller - Seller, if not the message sender
            function createAuction(
                uint256 _tokenId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                address _seller
            )
                external
                whenNotPaused
            {
                // Sanity check that no inputs overflow how many bits we've allocated
                // to store them in the auction struct.
                require(_startingPrice == uint256(uint128(_startingPrice)));
                require(_endingPrice == uint256(uint128(_endingPrice)));
                require(_duration == uint256(uint64(_duration)));
        
                require(_owns(msg.sender, _tokenId));
                _escrow(msg.sender, _tokenId);
                Auction memory auction = Auction(
                    _seller,
                    uint128(_startingPrice),
                    uint128(_endingPrice),
                    uint64(_duration),
                    uint64(now)
                );
                _addAuction(_tokenId, auction);
            }
        
            /// @dev Bids on an open auction, completing the auction and transferring
            ///  ownership of the NFT if enough Ether is supplied.
            /// @param _tokenId - ID of token to bid on.
            function bid(uint256 _tokenId)
                external
                payable
                whenNotPaused
            {
                // _bid will throw if the bid or funds transfer fails
                _bid(_tokenId, msg.value);
                _transfer(msg.sender, _tokenId);
            }
        
            /// @dev Cancels an auction that hasn't been won yet.
            ///  Returns the NFT to original owner.
            /// @notice This is a state-modifying function that can
            ///  be called while the contract is paused.
            /// @param _tokenId - ID of token on auction
            function cancelAuction(uint256 _tokenId)
                external
            {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                address seller = auction.seller;
                require(msg.sender == seller);
                _cancelAuction(_tokenId, seller);
            }
        
            /// @dev Cancels an auction when the contract is paused.
            ///  Only the owner may do this, and NFTs are returned to
            ///  the seller. This should only be used in emergencies.
            /// @param _tokenId - ID of the NFT on auction to cancel.
            function cancelAuctionWhenPaused(uint256 _tokenId)
                whenPaused
                onlyOwner
                external
            {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                _cancelAuction(_tokenId, auction.seller);
            }
        
            /// @dev Returns auction info for an NFT on auction.
            /// @param _tokenId - ID of NFT on auction.
            function getAuction(uint256 _tokenId)
                external
                view
                returns
            (
                address seller,
                uint256 startingPrice,
                uint256 endingPrice,
                uint256 duration,
                uint256 startedAt
            ) {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                return (
                    auction.seller,
                    auction.startingPrice,
                    auction.endingPrice,
                    auction.duration,
                    auction.startedAt
                );
            }
        
            /// @dev Returns the current price of an auction.
            /// @param _tokenId - ID of the token price we are checking.
            function getCurrentPrice(uint256 _tokenId)
                external
                view
                returns (uint256)
            {
                Auction storage auction = tokenIdToAuction[_tokenId];
                require(_isOnAuction(auction));
                return _currentPrice(auction);
            }
        
        }
        
        
        /// @title Clock auction modified for sale of kitties
        /// @notice We omit a fallback function to prevent accidental sends to this contract.
        contract SaleClockAuction is ClockAuction {
        
            // @dev Sanity check that allows us to ensure that we are pointing to the
            //  right auction in our setSaleAuctionAddress() call.
            bool public isSaleClockAuction = true;
            
            // Tracks last 5 sale price of gen0 kitty sales
            uint256 public gen0SaleCount;
            uint256[5] public lastGen0SalePrices;
        
            // Delegate constructor
            function SaleClockAuction(address _nftAddr, uint256 _cut) public
                ClockAuction(_nftAddr, _cut) {}
        
            /// @dev Creates and begins a new auction.
            /// @param _tokenId - ID of token to auction, sender must be owner.
            /// @param _startingPrice - Price of item (in wei) at beginning of auction.
            /// @param _endingPrice - Price of item (in wei) at end of auction.
            /// @param _duration - Length of auction (in seconds).
            /// @param _seller - Seller, if not the message sender
            function createAuction(
                uint256 _tokenId,
                uint256 _startingPrice,
                uint256 _endingPrice,
                uint256 _duration,
                address _seller
            )
                external
            {
                // Sanity check that no inputs overflow how many bits we've allocated
                // to store them in the auction struct.
                require(_startingPrice == uint256(uint128(_startingPrice)));
                require(_endingPrice == uint256(uint128(_endingPrice)));
                require(_duration == uint256(uint64(_duration)));
        
                require(msg.sender == address(nonFungibleContract));
                _escrow(_seller, _tokenId);
                Auction memory auction = Auction(
                    _seller,
                    uint128(_startingPrice),
                    uint128(_endingPrice),
                    uint64(_duration),
                    uint64(now)
                );
                _addAuction(_tokenId, auction);
            }
        
            /// @dev Updates lastSalePrice if seller is the nft contract
            /// Otherwise, works the same as default bid method.
            function bid(uint256 _tokenId)
                external
                payable
            {
                // _bid verifies token ID size
                address seller = tokenIdToAuction[_tokenId].seller;
                uint256 price = _bid(_tokenId, msg.value);
                _transfer(msg.sender, _tokenId);
        
                // If not a gen0 auction, exit
                if (seller == address(nonFungibleContract)) {
                    // Track gen0 sale prices
                    lastGen0SalePrices[gen0SaleCount % 5] = price;
                    gen0SaleCount++;
                }
            }
        
            function averageGen0SalePrice() external view returns (uint256) {
                uint256 sum = 0;
                for (uint256 i = 0; i < 5; i++) {
                    sum += lastGen0SalePrices[i];
                }
                return sum / 5;
            }
        
        }

        File 4 of 4: CloneableWallet
        // File: contracts/ERC721/ERC721ReceiverDraft.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ERC721ReceiverDraft
        /// @dev Interface for any contract that wants to support safeTransfers from
        ///  ERC721 asset contracts.
        /// @dev Note: this is the interface defined from 
        ///  https://github.com/ethereum/EIPs/commit/2bddd126def7c046e1e62408dc2b51bdd9e57f0f
        ///  to https://github.com/ethereum/EIPs/commit/27788131d5975daacbab607076f2ee04624f9dbb 
        ///  and is not the final interface.
        ///  Due to the extended period of time this revision was specified in the draft,
        ///  we are supporting both this and the newer (final) interface in order to be 
        ///  compatible with any ERC721 implementations that may have used this interface.
        contract ERC721ReceiverDraft {
        
            /// @dev Magic value to be returned upon successful reception of an NFT
            ///  Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
            ///  which can be also obtained as `ERC721ReceiverDraft(0).onERC721Received.selector`
            /// @dev see https://github.com/ethereum/EIPs/commit/2bddd126def7c046e1e62408dc2b51bdd9e57f0f
            bytes4 internal constant ERC721_RECEIVED_DRAFT = 0xf0b9e5ba;
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            ///  after a `transfer`. This function MAY throw to revert and reject the
            ///  transfer. This function MUST use 50,000 gas or less. Return of other
            ///  than the magic value MUST result in the transaction being reverted.
            ///  Note: the contract address is always the message sender.
            /// @param _from The sending address 
            /// @param _tokenId The NFT identifier which is being transfered
            /// @param data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
            ///  unless throwing
            function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
        }
        
        // File: contracts/ERC721/ERC721ReceiverFinal.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ERC721ReceiverFinal
        /// @notice Interface for any contract that wants to support safeTransfers from
        ///  ERC721 asset contracts.
        ///  @dev Note: this is the final interface as defined at http://erc721.org
        contract ERC721ReceiverFinal {
        
            /// @dev Magic value to be returned upon successful reception of an NFT
            ///  Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
            ///  which can be also obtained as `ERC721ReceiverFinal(0).onERC721Received.selector`
            /// @dev see https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v1.12.0/contracts/token/ERC721/ERC721Receiver.sol
            bytes4 internal constant ERC721_RECEIVED_FINAL = 0x150b7a02;
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            /// after a `safetransfer`. This function MAY throw to revert and reject the
            /// transfer. Return of other than the magic value MUST result in the
            /// transaction being reverted.
            /// Note: the contract address is always the message sender.
            /// @param _operator The address which called `safeTransferFrom` function
            /// @param _from The address which previously owned the token
            /// @param _tokenId The NFT identifier which is being transferred
            /// @param _data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
            function onERC721Received(
                address _operator,
                address _from,
                uint256 _tokenId,
                bytes _data
            )
            public
                returns (bytes4);
        }
        
        // File: contracts/ERC721/ERC721Receivable.sol
        
        pragma solidity ^0.4.24;
        
        
        
        /// @title ERC721Receivable handles the reception of ERC721 tokens
        ///  See ERC721 specification
        /// @author Christopher Scott
        /// @dev These functions are public, and could be called by anyone, even in the case
        ///  where no NFTs have been transferred. Since it's not a reliable source of
        ///  truth about ERC721 tokens being transferred, we save the gas and don't
        ///  bother emitting a (potentially spurious) event as found in 
        ///  https://github.com/OpenZeppelin/openzeppelin-solidity/blob/5471fc808a17342d738853d7bf3e9e5ef3108074/contracts/mocks/ERC721ReceiverMock.sol
        contract ERC721Receivable is ERC721ReceiverDraft, ERC721ReceiverFinal {
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            ///  after a `transfer`. This function MAY throw to revert and reject the
            ///  transfer. This function MUST use 50,000 gas or less. Return of other
            ///  than the magic value MUST result in the transaction being reverted.
            ///  Note: the contract address is always the message sender.
            /// @param _from The sending address 
            /// @param _tokenId The NFT identifier which is being transfered
            /// @param data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
            ///  unless throwing
            function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4) {
                _from;
                _tokenId;
                data;
        
                // emit ERC721Received(_operator, _from, _tokenId, _data, gasleft());
        
                return ERC721_RECEIVED_DRAFT;
            }
        
            /// @notice Handle the receipt of an NFT
            /// @dev The ERC721 smart contract calls this function on the recipient
            /// after a `safetransfer`. This function MAY throw to revert and reject the
            /// transfer. Return of other than the magic value MUST result in the
            /// transaction being reverted.
            /// Note: the contract address is always the message sender.
            /// @param _operator The address which called `safeTransferFrom` function
            /// @param _from The address which previously owned the token
            /// @param _tokenId The NFT identifier which is being transferred
            /// @param _data Additional data with no specified format
            /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
            function onERC721Received(
                address _operator,
                address _from,
                uint256 _tokenId,
                bytes _data
            )
                public
                returns(bytes4)
            {
                _operator;
                _from;
                _tokenId;
                _data;
        
                // emit ERC721Received(_operator, _from, _tokenId, _data, gasleft());
        
                return ERC721_RECEIVED_FINAL;
            }
        
        }
        
        // File: contracts/ERC223/ERC223Receiver.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ERC223Receiver ensures we are ERC223 compatible
        /// @author Christopher Scott
        contract ERC223Receiver {
            
            bytes4 public constant ERC223_ID = 0xc0ee0b8a;
        
            struct TKN {
                address sender;
                uint value;
                bytes data;
                bytes4 sig;
            }
            
            /// @notice tokenFallback is called from an ERC223 compatible contract
            /// @param _from the address from which the token was sent
            /// @param _value the amount of tokens sent
            /// @param _data the data sent with the transaction
            function tokenFallback(address _from, uint _value, bytes _data) public pure {
                _from;
                _value;
                _data;
            //   TKN memory tkn;
            //   tkn.sender = _from;
            //   tkn.value = _value;
            //   tkn.data = _data;
            //   uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
            //   tkn.sig = bytes4(u);
              
              /* tkn variable is analogue of msg variable of Ether transaction
              *  tkn.sender is person who initiated this token transaction   (analogue of msg.sender)
              *  tkn.value the number of tokens that were sent   (analogue of msg.value)
              *  tkn.data is data of token transaction   (analogue of msg.data)
              *  tkn.sig is 4 bytes signature of function
              *  if data of token transaction is a function execution
              */
        
            }
        }
        
        // File: contracts/ERC1271/ERC1271.sol
        
        pragma solidity ^0.4.24;
        
        contract ERC1271 {
        
            /// @dev bytes4(keccak256("isValidSignature(bytes32,bytes)")
            bytes4 internal constant ERC1271_VALIDSIGNATURE = 0x1626ba7e;
        
            /// @dev Should return whether the signature provided is valid for the provided data
            /// @param hash 32-byte hash of the data that is signed
            /// @param _signature Signature byte array associated with _data
            ///  MUST return the bytes4 magic value 0x1626ba7e when function passes.
            ///  MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
            ///  MUST allow external calls
            function isValidSignature(
                bytes32 hash, 
                bytes _signature)
                external
                view 
                returns (bytes4);
        }
        
        // File: contracts/ECDSA.sol
        
        pragma solidity ^0.4.24;
        
        
        /// @title ECDSA is a library that contains useful methods for working with ECDSA signatures
        library ECDSA {
        
            /// @notice Extracts the r, s, and v components from the `sigData` field starting from the `offset`
            /// @dev Note: does not do any bounds checking on the arguments!
            /// @param sigData the signature data; could be 1 or more packed signatures.
            /// @param offset the offset in sigData from which to start unpacking the signature components.
            function extractSignature(bytes sigData, uint256 offset) internal pure returns  (bytes32 r, bytes32 s, uint8 v) {
                // Divide the signature in r, s and v variables
                // ecrecover takes the signature parameters, and the only way to get them
                // currently is to use assembly.
                // solium-disable-next-line security/no-inline-assembly
                assembly {
                     let dataPointer := add(sigData, offset)
                     r := mload(add(dataPointer, 0x20))
                     s := mload(add(dataPointer, 0x40))
                     v := byte(0, mload(add(dataPointer, 0x60)))
                }
            
                return (r, s, v);
            }
        }
        
        // File: contracts/Wallet/CoreWallet.sol
        
        pragma solidity ^0.4.24;
        
        
        
        
        
        
        /// @title Core Wallet
        /// @notice A basic smart contract wallet with cosigner functionality. The notion of "cosigner" is
        ///  the simplest possible multisig solution, a two-of-two signature scheme. It devolves nicely
        ///  to "one-of-one" (i.e. singlesig) by simply having the cosigner set to the same value as
        ///  the main signer.
        /// 
        ///  Most "advanced" functionality (deadman's switch, multiday recovery flows, blacklisting, etc)
        ///  can be implemented externally to this smart contract, either as an additional smart contract
        ///  (which can be tracked as a signer without cosigner, or as a cosigner) or as an off-chain flow
        ///  using a public/private key pair as cosigner. Of course, the basic cosigning functionality could
        ///  also be implemented in this way, but (A) the complexity and gas cost of two-of-two multisig (as
        ///  implemented here) is negligable even if you don't need the cosigner functionality, and
        ///  (B) two-of-two multisig (as implemented here) handles a lot of really common use cases, most
        ///  notably third-party gas payment and off-chain blacklisting and fraud detection.
        contract CoreWallet is ERC721Receivable, ERC223Receiver, ERC1271  {
        
            using ECDSA for bytes;
        
            /// @notice We require that presigned transactions use the EIP-191 signing format.
            ///  See that EIP for more info: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-191.md
            byte public constant EIP191_VERSION_DATA = byte(0);
            byte public constant EIP191_PREFIX = byte(0x19);
        
            /// @notice This is the version of the contract.
            string public constant VERSION = "1.0.0";
        
            /// @notice A pre-shifted "1", used to increment the authVersion, so we can "prepend"
            ///  the authVersion to an address (for lookups in the authorizations mapping)
            ///  by using the '+' operator (which is cheaper than a shift and a mask). See the
            ///  comment on the `authorizations` variable for how this is used.
            uint256 public constant AUTH_VERSION_INCREMENTOR = (1 << 160);
            
            /// @notice The pre-shifted authVersion (to get the current authVersion as an integer,
            ///  shift this value right by 160 bits). Starts as `1 << 160` (`AUTH_VERSION_INCREMENTOR`)
            ///  See the comment on the `authorizations` variable for how this is used.
            uint256 public authVersion;
        
            /// @notice A mapping containing all of the addresses that are currently authorized to manage
            ///  the assets owned by this wallet.
            ///
            ///  The keys in this mapping are authorized addresses with a version number prepended,
            ///  like so: (authVersion,96)(address,160). The current authVersion MUST BE included
            ///  for each look-up; this allows us to effectively clear the entire mapping of its
            ///  contents merely by incrementing the authVersion variable. (This is important for
            ///  the emergencyRecovery() method.) Inspired by https://ethereum.stackexchange.com/a/42540
            ///
            ///  The values in this mapping are 256bit words, whose lower 20 bytes constitute "cosigners"
            ///  for each address. If an address maps to itself, then that address is said to have no cosigner.
            ///
            ///  The upper 12 bytes are reserved for future meta-data purposes.  The meta-data could refer
            ///  to the key (authorized address) or the value (cosigner) of the mapping.
            ///
            ///  Addresses that map to a non-zero cosigner in the current authVersion are called
            ///  "authorized addresses".
            mapping(uint256 => uint256) public authorizations;
        
            /// @notice A per-key nonce value, incremented each time a transaction is processed with that key.
            ///  Used for replay prevention. The nonce value in the transaction must exactly equal the current
            ///  nonce value in the wallet for that key. (This mirrors the way Ethereum's transaction nonce works.)
            mapping(address => uint256) public nonces;
        
            /// @notice A special address that is authorized to call `emergencyRecovery()`. That function
            ///  resets ALL authorization for this wallet, and must therefore be treated with utmost security.
            ///  Reasonable choices for recoveryAddress include:
            ///       - the address of a private key in cold storage
            ///       - a physically secured hardware wallet
            ///       - a multisig smart contract, possibly with a time-delayed challenge period
            ///       - the zero address, if you like performing without a safety net ;-)
            address public recoveryAddress;
        
            /// @notice Used to track whether or not this contract instance has been initialized. This
            ///  is necessary since it is common for this wallet smart contract to be used as the "library
            ///  code" for an clone contract. See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md
            ///  for more information about clone contracts.
            bool public initialized;
            
            /// @notice Used to decorate methods that can only be called directly by the recovery address.
            modifier onlyRecoveryAddress() {
                require(msg.sender == recoveryAddress, "sender must be recovery address");
                _;
            }
        
            /// @notice Used to decorate the `init` function so this can only be called one time. Necessary
            ///  since this contract will often be used as a "clone". (See above.)
            modifier onlyOnce() {
                require(!initialized, "must not already be initialized");
                initialized = true;
                _;
            }
            
            /// @notice Used to decorate methods that can only be called indirectly via an `invoke()` method.
            ///  In practice, it means that those methods can only be called by a signer/cosigner
            ///  pair that is currently authorized. Theoretically, we could factor out the
            ///  signer/cosigner verification code and use it explicitly in this modifier, but that
            ///  would either result in duplicated code, or additional overhead in the invoke()
            ///  calls (due to the stack manipulation for calling into the shared verification function).
            ///  Doing it this way makes calling the administration functions more expensive (since they
            ///  go through a explict call() instead of just branching within the contract), but it
            ///  makes invoke() more efficient. We assume that invoke() will be used much, much more often
            ///  than any of the administration functions.
            modifier onlyInvoked() {
                require(msg.sender == address(this), "must be called from `invoke()`");
                _;
            }
            
            /// @notice Emitted when an authorized address is added, removed, or modified. When an
            ///  authorized address is removed ("deauthorized"), cosigner will be address(0) in
            ///  this event.
            ///  
            ///  NOTE: When emergencyRecovery() is called, all existing addresses are deauthorized
            ///  WITHOUT Authorized(addr, 0) being emitted. If you are keeping an off-chain mirror of
            ///  authorized addresses, you must also watch for EmergencyRecovery events.
            /// @dev hash is 0xf5a7f4fb8a92356e8c8c4ae7ac3589908381450500a7e2fd08c95600021ee889
            /// @param authorizedAddress the address to authorize or unauthorize
            /// @param cosigner the 2-of-2 signatory (optional).
            event Authorized(address authorizedAddress, uint256 cosigner);
            
            /// @notice Emitted when an emergency recovery has been performed. If this event is fired,
            ///  ALL previously authorized addresses have been deauthorized and the only authorized
            ///  address is the authorizedAddress indicated in this event.
            /// @dev hash is 0xe12d0bbeb1d06d7a728031056557140afac35616f594ef4be227b5b172a604b5
            /// @param authorizedAddress the new authorized address
            /// @param cosigner the cosigning address for `authorizedAddress`
            event EmergencyRecovery(address authorizedAddress, uint256 cosigner);
        
            /// @notice Emitted when the recovery address changes. Either (but not both) of the
            ///  parameters may be zero.
            /// @dev hash is 0x568ab3dedd6121f0385e007e641e74e1f49d0fa69cab2957b0b07c4c7de5abb6
            /// @param previousRecoveryAddress the previous recovery address
            /// @param newRecoveryAddress the new recovery address
            event RecoveryAddressChanged(address previousRecoveryAddress, address newRecoveryAddress);
        
            /// @dev Emitted when this contract receives a non-zero amount ether via the fallback function
            ///  (i.e. This event is not fired if the contract receives ether as part of a method invocation)
            /// @param from the address which sent you ether
            /// @param value the amount of ether sent
            event Received(address from, uint value);
        
            /// @notice Emitted whenever a transaction is processed sucessfully from this wallet. Includes
            ///  both simple send ether transactions, as well as other smart contract invocations.
            /// @dev hash is 0x101214446435ebbb29893f3348e3aae5ea070b63037a3df346d09d3396a34aee
            /// @param hash The hash of the entire operation set. 0 is returned when emitted from `invoke0()`.
            /// @param result A bitfield of the results of the operations. A bit of 0 means success, and 1 means failure.
            /// @param numOperations A count of the number of operations processed
            event InvocationSuccess(
                bytes32 hash,
                uint256 result,
                uint256 numOperations
            );
        
            /// @notice The shared initialization code used to setup the contract state regardless of whether or
            ///  not the clone pattern is being used.
            /// @param _authorizedAddress the initial authorized address, must not be zero!
            /// @param _cosigner the initial cosigning address for `_authorizedAddress`, can be equal to `_authorizedAddress`
            /// @param _recoveryAddress the initial recovery address for the wallet, can be address(0)
            function init(address _authorizedAddress, uint256 _cosigner, address _recoveryAddress) public onlyOnce {
                require(_authorizedAddress != _recoveryAddress, "Do not use the recovery address as an authorized address.");
                require(address(_cosigner) != _recoveryAddress, "Do not use the recovery address as a cosigner.");
                require(_authorizedAddress != address(0), "Authorized addresses must not be zero.");
                require(address(_cosigner) != address(0), "Initial cosigner must not be zero.");
                
                recoveryAddress = _recoveryAddress;
                // set initial authorization value
                authVersion = AUTH_VERSION_INCREMENTOR;
                // add initial authorized address
                authorizations[authVersion + uint256(_authorizedAddress)] = _cosigner;
                
                emit Authorized(_authorizedAddress, _cosigner);
            }
        
            /// @notice The fallback function, invoked whenever we receive a transaction that doesn't call any of our
            ///  named functions. In particular, this method is called when we are the target of a simple send transaction
            ///  or when someone tries to call a method that we don't implement. We assume that a "correct" invocation of
            ///  this method only occurs when someone is trying to transfer ether to this wallet, in which case and the
            ///  `msg.data.length` will be 0.
            ///
            ///  NOTE: Some smart contracts send 0 eth as part of a more complex
            ///  operation (-cough- CryptoKitties -cough-) ; ideally, we'd `require(msg.value > 0)` here, but to work
            ///  with those kinds of smart contracts, we accept zero sends and just skip logging in that case.
            function() external payable {
                require(msg.data.length == 0, "Invalid transaction.");
                if (msg.value > 0) {
                    emit Received(msg.sender, msg.value);
                }
            }
            
            /// @notice Configures an authorizable address. Can be used in four ways:
            ///   - Add a new signer/cosigner pair (cosigner must be non-zero)
            ///   - Set or change the cosigner for an existing signer (if authorizedAddress != cosigner)
            ///   - Remove the cosigning requirement for a signer (if authorizedAddress == cosigner)
            ///   - Remove a signer (if cosigner == address(0))
            /// @dev Must be called through `invoke()`
            /// @param _authorizedAddress the address to configure authorization
            /// @param _cosigner the corresponding cosigning address
            function setAuthorized(address _authorizedAddress, uint256 _cosigner) external onlyInvoked {
                // TODO: Allowing a signer to remove itself is actually pretty terrible; it could result in the user
                //  removing their only available authorized key. Unfortunately, due to how the invocation forwarding
                //  works, we don't actually _know_ which signer was used to call this method, so there's no easy way
                //  to prevent this.
                
                // TODO: Allowing the backup key to be set as an authorized address bypasses the recovery mechanisms.
                //  Dapper can prevent this with offchain logic and the cosigner, but it would be nice to have 
                //  this enforced by the smart contract logic itself.
                
                require(_authorizedAddress != address(0), "Authorized addresses must not be zero.");
                require(_authorizedAddress != recoveryAddress, "Do not use the recovery address as an authorized address.");
                require(address(_cosigner) == address(0) || address(_cosigner) != recoveryAddress, "Do not use the recovery address as a cosigner.");
         
                authorizations[authVersion + uint256(_authorizedAddress)] = _cosigner;
                emit Authorized(_authorizedAddress, _cosigner);
            }
            
            /// @notice Performs an emergency recovery operation, removing all existing authorizations and setting
            ///  a sole new authorized address with optional cosigner. THIS IS A SCORCHED EARTH SOLUTION, and great
            ///  care should be taken to ensure that this method is never called unless it is a last resort. See the
            ///  comments above about the proper kinds of addresses to use as the recoveryAddress to ensure this method
            ///  is not trivially abused.
            /// @param _authorizedAddress the new and sole authorized address
            /// @param _cosigner the corresponding cosigner address, can be equal to _authorizedAddress
            function emergencyRecovery(address _authorizedAddress, uint256 _cosigner) external onlyRecoveryAddress {
                require(_authorizedAddress != address(0), "Authorized addresses must not be zero.");
                require(_authorizedAddress != recoveryAddress, "Do not use the recovery address as an authorized address.");
                require(address(_cosigner) != address(0), "The cosigner must not be zero.");
        
                // Incrementing the authVersion number effectively erases the authorizations mapping. See the comments
                // on the authorizations variable (above) for more information.
                authVersion += AUTH_VERSION_INCREMENTOR;
        
                // Store the new signer/cosigner pair as the only remaining authorized address
                authorizations[authVersion + uint256(_authorizedAddress)] = _cosigner;
                emit EmergencyRecovery(_authorizedAddress, _cosigner);
            }
        
            /// @notice Sets the recovery address, which can be zero (indicating that no recovery is possible)
            ///  Can be updated by any authorized address. This address should be set with GREAT CARE. See the
            ///  comments above about the proper kinds of addresses to use as the recoveryAddress to ensure this
            ///  mechanism is not trivially abused.
            /// @dev Must be called through `invoke()`
            /// @param _recoveryAddress the new recovery address
            function setRecoveryAddress(address _recoveryAddress) external onlyInvoked {
                require(
                    address(authorizations[authVersion + uint256(_recoveryAddress)]) == address(0),
                    "Do not use an authorized address as the recovery address."
                );
         
                address previous = recoveryAddress;
                recoveryAddress = _recoveryAddress;
        
                emit RecoveryAddressChanged(previous, recoveryAddress);
            }
        
            /// @notice Allows ANY caller to recover gas by way of deleting old authorization keys after
            ///  a recovery operation. Anyone can call this method to delete the old unused storage and
            ///  get themselves a bit of gas refund in the bargin.
            /// @dev keys must be known to caller or else nothing is refunded
            /// @param _version the version of the mapping which you want to delete (unshifted)
            /// @param _keys the authorization keys to delete 
            function recoverGas(uint256 _version, address[] _keys) external {
                // TODO: should this be 0xffffffffffffffffffffffff ?
                require(_version > 0 && _version < 0xffffffff, "Invalid version number.");
                
                uint256 shiftedVersion = _version << 160;
        
                require(shiftedVersion < authVersion, "You can only recover gas from expired authVersions.");
        
                for (uint256 i = 0; i < _keys.length; ++i) {
                    delete(authorizations[shiftedVersion + uint256(_keys[i])]);
                }
            }
        
            /// @notice Should return whether the signature provided is valid for the provided data
            ///  See https://github.com/ethereum/EIPs/issues/1271
            /// @dev This function meets the following conditions as per the EIP:
            ///  MUST return the bytes4 magic value `0x1626ba7e` when function passes.
            ///  MUST NOT modify state (using `STATICCALL` for solc < 0.5, `view` modifier for solc > 0.5)
            ///  MUST allow external calls
            /// @param hash A 32 byte hash of the signed data.  The actual hash that is hashed however is the
            ///  the following tightly packed arguments: `0x19,0x0,wallet_address,hash`
            /// @param _signature Signature byte array associated with `_data`
            /// @return Magic value `0x1626ba7e` upon success, 0 otherwise.
            function isValidSignature(bytes32 hash, bytes _signature) external view returns (bytes4) {
                
                // We 'hash the hash' for the following reasons:
                // 1. `hash` is not the hash of an Ethereum transaction
                // 2. signature must target this wallet to avoid replaying the signature for another wallet
                // with the same key
                // 3. Gnosis does something similar: 
                // https://github.com/gnosis/safe-contracts/blob/102e632d051650b7c4b0a822123f449beaf95aed/contracts/GnosisSafe.sol
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    hash));
        
                bytes32[2] memory r;
                bytes32[2] memory s;
                uint8[2] memory v;
                address signer;
                address cosigner;
        
                // extract 1 or 2 signatures depending on length
                if (_signature.length == 65) {
                    (r[0], s[0], v[0]) = _signature.extractSignature(0);
                    signer = ecrecover(operationHash, v[0], r[0], s[0]);
                    cosigner = signer;
                } else if (_signature.length == 130) {
                    (r[0], s[0], v[0]) = _signature.extractSignature(0);
                    (r[1], s[1], v[1]) = _signature.extractSignature(65);
                    signer = ecrecover(operationHash, v[0], r[0], s[0]);
                    cosigner = ecrecover(operationHash, v[1], r[1], s[1]);
                } else {
                    return 0;
                }
                    
                // check for valid signature
                if (signer == address(0)) {
                    return 0;
                }
        
                // check for valid signature
                if (cosigner == address(0)) {
                    return 0;
                }
        
                // check to see if this is an authorized key
                if (address(authorizations[authVersion + uint256(signer)]) != cosigner) {
                    return 0;
                }
        
                return ERC1271_VALIDSIGNATURE;
            }
        
            /// @notice Query if a contract implements an interface
            /// @param interfaceID The interface identifier, as specified in ERC-165
            /// @dev Interface identification is specified in ERC-165. This function
            ///  uses less than 30,000 gas.
            /// @return `true` if the contract implements `interfaceID` and
            ///  `interfaceID` is not 0xffffffff, `false` otherwise
            function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
                // I am not sure why the linter is complaining about the whitespace
                return
                    interfaceID == this.supportsInterface.selector || // ERC165
                    interfaceID == ERC721_RECEIVED_FINAL || // ERC721 Final
                    interfaceID == ERC721_RECEIVED_DRAFT || // ERC721 Draft
                    interfaceID == ERC223_ID || // ERC223
                    interfaceID == ERC1271_VALIDSIGNATURE; // ERC1271
            }
        
            /// @notice A version of `invoke()` that has no explicit signatures, and uses msg.sender
            ///  as both the signer and cosigner. Will only succeed if `msg.sender` is an authorized
            ///  signer for this wallet, with no cosigner, saving transaction size and gas in that case.
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke0(bytes data) external {
                // The nonce doesn't need to be incremented for transactions that don't include explicit signatures;
                // the built-in nonce of the native ethereum transaction will protect against replay attacks, and we
                // can save the gas that would be spent updating the nonce variable
        
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner)
                require(address(authorizations[authVersion + uint256(msg.sender)]) == msg.sender, "Invalid authorization.");
        
                internalInvoke(0, data);
            }
        
            /// @notice A version of `invoke()` that has one explicit signature which is used to derive the authorized
            ///  address. Uses `msg.sender` as the cosigner.
            /// @param v the v value for the signature; see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
            /// @param r the r value for the signature
            /// @param s the s value for the signature
            /// @param nonce the nonce value for the signature
            /// @param authorizedAddress the address of the authorization key; this is used here so that cosigner signatures are interchangeable
            ///  between this function and `invoke2()`
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke1CosignerSends(uint8 v, bytes32 r, bytes32 s, uint256 nonce, address authorizedAddress, bytes data) external {
                // check signature version
                require(v == 27 || v == 28, "Invalid signature version.");
        
                // calculate hash
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    nonce,
                    authorizedAddress,
                    data));
         
                // recover signer
                address signer = ecrecover(operationHash, v, r, s);
        
                // check for valid signature
                require(signer != address(0), "Invalid signature.");
        
                // check nonce
                require(nonce == nonces[signer], "must use correct nonce");
        
                // check signer
                require(signer == authorizedAddress, "authorized addresses must be equal");
        
                // Get cosigner
                address requiredCosigner = address(authorizations[authVersion + uint256(signer)]);
                
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
                // if the actual cosigner matches the required cosigner.
                require(requiredCosigner == signer || requiredCosigner == msg.sender, "Invalid authorization.");
        
                // increment nonce to prevent replay attacks
                nonces[signer] = nonce + 1;
        
                // call internal function
                internalInvoke(operationHash, data);
            }
        
            /// @notice A version of `invoke()` that has one explicit signature which is used to derive the cosigning
            ///  address. Uses `msg.sender` as the authorized address.
            /// @param v the v value for the signature; see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
            /// @param r the r value for the signature
            /// @param s the s value for the signature
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke1SignerSends(uint8 v, bytes32 r, bytes32 s, bytes data) external {
                // check signature version
                // `ecrecover` will infact return 0 if given invalid
                // so perhaps this check is redundant
                require(v == 27 || v == 28, "Invalid signature version.");
                
                uint256 nonce = nonces[msg.sender];
        
                // calculate hash
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    nonce,
                    msg.sender,
                    data));
         
                // recover cosigner
                address cosigner = ecrecover(operationHash, v, r, s);
                
                // check for valid signature
                require(cosigner != address(0), "Invalid signature.");
        
                // Get required cosigner
                address requiredCosigner = address(authorizations[authVersion + uint256(msg.sender)]);
                
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
                // if the actual cosigner matches the required cosigner.
                require(requiredCosigner == cosigner || requiredCosigner == msg.sender, "Invalid authorization.");
        
                // increment nonce to prevent replay attacks
                nonces[msg.sender] = nonce + 1;
         
                internalInvoke(operationHash, data);
            }
        
            /// @notice A version of `invoke()` that has two explicit signatures, the first is used to derive the authorized
            ///  address, the second to derive the cosigner. The value of `msg.sender` is ignored.
            /// @param v the v values for the signatures
            /// @param r the r values for the signatures
            /// @param s the s values for the signatures
            /// @param nonce the nonce value for the signature
            /// @param authorizedAddress the address of the signer; forces the signature to be unique and tied to the signers nonce 
            /// @param data The data containing the transactions to be invoked; see internalInvoke for details.
            function invoke2(uint8[2] v, bytes32[2] r, bytes32[2] s, uint256 nonce, address authorizedAddress, bytes data) external {
                // check signature versions
                // `ecrecover` will infact return 0 if given invalid
                // so perhaps these checks are redundant
                require(v[0] == 27 || v[0] == 28, "invalid signature version v[0]");
                require(v[1] == 27 || v[1] == 28, "invalid signature version v[1]");
         
                bytes32 operationHash = keccak256(
                    abi.encodePacked(
                    EIP191_PREFIX,
                    EIP191_VERSION_DATA,
                    this,
                    nonce,
                    authorizedAddress,
                    data));
         
                // recover signer and cosigner
                address signer = ecrecover(operationHash, v[0], r[0], s[0]);
                address cosigner = ecrecover(operationHash, v[1], r[1], s[1]);
        
                // check for valid signatures
                require(signer != address(0), "Invalid signature for signer.");
                require(cosigner != address(0), "Invalid signature for cosigner.");
        
                // check signer address
                require(signer == authorizedAddress, "authorized addresses must be equal");
        
                // check nonces
                require(nonce == nonces[signer], "must use correct nonce for signer");
        
                // Get Mapping
                address requiredCosigner = address(authorizations[authVersion + uint256(signer)]);
                
                // The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
                // if the actual cosigner matches the required cosigner.
                require(requiredCosigner == signer || requiredCosigner == cosigner, "Invalid authorization.");
        
                // increment nonce to prevent replay attacks
                nonces[signer]++;
        
                internalInvoke(operationHash, data);
            }
        
            /// @dev Internal invoke call, 
            /// @param operationHash The hash of the operation
            /// @param data The data to send to the `call()` operation
            ///  The data is prefixed with a global 1 byte revert flag
            ///  If revert is 1, then any revert from a `call()` operation is rethrown.
            ///  Otherwise, the error is recorded in the `result` field of the `InvocationSuccess` event.
            ///  Immediately following the revert byte (no padding), the data format is then is a series
            ///  of 1 or more tightly packed tuples:
            ///  `<target(20),amount(32),datalength(32),data>`
            ///  If `datalength == 0`, the data field must be omitted
            function internalInvoke(bytes32 operationHash, bytes data) internal {
                // keep track of the number of operations processed
                uint256 numOps;
                // keep track of the result of each operation as a bit
                uint256 result;
        
                // We need to store a reference to this string as a variable so we can use it as an argument to
                // the revert call from assembly.
                string memory invalidLengthMessage = "Data field too short";
                string memory callFailed = "Call failed";
        
                // At an absolute minimum, the data field must be at least 85 bytes
                // <revert(1), to_address(20), value(32), data_length(32)>
                require(data.length >= 85, invalidLengthMessage);
        
                // Forward the call onto its actual target. Note that the target address can be `self` here, which is
                // actually the required flow for modifying the configuration of the authorized keys and recovery address.
                //
                // The assembly code below loads data directly from memory, so the enclosing function must be marked `internal`
                assembly {
                    // A cursor pointing to the revert flag, starts after the length field of the data object
                    let memPtr := add(data, 32)
        
                    // The revert flag is the leftmost byte from memPtr
                    let revertFlag := byte(0, mload(memPtr))
        
                    // A pointer to the end of the data object
                    let endPtr := add(memPtr, mload(data))
        
                    // Now, memPtr is a cursor pointing to the begining of the current sub-operation
                    memPtr := add(memPtr, 1)
        
                    // Loop through data, parsing out the various sub-operations
                    for { } lt(memPtr, endPtr) { } {
                        // Load the length of the call data of the current operation
                        // 52 = to(20) + value(32)
                        let len := mload(add(memPtr, 52))
                        
                        // Compute a pointer to the end of the current operation
                        // 84 = to(20) + value(32) + size(32)
                        let opEnd := add(len, add(memPtr, 84))
        
                        // Bail if the current operation's data overruns the end of the enclosing data buffer
                        // NOTE: Comment out this bit of code and uncomment the next section if you want
                        // the solidity-coverage tool to work.
                        // See https://github.com/sc-forks/solidity-coverage/issues/287
                        if gt(opEnd, endPtr) {
                            // The computed end of this operation goes past the end of the data buffer. Not good!
                            revert(add(invalidLengthMessage, 32), mload(invalidLengthMessage))
                        }
                        // NOTE: Code that is compatible with solidity-coverage
                        // switch gt(opEnd, endPtr)
                        // case 1 {
                        //     revert(add(invalidLengthMessage, 32), mload(invalidLengthMessage))
                        // }
        
                        // This line of code packs in a lot of functionality!
                        //  - load the target address from memPtr, the address is only 20-bytes but mload always grabs 32-bytes,
                        //    so we have to divide the result by 2^96 to effectively right-shift by 12 bytes.
                        //  - load the value field, stored at memPtr+20
                        //  - pass a pointer to the call data, stored at memPtr+84
                        //  - use the previously loaded len field as the size of the call data
                        //  - make the call (passing all remaining gas to the child call)
                        //  - check the result (0 == reverted)
                        if eq(0, call(gas, div(mload(memPtr), exp(2, 96)), mload(add(memPtr, 20)), add(memPtr, 84), len, 0, 0)) {
                            
                            switch revertFlag
                            case 1 {
                                revert(add(callFailed, 32), mload(callFailed))
                            }
                            default {
                                // mark this operation as failed
                                // create the appropriate bit, 'or' with previous
                                result := or(result, exp(2, numOps))
                            }
                        }
        
                        // increment our counter
                        numOps := add(numOps, 1)
                     
                        // Update mem pointer to point to the next sub-operation
                        memPtr := opEnd
                    }
                }
        
                // emit single event upon success
                emit InvocationSuccess(operationHash, result, numOps);
            }
        }
        
        // File: contracts/Wallet/CloneableWallet.sol
        
        pragma solidity ^0.4.24;
        
        
        
        /// @title Cloneable Wallet
        /// @notice This contract represents a complete but non working wallet.  
        ///  It is meant to be deployed and serve as the contract that you clone
        ///  in an EIP 1167 clone setup.
        /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md
        /// @dev Currently, we are seeing approximatley 933 gas overhead for using
        ///  the clone wallet; use `FullWallet` if you think users will overtake
        ///  the transaction threshold over the lifetime of the wallet.
        contract CloneableWallet is CoreWallet {
        
            /// @dev An empty constructor that deploys a NON-FUNCTIONAL version
            ///  of `CoreWallet`
            constructor () public {
                initialized = true;
            }
        }