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