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