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