Project setup (#4)
|
@ -0,0 +1,11 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.sol]
|
||||
indent_size = 4
|
|
@ -0,0 +1,5 @@
|
|||
DEPLOYMENT_ACCOUNT_PRIVATE_KEY=67..14
|
||||
DEPLOYMENT_GAS_LIMIT_EXTRA=0.2
|
||||
FOREIGN_DEPLOYMENT_GAS_PRICE=1000000000
|
||||
FOREIGN_RPC_URL=https://sokol.poa.network
|
||||
KITTIES_AMOUNT=1
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"extends": ["plugin:node/recommended", "airbnb-base", "plugin:prettier/recommended"],
|
||||
"plugins": ["node"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "off",
|
||||
"consistent-return": "off",
|
||||
"no-console": "off",
|
||||
"no-plusplus": "off",
|
||||
"no-use-before-define": ["error", { "functions": false }],
|
||||
"node/no-unpublished-require": "off"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
node_modules
|
||||
.idea
|
||||
build
|
||||
flats
|
||||
.env
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"printWidth": 120,
|
||||
"bracketSpacing": true,
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.sol",
|
||||
"options": {
|
||||
"singleQuote": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
116
LICENSE.md
|
@ -1,116 +0,0 @@
|
|||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>
|
|
@ -1,607 +0,0 @@
|
|||
/**
|
||||
* Note: For learning and education copied from
|
||||
* https://etherscan.io/address/0xb1690c08e213a35ed9bab7b318de14420fb57d8c#code
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.11;
|
||||
|
||||
|
||||
/**
|
||||
* @title Ownable
|
||||
* @dev The Ownable contract has an owner address, and provides basic authorization control
|
||||
* functions, this simplifies the implementation of "user permissions".
|
||||
*/
|
||||
contract Ownable {
|
||||
address public owner;
|
||||
|
||||
|
||||
/**
|
||||
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
|
||||
* account.
|
||||
*/
|
||||
function Ownable() {
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @dev Throws if called by any account other than the owner.
|
||||
*/
|
||||
modifier onlyOwner() {
|
||||
require(msg.sender == owner);
|
||||
_;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @dev Allows the current owner to transfer control of the contract to a newOwner.
|
||||
* @param newOwner The address to transfer ownership to.
|
||||
*/
|
||||
function transferOwnership(address newOwner) onlyOwner {
|
||||
if (newOwner != address(0)) {
|
||||
owner = newOwner;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
|
||||
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
|
||||
contract ERC721 {
|
||||
// Required methods
|
||||
function totalSupply() public view returns (uint256 total);
|
||||
function balanceOf(address _owner) public view returns (uint256 balance);
|
||||
function ownerOf(uint256 _tokenId) external view returns (address owner);
|
||||
function approve(address _to, uint256 _tokenId) external;
|
||||
function transfer(address _to, uint256 _tokenId) external;
|
||||
function transferFrom(address _from, address _to, uint256 _tokenId) external;
|
||||
|
||||
// Events
|
||||
event Transfer(address from, address to, uint256 tokenId);
|
||||
event Approval(address owner, address approved, uint256 tokenId);
|
||||
|
||||
// Optional
|
||||
// function name() public view returns (string name);
|
||||
// function symbol() public view returns (string symbol);
|
||||
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
|
||||
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
|
||||
|
||||
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
|
||||
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// @title Auction Core
|
||||
/// @dev Contains models, variables, and internal methods for the auction.
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
contract ClockAuctionBase {
|
||||
|
||||
// Represents an auction on an NFT
|
||||
struct Auction {
|
||||
// Current owner of NFT
|
||||
address seller;
|
||||
// Price (in wei) at beginning of auction
|
||||
uint128 startingPrice;
|
||||
// Price (in wei) at end of auction
|
||||
uint128 endingPrice;
|
||||
// Duration (in seconds) of auction
|
||||
uint64 duration;
|
||||
// Time when auction started
|
||||
// NOTE: 0 if this auction has been concluded
|
||||
uint64 startedAt;
|
||||
}
|
||||
|
||||
// Reference to contract tracking NFT ownership
|
||||
ERC721 public nonFungibleContract;
|
||||
|
||||
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
|
||||
// Values 0-10,000 map to 0%-100%
|
||||
uint256 public ownerCut;
|
||||
|
||||
// Map from token ID to their corresponding auction.
|
||||
mapping (uint256 => Auction) tokenIdToAuction;
|
||||
|
||||
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
|
||||
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
|
||||
event AuctionCancelled(uint256 tokenId);
|
||||
|
||||
/// @dev Returns true if the claimant owns the token.
|
||||
/// @param _claimant - Address claiming to own the token.
|
||||
/// @param _tokenId - ID of token whose ownership to verify.
|
||||
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
|
||||
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
|
||||
}
|
||||
|
||||
/// @dev Escrows the NFT, assigning ownership to this contract.
|
||||
/// Throws if the escrow fails.
|
||||
/// @param _owner - Current owner address of token to escrow.
|
||||
/// @param _tokenId - ID of token whose approval to verify.
|
||||
function _escrow(address _owner, uint256 _tokenId) internal {
|
||||
// it will throw if transfer fails
|
||||
nonFungibleContract.transferFrom(_owner, this, _tokenId);
|
||||
}
|
||||
|
||||
/// @dev Transfers an NFT owned by this contract to another address.
|
||||
/// Returns true if the transfer succeeds.
|
||||
/// @param _receiver - Address to transfer NFT to.
|
||||
/// @param _tokenId - ID of token to transfer.
|
||||
function _transfer(address _receiver, uint256 _tokenId) internal {
|
||||
// it will throw if transfer fails
|
||||
nonFungibleContract.transfer(_receiver, _tokenId);
|
||||
}
|
||||
|
||||
/// @dev Adds an auction to the list of open auctions. Also fires the
|
||||
/// AuctionCreated event.
|
||||
/// @param _tokenId The ID of the token to be put on auction.
|
||||
/// @param _auction Auction to add.
|
||||
function _addAuction(uint256 _tokenId, Auction _auction) internal {
|
||||
// Require that all auctions have a duration of
|
||||
// at least one minute. (Keeps our math from getting hairy!)
|
||||
require(_auction.duration >= 1 minutes);
|
||||
|
||||
tokenIdToAuction[_tokenId] = _auction;
|
||||
|
||||
AuctionCreated(
|
||||
uint256(_tokenId),
|
||||
uint256(_auction.startingPrice),
|
||||
uint256(_auction.endingPrice),
|
||||
uint256(_auction.duration)
|
||||
);
|
||||
}
|
||||
|
||||
/// @dev Cancels an auction unconditionally.
|
||||
function _cancelAuction(uint256 _tokenId, address _seller) internal {
|
||||
_removeAuction(_tokenId);
|
||||
_transfer(_seller, _tokenId);
|
||||
AuctionCancelled(_tokenId);
|
||||
}
|
||||
|
||||
/// @dev Computes the price and transfers winnings.
|
||||
/// Does NOT transfer ownership of token.
|
||||
function _bid(uint256 _tokenId, uint256 _bidAmount)
|
||||
internal
|
||||
returns (uint256)
|
||||
{
|
||||
// Get a reference to the auction struct
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
|
||||
// Explicitly check that this auction is currently live.
|
||||
// (Because of how Ethereum mappings work, we can't just count
|
||||
// on the lookup above failing. An invalid _tokenId will just
|
||||
// return an auction object that is all zeros.)
|
||||
require(_isOnAuction(auction));
|
||||
|
||||
// Check that the bid is greater than or equal to the current price
|
||||
uint256 price = _currentPrice(auction);
|
||||
require(_bidAmount >= price);
|
||||
|
||||
// Grab a reference to the seller before the auction struct
|
||||
// gets deleted.
|
||||
address seller = auction.seller;
|
||||
|
||||
// The bid is good! Remove the auction before sending the fees
|
||||
// to the sender so we can't have a reentrancy attack.
|
||||
_removeAuction(_tokenId);
|
||||
|
||||
// Transfer proceeds to seller (if there are any!)
|
||||
if (price > 0) {
|
||||
// Calculate the auctioneer's cut.
|
||||
// (NOTE: _computeCut() is guaranteed to return a
|
||||
// value <= price, so this subtraction can't go negative.)
|
||||
uint256 auctioneerCut = _computeCut(price);
|
||||
uint256 sellerProceeds = price - auctioneerCut;
|
||||
|
||||
// NOTE: Doing a transfer() in the middle of a complex
|
||||
// method like this is generally discouraged because of
|
||||
// reentrancy attacks and DoS attacks if the seller is
|
||||
// a contract with an invalid fallback function. We explicitly
|
||||
// guard against reentrancy attacks by removing the auction
|
||||
// before calling transfer(), and the only thing the seller
|
||||
// can DoS is the sale of their own asset! (And if it's an
|
||||
// accident, they can call cancelAuction(). )
|
||||
seller.transfer(sellerProceeds);
|
||||
}
|
||||
|
||||
// Calculate any excess funds included with the bid. If the excess
|
||||
// is anything worth worrying about, transfer it back to bidder.
|
||||
// NOTE: We checked above that the bid amount is greater than or
|
||||
// equal to the price so this cannot underflow.
|
||||
uint256 bidExcess = _bidAmount - price;
|
||||
|
||||
// Return the funds. Similar to the previous transfer, this is
|
||||
// not susceptible to a re-entry attack because the auction is
|
||||
// removed before any transfers occur.
|
||||
msg.sender.transfer(bidExcess);
|
||||
|
||||
// Tell the world!
|
||||
AuctionSuccessful(_tokenId, price, msg.sender);
|
||||
|
||||
return price;
|
||||
}
|
||||
|
||||
/// @dev Removes an auction from the list of open auctions.
|
||||
/// @param _tokenId - ID of NFT on auction.
|
||||
function _removeAuction(uint256 _tokenId) internal {
|
||||
delete tokenIdToAuction[_tokenId];
|
||||
}
|
||||
|
||||
/// @dev Returns true if the NFT is on auction.
|
||||
/// @param _auction - Auction to check.
|
||||
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
|
||||
return (_auction.startedAt > 0);
|
||||
}
|
||||
|
||||
/// @dev Returns current price of an NFT on auction. Broken into two
|
||||
/// functions (this one, that computes the duration from the auction
|
||||
/// structure, and the other that does the price computation) so we
|
||||
/// can easily test that the price computation works correctly.
|
||||
function _currentPrice(Auction storage _auction)
|
||||
internal
|
||||
view
|
||||
returns (uint256)
|
||||
{
|
||||
uint256 secondsPassed = 0;
|
||||
|
||||
// A bit of insurance against negative values (or wraparound).
|
||||
// Probably not necessary (since Ethereum guarnatees that the
|
||||
// now variable doesn't ever go backwards).
|
||||
if (now > _auction.startedAt) {
|
||||
secondsPassed = now - _auction.startedAt;
|
||||
}
|
||||
|
||||
return _computeCurrentPrice(
|
||||
_auction.startingPrice,
|
||||
_auction.endingPrice,
|
||||
_auction.duration,
|
||||
secondsPassed
|
||||
);
|
||||
}
|
||||
|
||||
/// @dev Computes the current price of an auction. Factored out
|
||||
/// from _currentPrice so we can run extensive unit tests.
|
||||
/// When testing, make this function public and turn on
|
||||
/// `Current price computation` test suite.
|
||||
function _computeCurrentPrice(
|
||||
uint256 _startingPrice,
|
||||
uint256 _endingPrice,
|
||||
uint256 _duration,
|
||||
uint256 _secondsPassed
|
||||
)
|
||||
internal
|
||||
pure
|
||||
returns (uint256)
|
||||
{
|
||||
// NOTE: We don't use SafeMath (or similar) in this function because
|
||||
// all of our public functions carefully cap the maximum values for
|
||||
// time (at 64-bits) and currency (at 128-bits). _duration is
|
||||
// also known to be non-zero (see the require() statement in
|
||||
// _addAuction())
|
||||
if (_secondsPassed >= _duration) {
|
||||
// We've reached the end of the dynamic pricing portion
|
||||
// of the auction, just return the end price.
|
||||
return _endingPrice;
|
||||
} else {
|
||||
// Starting price can be higher than ending price (and often is!), so
|
||||
// this delta can be negative.
|
||||
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
|
||||
|
||||
// This multiplication can't overflow, _secondsPassed will easily fit within
|
||||
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
|
||||
// will always fit within 256-bits.
|
||||
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
|
||||
|
||||
// currentPriceChange can be negative, but if so, will have a magnitude
|
||||
// less that _startingPrice. Thus, this result will always end up positive.
|
||||
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
|
||||
|
||||
return uint256(currentPrice);
|
||||
}
|
||||
}
|
||||
|
||||
/// @dev Computes owner's cut of a sale.
|
||||
/// @param _price - Sale price of NFT.
|
||||
function _computeCut(uint256 _price) internal view returns (uint256) {
|
||||
// NOTE: We don't use SafeMath (or similar) in this function because
|
||||
// all of our entry functions carefully cap the maximum values for
|
||||
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
|
||||
// statement in the ClockAuction constructor). The result of this
|
||||
// function is always guaranteed to be <= _price.
|
||||
return _price * ownerCut / 10000;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @title Pausable
|
||||
* @dev Base contract which allows children to implement an emergency stop mechanism.
|
||||
*/
|
||||
contract Pausable is Ownable {
|
||||
event Pause();
|
||||
event Unpause();
|
||||
|
||||
bool public paused = false;
|
||||
|
||||
|
||||
/**
|
||||
* @dev modifier to allow actions only when the contract IS paused
|
||||
*/
|
||||
modifier whenNotPaused() {
|
||||
require(!paused);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev modifier to allow actions only when the contract IS NOT paused
|
||||
*/
|
||||
modifier whenPaused {
|
||||
require(paused);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev called by the owner to pause, triggers stopped state
|
||||
*/
|
||||
function pause() onlyOwner whenNotPaused returns (bool) {
|
||||
paused = true;
|
||||
Pause();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev called by the owner to unpause, returns to normal state
|
||||
*/
|
||||
function unpause() onlyOwner whenPaused returns (bool) {
|
||||
paused = false;
|
||||
Unpause();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// @title Clock auction for non-fungible tokens.
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
contract ClockAuction is Pausable, ClockAuctionBase {
|
||||
|
||||
/// @dev The ERC-165 interface signature for ERC-721.
|
||||
/// Ref: https://github.com/ethereum/EIPs/issues/165
|
||||
/// Ref: https://github.com/ethereum/EIPs/issues/721
|
||||
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
|
||||
|
||||
/// @dev Constructor creates a reference to the NFT ownership contract
|
||||
/// and verifies the owner cut is in the valid range.
|
||||
/// @param _nftAddress - address of a deployed contract implementing
|
||||
/// the Nonfungible Interface.
|
||||
/// @param _cut - percent cut the owner takes on each auction, must be
|
||||
/// between 0-10,000.
|
||||
function ClockAuction(address _nftAddress, uint256 _cut) public {
|
||||
require(_cut <= 10000);
|
||||
ownerCut = _cut;
|
||||
|
||||
ERC721 candidateContract = ERC721(_nftAddress);
|
||||
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
|
||||
nonFungibleContract = candidateContract;
|
||||
}
|
||||
|
||||
/// @dev Remove all Ether from the contract, which is the owner's cuts
|
||||
/// as well as any Ether sent directly to the contract address.
|
||||
/// Always transfers to the NFT contract, but can be called either by
|
||||
/// the owner or the NFT contract.
|
||||
function withdrawBalance() external {
|
||||
address nftAddress = address(nonFungibleContract);
|
||||
|
||||
require(
|
||||
msg.sender == owner ||
|
||||
msg.sender == nftAddress
|
||||
);
|
||||
// We are using this boolean method to make sure that even if one fails it will still work
|
||||
bool res = nftAddress.send(this.balance);
|
||||
}
|
||||
|
||||
/// @dev Creates and begins a new auction.
|
||||
/// @param _tokenId - ID of token to auction, sender must be owner.
|
||||
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
|
||||
/// @param _endingPrice - Price of item (in wei) at end of auction.
|
||||
/// @param _duration - Length of time to move between starting
|
||||
/// price and ending price (in seconds).
|
||||
/// @param _seller - Seller, if not the message sender
|
||||
function createAuction(
|
||||
uint256 _tokenId,
|
||||
uint256 _startingPrice,
|
||||
uint256 _endingPrice,
|
||||
uint256 _duration,
|
||||
address _seller
|
||||
)
|
||||
external
|
||||
whenNotPaused
|
||||
{
|
||||
// Sanity check that no inputs overflow how many bits we've allocated
|
||||
// to store them in the auction struct.
|
||||
require(_startingPrice == uint256(uint128(_startingPrice)));
|
||||
require(_endingPrice == uint256(uint128(_endingPrice)));
|
||||
require(_duration == uint256(uint64(_duration)));
|
||||
|
||||
require(_owns(msg.sender, _tokenId));
|
||||
_escrow(msg.sender, _tokenId);
|
||||
Auction memory auction = Auction(
|
||||
_seller,
|
||||
uint128(_startingPrice),
|
||||
uint128(_endingPrice),
|
||||
uint64(_duration),
|
||||
uint64(now)
|
||||
);
|
||||
_addAuction(_tokenId, auction);
|
||||
}
|
||||
|
||||
/// @dev Bids on an open auction, completing the auction and transferring
|
||||
/// ownership of the NFT if enough Ether is supplied.
|
||||
/// @param _tokenId - ID of token to bid on.
|
||||
function bid(uint256 _tokenId)
|
||||
external
|
||||
payable
|
||||
whenNotPaused
|
||||
{
|
||||
// _bid will throw if the bid or funds transfer fails
|
||||
_bid(_tokenId, msg.value);
|
||||
_transfer(msg.sender, _tokenId);
|
||||
}
|
||||
|
||||
/// @dev Cancels an auction that hasn't been won yet.
|
||||
/// Returns the NFT to original owner.
|
||||
/// @notice This is a state-modifying function that can
|
||||
/// be called while the contract is paused.
|
||||
/// @param _tokenId - ID of token on auction
|
||||
function cancelAuction(uint256 _tokenId)
|
||||
external
|
||||
{
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
address seller = auction.seller;
|
||||
require(msg.sender == seller);
|
||||
_cancelAuction(_tokenId, seller);
|
||||
}
|
||||
|
||||
/// @dev Cancels an auction when the contract is paused.
|
||||
/// Only the owner may do this, and NFTs are returned to
|
||||
/// the seller. This should only be used in emergencies.
|
||||
/// @param _tokenId - ID of the NFT on auction to cancel.
|
||||
function cancelAuctionWhenPaused(uint256 _tokenId)
|
||||
whenPaused
|
||||
onlyOwner
|
||||
external
|
||||
{
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
_cancelAuction(_tokenId, auction.seller);
|
||||
}
|
||||
|
||||
/// @dev Returns auction info for an NFT on auction.
|
||||
/// @param _tokenId - ID of NFT on auction.
|
||||
function getAuction(uint256 _tokenId)
|
||||
external
|
||||
view
|
||||
returns
|
||||
(
|
||||
address seller,
|
||||
uint256 startingPrice,
|
||||
uint256 endingPrice,
|
||||
uint256 duration,
|
||||
uint256 startedAt
|
||||
) {
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
return (
|
||||
auction.seller,
|
||||
auction.startingPrice,
|
||||
auction.endingPrice,
|
||||
auction.duration,
|
||||
auction.startedAt
|
||||
);
|
||||
}
|
||||
|
||||
/// @dev Returns the current price of an auction.
|
||||
/// @param _tokenId - ID of the token price we are checking.
|
||||
function getCurrentPrice(uint256 _tokenId)
|
||||
external
|
||||
view
|
||||
returns (uint256)
|
||||
{
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
return _currentPrice(auction);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// @title Clock auction modified for sale of kitties
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
contract SaleClockAuction is ClockAuction {
|
||||
|
||||
// @dev Sanity check that allows us to ensure that we are pointing to the
|
||||
// right auction in our setSaleAuctionAddress() call.
|
||||
bool public isSaleClockAuction = true;
|
||||
|
||||
// Tracks last 5 sale price of gen0 kitty sales
|
||||
uint256 public gen0SaleCount;
|
||||
uint256[5] public lastGen0SalePrices;
|
||||
|
||||
// Delegate constructor
|
||||
function SaleClockAuction(address _nftAddr, uint256 _cut) public
|
||||
ClockAuction(_nftAddr, _cut) {}
|
||||
|
||||
/// @dev Creates and begins a new auction.
|
||||
/// @param _tokenId - ID of token to auction, sender must be owner.
|
||||
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
|
||||
/// @param _endingPrice - Price of item (in wei) at end of auction.
|
||||
/// @param _duration - Length of auction (in seconds).
|
||||
/// @param _seller - Seller, if not the message sender
|
||||
function createAuction(
|
||||
uint256 _tokenId,
|
||||
uint256 _startingPrice,
|
||||
uint256 _endingPrice,
|
||||
uint256 _duration,
|
||||
address _seller
|
||||
)
|
||||
external
|
||||
{
|
||||
// Sanity check that no inputs overflow how many bits we've allocated
|
||||
// to store them in the auction struct.
|
||||
require(_startingPrice == uint256(uint128(_startingPrice)));
|
||||
require(_endingPrice == uint256(uint128(_endingPrice)));
|
||||
require(_duration == uint256(uint64(_duration)));
|
||||
|
||||
require(msg.sender == address(nonFungibleContract));
|
||||
_escrow(_seller, _tokenId);
|
||||
Auction memory auction = Auction(
|
||||
_seller,
|
||||
uint128(_startingPrice),
|
||||
uint128(_endingPrice),
|
||||
uint64(_duration),
|
||||
uint64(now)
|
||||
);
|
||||
_addAuction(_tokenId, auction);
|
||||
}
|
||||
|
||||
/// @dev Updates lastSalePrice if seller is the nft contract
|
||||
/// Otherwise, works the same as default bid method.
|
||||
function bid(uint256 _tokenId)
|
||||
external
|
||||
payable
|
||||
{
|
||||
// _bid verifies token ID size
|
||||
address seller = tokenIdToAuction[_tokenId].seller;
|
||||
uint256 price = _bid(_tokenId, msg.value);
|
||||
_transfer(msg.sender, _tokenId);
|
||||
|
||||
// If not a gen0 auction, exit
|
||||
if (seller == address(nonFungibleContract)) {
|
||||
// Track gen0 sale prices
|
||||
lastGen0SalePrices[gen0SaleCount % 5] = price;
|
||||
gen0SaleCount++;
|
||||
}
|
||||
}
|
||||
|
||||
function averageGen0SalePrice() external view returns (uint256) {
|
||||
uint256 sum = 0;
|
||||
for (uint256 i = 0; i < 5; i++) {
|
||||
sum += lastGen0SalePrices[i];
|
||||
}
|
||||
return sum / 5;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,594 +0,0 @@
|
|||
/**
|
||||
* Note: For learning and education copied from
|
||||
* https://etherscan.io/address/0xc7af99fe5513eb6710e6d5f44f9989da40f27f26#code
|
||||
*/
|
||||
|
||||
pragma solidity ^0.4.11;
|
||||
|
||||
|
||||
/**
|
||||
* @title Ownable
|
||||
* @dev The Ownable contract has an owner address, and provides basic authorization control
|
||||
* functions, this simplifies the implementation of "user permissions".
|
||||
*/
|
||||
contract Ownable {
|
||||
address public owner;
|
||||
|
||||
|
||||
/**
|
||||
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
|
||||
* account.
|
||||
*/
|
||||
function Ownable() {
|
||||
owner = msg.sender;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @dev Throws if called by any account other than the owner.
|
||||
*/
|
||||
modifier onlyOwner() {
|
||||
require(msg.sender == owner);
|
||||
_;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @dev Allows the current owner to transfer control of the contract to a newOwner.
|
||||
* @param newOwner The address to transfer ownership to.
|
||||
*/
|
||||
function transferOwnership(address newOwner) onlyOwner {
|
||||
if (newOwner != address(0)) {
|
||||
owner = newOwner;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
|
||||
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
|
||||
contract ERC721 {
|
||||
// Required methods
|
||||
function totalSupply() public view returns (uint256 total);
|
||||
function balanceOf(address _owner) public view returns (uint256 balance);
|
||||
function ownerOf(uint256 _tokenId) external view returns (address owner);
|
||||
function approve(address _to, uint256 _tokenId) external;
|
||||
function transfer(address _to, uint256 _tokenId) external;
|
||||
function transferFrom(address _from, address _to, uint256 _tokenId) external;
|
||||
|
||||
// Events
|
||||
event Transfer(address from, address to, uint256 tokenId);
|
||||
event Approval(address owner, address approved, uint256 tokenId);
|
||||
|
||||
// Optional
|
||||
// function name() public view returns (string name);
|
||||
// function symbol() public view returns (string symbol);
|
||||
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
|
||||
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
|
||||
|
||||
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
|
||||
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// @title Auction Core
|
||||
/// @dev Contains models, variables, and internal methods for the auction.
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
contract ClockAuctionBase {
|
||||
|
||||
// Represents an auction on an NFT
|
||||
struct Auction {
|
||||
// Current owner of NFT
|
||||
address seller;
|
||||
// Price (in wei) at beginning of auction
|
||||
uint128 startingPrice;
|
||||
// Price (in wei) at end of auction
|
||||
uint128 endingPrice;
|
||||
// Duration (in seconds) of auction
|
||||
uint64 duration;
|
||||
// Time when auction started
|
||||
// NOTE: 0 if this auction has been concluded
|
||||
uint64 startedAt;
|
||||
}
|
||||
|
||||
// Reference to contract tracking NFT ownership
|
||||
ERC721 public nonFungibleContract;
|
||||
|
||||
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
|
||||
// Values 0-10,000 map to 0%-100%
|
||||
uint256 public ownerCut;
|
||||
|
||||
// Map from token ID to their corresponding auction.
|
||||
mapping (uint256 => Auction) tokenIdToAuction;
|
||||
|
||||
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
|
||||
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
|
||||
event AuctionCancelled(uint256 tokenId);
|
||||
|
||||
/// @dev Returns true if the claimant owns the token.
|
||||
/// @param _claimant - Address claiming to own the token.
|
||||
/// @param _tokenId - ID of token whose ownership to verify.
|
||||
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
|
||||
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
|
||||
}
|
||||
|
||||
/// @dev Escrows the NFT, assigning ownership to this contract.
|
||||
/// Throws if the escrow fails.
|
||||
/// @param _owner - Current owner address of token to escrow.
|
||||
/// @param _tokenId - ID of token whose approval to verify.
|
||||
function _escrow(address _owner, uint256 _tokenId) internal {
|
||||
// it will throw if transfer fails
|
||||
nonFungibleContract.transferFrom(_owner, this, _tokenId);
|
||||
}
|
||||
|
||||
/// @dev Transfers an NFT owned by this contract to another address.
|
||||
/// Returns true if the transfer succeeds.
|
||||
/// @param _receiver - Address to transfer NFT to.
|
||||
/// @param _tokenId - ID of token to transfer.
|
||||
function _transfer(address _receiver, uint256 _tokenId) internal {
|
||||
// it will throw if transfer fails
|
||||
nonFungibleContract.transfer(_receiver, _tokenId);
|
||||
}
|
||||
|
||||
/// @dev Adds an auction to the list of open auctions. Also fires the
|
||||
/// AuctionCreated event.
|
||||
/// @param _tokenId The ID of the token to be put on auction.
|
||||
/// @param _auction Auction to add.
|
||||
function _addAuction(uint256 _tokenId, Auction _auction) internal {
|
||||
// Require that all auctions have a duration of
|
||||
// at least one minute. (Keeps our math from getting hairy!)
|
||||
require(_auction.duration >= 1 minutes);
|
||||
|
||||
tokenIdToAuction[_tokenId] = _auction;
|
||||
|
||||
AuctionCreated(
|
||||
uint256(_tokenId),
|
||||
uint256(_auction.startingPrice),
|
||||
uint256(_auction.endingPrice),
|
||||
uint256(_auction.duration)
|
||||
);
|
||||
}
|
||||
|
||||
/// @dev Cancels an auction unconditionally.
|
||||
function _cancelAuction(uint256 _tokenId, address _seller) internal {
|
||||
_removeAuction(_tokenId);
|
||||
_transfer(_seller, _tokenId);
|
||||
AuctionCancelled(_tokenId);
|
||||
}
|
||||
|
||||
/// @dev Computes the price and transfers winnings.
|
||||
/// Does NOT transfer ownership of token.
|
||||
function _bid(uint256 _tokenId, uint256 _bidAmount)
|
||||
internal
|
||||
returns (uint256)
|
||||
{
|
||||
// Get a reference to the auction struct
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
|
||||
// Explicitly check that this auction is currently live.
|
||||
// (Because of how Ethereum mappings work, we can't just count
|
||||
// on the lookup above failing. An invalid _tokenId will just
|
||||
// return an auction object that is all zeros.)
|
||||
require(_isOnAuction(auction));
|
||||
|
||||
// Check that the bid is greater than or equal to the current price
|
||||
uint256 price = _currentPrice(auction);
|
||||
require(_bidAmount >= price);
|
||||
|
||||
// Grab a reference to the seller before the auction struct
|
||||
// gets deleted.
|
||||
address seller = auction.seller;
|
||||
|
||||
// The bid is good! Remove the auction before sending the fees
|
||||
// to the sender so we can't have a reentrancy attack.
|
||||
_removeAuction(_tokenId);
|
||||
|
||||
// Transfer proceeds to seller (if there are any!)
|
||||
if (price > 0) {
|
||||
// Calculate the auctioneer's cut.
|
||||
// (NOTE: _computeCut() is guaranteed to return a
|
||||
// value <= price, so this subtraction can't go negative.)
|
||||
uint256 auctioneerCut = _computeCut(price);
|
||||
uint256 sellerProceeds = price - auctioneerCut;
|
||||
|
||||
// NOTE: Doing a transfer() in the middle of a complex
|
||||
// method like this is generally discouraged because of
|
||||
// reentrancy attacks and DoS attacks if the seller is
|
||||
// a contract with an invalid fallback function. We explicitly
|
||||
// guard against reentrancy attacks by removing the auction
|
||||
// before calling transfer(), and the only thing the seller
|
||||
// can DoS is the sale of their own asset! (And if it's an
|
||||
// accident, they can call cancelAuction(). )
|
||||
seller.transfer(sellerProceeds);
|
||||
}
|
||||
|
||||
// Calculate any excess funds included with the bid. If the excess
|
||||
// is anything worth worrying about, transfer it back to bidder.
|
||||
// NOTE: We checked above that the bid amount is greater than or
|
||||
// equal to the price so this cannot underflow.
|
||||
uint256 bidExcess = _bidAmount - price;
|
||||
|
||||
// Return the funds. Similar to the previous transfer, this is
|
||||
// not susceptible to a re-entry attack because the auction is
|
||||
// removed before any transfers occur.
|
||||
msg.sender.transfer(bidExcess);
|
||||
|
||||
// Tell the world!
|
||||
AuctionSuccessful(_tokenId, price, msg.sender);
|
||||
|
||||
return price;
|
||||
}
|
||||
|
||||
/// @dev Removes an auction from the list of open auctions.
|
||||
/// @param _tokenId - ID of NFT on auction.
|
||||
function _removeAuction(uint256 _tokenId) internal {
|
||||
delete tokenIdToAuction[_tokenId];
|
||||
}
|
||||
|
||||
/// @dev Returns true if the NFT is on auction.
|
||||
/// @param _auction - Auction to check.
|
||||
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
|
||||
return (_auction.startedAt > 0);
|
||||
}
|
||||
|
||||
/// @dev Returns current price of an NFT on auction. Broken into two
|
||||
/// functions (this one, that computes the duration from the auction
|
||||
/// structure, and the other that does the price computation) so we
|
||||
/// can easily test that the price computation works correctly.
|
||||
function _currentPrice(Auction storage _auction)
|
||||
internal
|
||||
view
|
||||
returns (uint256)
|
||||
{
|
||||
uint256 secondsPassed = 0;
|
||||
|
||||
// A bit of insurance against negative values (or wraparound).
|
||||
// Probably not necessary (since Ethereum guarnatees that the
|
||||
// now variable doesn't ever go backwards).
|
||||
if (now > _auction.startedAt) {
|
||||
secondsPassed = now - _auction.startedAt;
|
||||
}
|
||||
|
||||
return _computeCurrentPrice(
|
||||
_auction.startingPrice,
|
||||
_auction.endingPrice,
|
||||
_auction.duration,
|
||||
secondsPassed
|
||||
);
|
||||
}
|
||||
|
||||
/// @dev Computes the current price of an auction. Factored out
|
||||
/// from _currentPrice so we can run extensive unit tests.
|
||||
/// When testing, make this function public and turn on
|
||||
/// `Current price computation` test suite.
|
||||
function _computeCurrentPrice(
|
||||
uint256 _startingPrice,
|
||||
uint256 _endingPrice,
|
||||
uint256 _duration,
|
||||
uint256 _secondsPassed
|
||||
)
|
||||
internal
|
||||
pure
|
||||
returns (uint256)
|
||||
{
|
||||
// NOTE: We don't use SafeMath (or similar) in this function because
|
||||
// all of our public functions carefully cap the maximum values for
|
||||
// time (at 64-bits) and currency (at 128-bits). _duration is
|
||||
// also known to be non-zero (see the require() statement in
|
||||
// _addAuction())
|
||||
if (_secondsPassed >= _duration) {
|
||||
// We've reached the end of the dynamic pricing portion
|
||||
// of the auction, just return the end price.
|
||||
return _endingPrice;
|
||||
} else {
|
||||
// Starting price can be higher than ending price (and often is!), so
|
||||
// this delta can be negative.
|
||||
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
|
||||
|
||||
// This multiplication can't overflow, _secondsPassed will easily fit within
|
||||
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
|
||||
// will always fit within 256-bits.
|
||||
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
|
||||
|
||||
// currentPriceChange can be negative, but if so, will have a magnitude
|
||||
// less that _startingPrice. Thus, this result will always end up positive.
|
||||
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
|
||||
|
||||
return uint256(currentPrice);
|
||||
}
|
||||
}
|
||||
|
||||
/// @dev Computes owner's cut of a sale.
|
||||
/// @param _price - Sale price of NFT.
|
||||
function _computeCut(uint256 _price) internal view returns (uint256) {
|
||||
// NOTE: We don't use SafeMath (or similar) in this function because
|
||||
// all of our entry functions carefully cap the maximum values for
|
||||
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
|
||||
// statement in the ClockAuction constructor). The result of this
|
||||
// function is always guaranteed to be <= _price.
|
||||
return _price * ownerCut / 10000;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @title Pausable
|
||||
* @dev Base contract which allows children to implement an emergency stop mechanism.
|
||||
*/
|
||||
contract Pausable is Ownable {
|
||||
event Pause();
|
||||
event Unpause();
|
||||
|
||||
bool public paused = false;
|
||||
|
||||
|
||||
/**
|
||||
* @dev modifier to allow actions only when the contract IS paused
|
||||
*/
|
||||
modifier whenNotPaused() {
|
||||
require(!paused);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev modifier to allow actions only when the contract IS NOT paused
|
||||
*/
|
||||
modifier whenPaused {
|
||||
require(paused);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev called by the owner to pause, triggers stopped state
|
||||
*/
|
||||
function pause() onlyOwner whenNotPaused returns (bool) {
|
||||
paused = true;
|
||||
Pause();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev called by the owner to unpause, returns to normal state
|
||||
*/
|
||||
function unpause() onlyOwner whenPaused returns (bool) {
|
||||
paused = false;
|
||||
Unpause();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// @title Clock auction for non-fungible tokens.
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
contract ClockAuction is Pausable, ClockAuctionBase {
|
||||
|
||||
/// @dev The ERC-165 interface signature for ERC-721.
|
||||
/// Ref: https://github.com/ethereum/EIPs/issues/165
|
||||
/// Ref: https://github.com/ethereum/EIPs/issues/721
|
||||
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
|
||||
|
||||
/// @dev Constructor creates a reference to the NFT ownership contract
|
||||
/// and verifies the owner cut is in the valid range.
|
||||
/// @param _nftAddress - address of a deployed contract implementing
|
||||
/// the Nonfungible Interface.
|
||||
/// @param _cut - percent cut the owner takes on each auction, must be
|
||||
/// between 0-10,000.
|
||||
function ClockAuction(address _nftAddress, uint256 _cut) public {
|
||||
require(_cut <= 10000);
|
||||
ownerCut = _cut;
|
||||
|
||||
ERC721 candidateContract = ERC721(_nftAddress);
|
||||
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
|
||||
nonFungibleContract = candidateContract;
|
||||
}
|
||||
|
||||
/// @dev Remove all Ether from the contract, which is the owner's cuts
|
||||
/// as well as any Ether sent directly to the contract address.
|
||||
/// Always transfers to the NFT contract, but can be called either by
|
||||
/// the owner or the NFT contract.
|
||||
function withdrawBalance() external {
|
||||
address nftAddress = address(nonFungibleContract);
|
||||
|
||||
require(
|
||||
msg.sender == owner ||
|
||||
msg.sender == nftAddress
|
||||
);
|
||||
// We are using this boolean method to make sure that even if one fails it will still work
|
||||
bool res = nftAddress.send(this.balance);
|
||||
}
|
||||
|
||||
/// @dev Creates and begins a new auction.
|
||||
/// @param _tokenId - ID of token to auction, sender must be owner.
|
||||
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
|
||||
/// @param _endingPrice - Price of item (in wei) at end of auction.
|
||||
/// @param _duration - Length of time to move between starting
|
||||
/// price and ending price (in seconds).
|
||||
/// @param _seller - Seller, if not the message sender
|
||||
function createAuction(
|
||||
uint256 _tokenId,
|
||||
uint256 _startingPrice,
|
||||
uint256 _endingPrice,
|
||||
uint256 _duration,
|
||||
address _seller
|
||||
)
|
||||
external
|
||||
whenNotPaused
|
||||
{
|
||||
// Sanity check that no inputs overflow how many bits we've allocated
|
||||
// to store them in the auction struct.
|
||||
require(_startingPrice == uint256(uint128(_startingPrice)));
|
||||
require(_endingPrice == uint256(uint128(_endingPrice)));
|
||||
require(_duration == uint256(uint64(_duration)));
|
||||
|
||||
require(_owns(msg.sender, _tokenId));
|
||||
_escrow(msg.sender, _tokenId);
|
||||
Auction memory auction = Auction(
|
||||
_seller,
|
||||
uint128(_startingPrice),
|
||||
uint128(_endingPrice),
|
||||
uint64(_duration),
|
||||
uint64(now)
|
||||
);
|
||||
_addAuction(_tokenId, auction);
|
||||
}
|
||||
|
||||
/// @dev Bids on an open auction, completing the auction and transferring
|
||||
/// ownership of the NFT if enough Ether is supplied.
|
||||
/// @param _tokenId - ID of token to bid on.
|
||||
function bid(uint256 _tokenId)
|
||||
external
|
||||
payable
|
||||
whenNotPaused
|
||||
{
|
||||
// _bid will throw if the bid or funds transfer fails
|
||||
_bid(_tokenId, msg.value);
|
||||
_transfer(msg.sender, _tokenId);
|
||||
}
|
||||
|
||||
/// @dev Cancels an auction that hasn't been won yet.
|
||||
/// Returns the NFT to original owner.
|
||||
/// @notice This is a state-modifying function that can
|
||||
/// be called while the contract is paused.
|
||||
/// @param _tokenId - ID of token on auction
|
||||
function cancelAuction(uint256 _tokenId)
|
||||
external
|
||||
{
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
address seller = auction.seller;
|
||||
require(msg.sender == seller);
|
||||
_cancelAuction(_tokenId, seller);
|
||||
}
|
||||
|
||||
/// @dev Cancels an auction when the contract is paused.
|
||||
/// Only the owner may do this, and NFTs are returned to
|
||||
/// the seller. This should only be used in emergencies.
|
||||
/// @param _tokenId - ID of the NFT on auction to cancel.
|
||||
function cancelAuctionWhenPaused(uint256 _tokenId)
|
||||
whenPaused
|
||||
onlyOwner
|
||||
external
|
||||
{
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
_cancelAuction(_tokenId, auction.seller);
|
||||
}
|
||||
|
||||
/// @dev Returns auction info for an NFT on auction.
|
||||
/// @param _tokenId - ID of NFT on auction.
|
||||
function getAuction(uint256 _tokenId)
|
||||
external
|
||||
view
|
||||
returns
|
||||
(
|
||||
address seller,
|
||||
uint256 startingPrice,
|
||||
uint256 endingPrice,
|
||||
uint256 duration,
|
||||
uint256 startedAt
|
||||
) {
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
return (
|
||||
auction.seller,
|
||||
auction.startingPrice,
|
||||
auction.endingPrice,
|
||||
auction.duration,
|
||||
auction.startedAt
|
||||
);
|
||||
}
|
||||
|
||||
/// @dev Returns the current price of an auction.
|
||||
/// @param _tokenId - ID of the token price we are checking.
|
||||
function getCurrentPrice(uint256 _tokenId)
|
||||
external
|
||||
view
|
||||
returns (uint256)
|
||||
{
|
||||
Auction storage auction = tokenIdToAuction[_tokenId];
|
||||
require(_isOnAuction(auction));
|
||||
return _currentPrice(auction);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// @title Reverse auction modified for siring
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
contract SiringClockAuction is ClockAuction {
|
||||
|
||||
// @dev Sanity check that allows us to ensure that we are pointing to the
|
||||
// right auction in our setSiringAuctionAddress() call.
|
||||
bool public isSiringClockAuction = true;
|
||||
|
||||
// Delegate constructor
|
||||
function SiringClockAuction(address _nftAddr, uint256 _cut) public
|
||||
ClockAuction(_nftAddr, _cut) {}
|
||||
|
||||
/// @dev Creates and begins a new auction. Since this function is wrapped,
|
||||
/// require sender to be KittyCore contract.
|
||||
/// @param _tokenId - ID of token to auction, sender must be owner.
|
||||
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
|
||||
/// @param _endingPrice - Price of item (in wei) at end of auction.
|
||||
/// @param _duration - Length of auction (in seconds).
|
||||
/// @param _seller - Seller, if not the message sender
|
||||
function createAuction(
|
||||
uint256 _tokenId,
|
||||
uint256 _startingPrice,
|
||||
uint256 _endingPrice,
|
||||
uint256 _duration,
|
||||
address _seller
|
||||
)
|
||||
external
|
||||
{
|
||||
// Sanity check that no inputs overflow how many bits we've allocated
|
||||
// to store them in the auction struct.
|
||||
require(_startingPrice == uint256(uint128(_startingPrice)));
|
||||
require(_endingPrice == uint256(uint128(_endingPrice)));
|
||||
require(_duration == uint256(uint64(_duration)));
|
||||
|
||||
require(msg.sender == address(nonFungibleContract));
|
||||
_escrow(_seller, _tokenId);
|
||||
Auction memory auction = Auction(
|
||||
_seller,
|
||||
uint128(_startingPrice),
|
||||
uint128(_endingPrice),
|
||||
uint64(_duration),
|
||||
uint64(now)
|
||||
);
|
||||
_addAuction(_tokenId, auction);
|
||||
}
|
||||
|
||||
/// @dev Places a bid for siring. Requires the sender
|
||||
/// is the KittyCore contract because all bid methods
|
||||
/// should be wrapped. Also returns the kitty to the
|
||||
/// seller rather than the winner.
|
||||
function bid(uint256 _tokenId)
|
||||
external
|
||||
payable
|
||||
{
|
||||
require(msg.sender == address(nonFungibleContract));
|
||||
address seller = tokenIdToAuction[_tokenId].seller;
|
||||
// _bid checks that token ID is valid and will throw if bid fails
|
||||
_bid(_tokenId, msg.value);
|
||||
// We transfer the kitty back to the seller, the winner will get
|
||||
// the offspring
|
||||
_transfer(seller, _tokenId);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,3 +1,9 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./Pausable.sol";
|
||||
import "./ClockAuctionBase.sol";
|
||||
import "./ERC721.sol";
|
||||
|
||||
/// @title Clock auction for non-fungible tokens.
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
// @title Auction Core
|
||||
pragma solidity 0.4.24;
|
||||
|
||||
import "./ERC721.sol";// @title Auction Core
|
||||
/// @dev Contains models, variables, and internal methods for the auction.
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
pragma solidity 0.4.24;
|
||||
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
|
||||
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
pragma solidity 0.4.24;
|
||||
/// @title The external contract that is responsible for generating metadata for the kitties,
|
||||
/// it has one function that will return the data as bytes.
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
// see https://etherscan.io/address/0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b#code
|
||||
|
||||
|
||||
pragma solidity ^0.4.18;
|
||||
pragma solidity 0.4.24;
|
||||
|
||||
|
||||
/// @title GeneScience implements the trait calculation for new kitties
|
|
@ -1,3 +1,4 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
/// @title SEKRETOOOO
|
||||
contract GeneScienceInterface {
|
|
@ -1,3 +1,5 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
/// @title A facet of KittyCore that manages special access privileges.
|
||||
/// @author Axiom Zen (https://www.axiomzen.co)
|
||||
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
|
|
@ -1,3 +1,8 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./KittyBreeding.sol";
|
||||
import "./SaleClockAuction.sol";
|
||||
import "./SiringClockAuction.sol";
|
||||
/// @title Handles creating auctions for sale and siring of kitties.
|
||||
/// This wrapper of ReverseAuction exists only so that users can create
|
||||
/// auctions with only one transaction.
|
|
@ -1,3 +1,8 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./KittyAccessControl.sol";
|
||||
import "./SaleClockAuction.sol";
|
||||
import "./SiringClockAuction.sol";
|
||||
/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables.
|
||||
/// @author Axiom Zen (https://www.axiomzen.co)
|
||||
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
|
|
@ -1,3 +1,8 @@
|
|||
pragma solidity 0.4.24;
|
||||
import "./KittyOwnership.sol";
|
||||
import "./GeneScienceInterface.sol";
|
||||
import "./KittyBase.sol";
|
||||
|
||||
/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth.
|
||||
/// @author Axiom Zen (https://www.axiomzen.co)
|
||||
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
|
|
@ -1,3 +1,6 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./KittyMinting.sol";
|
||||
/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain.
|
||||
/// @author Axiom Zen (https://www.axiomzen.co)
|
||||
/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost.
|
|
@ -1,3 +1,5 @@
|
|||
pragma solidity 0.4.24;
|
||||
import "./KittyAuction.sol";
|
||||
/// @title all functions related to creating kittens
|
||||
|
||||
contract KittyMinting is KittyAuction {
|
|
@ -1,3 +1,9 @@
|
|||
pragma solidity 0.4.24;
|
||||
import "./KittyBase.sol";
|
||||
import "./ERC721.sol";
|
||||
import "./ERC721Metadata.sol";
|
||||
|
||||
|
||||
/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant.
|
||||
/// @author Axiom Zen (https://www.axiomzen.co)
|
||||
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
|
|
@ -1,3 +1,5 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
/**
|
||||
* @title Ownable
|
||||
* @dev The Ownable contract has an owner address, and provides basic authorization control
|
|
@ -1,3 +1,7 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./Ownable.sol";
|
||||
|
||||
/**
|
||||
* @title Pausable
|
||||
* @dev Base contract which allows children to implement an emergency stop mechanism.
|
|
@ -1,357 +1,357 @@
|
|||
_Code on the Blockchain - Electronic Contract Scripts_
|
||||
|
||||
# CryptoKitties Blockchain Contracts / Services
|
||||
|
||||
|
||||
Note: Almost all of the CryptoKitties contract scripts are open source and documented with inline running commentary. Thanks!
|
||||
The [KittyCore](dl/KittyCore.sol) contract script is about 2 000 lines total.
|
||||
|
||||
The only sooper-sekretoo contract is the [GeneScienceInterface](GeneScienceInterface.sol) with the "magic" mixGenes function
|
||||
that given genes of kitten 1 & 2, return a genetic combination.
|
||||
|
||||
Note: The mixGenes got "reverse-engineered" from the opcode - thanks to Sean Soria (see [CryptoKitties mixGenes Function](https://medium.com/@sean.soria/cryptokitties-mixgenes-function-69207883fc80), Dec 2017) -
|
||||
and is now a "public" sooper-sektretoo.
|
||||
See [`mixGenes.rb`](https://github.com/openblockchains/awesome-cryptokitties/blob/master/genes/mixGenes.rb) for a ruby version
|
||||
or [`mixGenes.py`](https://github.com/openblockchains/awesome-cryptokitties/blob/master/genes/mixGenes.py) for a python version.
|
||||
|
||||
|
||||
|
||||
|
||||
## Source Code
|
||||
|
||||
Etherscan
|
||||
|
||||
- KittyCore (Open Source), see contract address [`0x06012c8cf97bead5deae237070f9587f8e7a266d`](https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code)
|
||||
- GeneScienceInterface (Opcode), see contract address [`0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b`](https://etherscan.io/address/0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b#code)
|
||||
|
||||
> The genetic combination algorithm is kept seperate so we can open-source all of
|
||||
> the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
|
||||
> Don't worry, I'm sure someone will reverse engineer it soon enough!
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
- SaleClockAuction (Open Source), see contract address [`0xb1690c08e213a35ed9bab7b318de14420fb57d8c`](https://etherscan.io/address/0xb1690c08e213a35ed9bab7b318de14420fb57d8c#code)
|
||||
- SiringClockAuction (Open Source), see contract address [`0xc7af99fe5513eb6710e6d5f44f9989da40f27f26`](https://etherscan.io/address/0xc7af99fe5513eb6710e6d5f44f9989da40f27f26#code)
|
||||
|
||||
> The auctions are
|
||||
> seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
|
||||
> them in their own contracts, we can upgrade them without disrupting the main contract that tracks
|
||||
> kitty ownership.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
<!-- add why? why not?
|
||||
|
||||
- CEO, see contract address [`0xaf1e54b359b0897133f437fc961dd16f20c045e1`](https://etherscan.io/address/0xaf1e54b359b0897133f437fc961dd16f20c045e1#code)
|
||||
- CFO, see contract address [`0x2041bb7d8b49f0bde3aa1fa7fb506ac6c539394c`](https://etherscan.io/address/0x2041bb7d8b49f0bde3aa1fa7fb506ac6c539394c#code)
|
||||
- COO, see contract address [`0xa21037849678af57f9865c6b9887f4e339f6377a`](https://etherscan.io/address/0xa21037849678af57f9865c6b9887f4e339f6377a#code)
|
||||
-->
|
||||
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
Contract structure:
|
||||
|
||||
> The day-one functionality of the contract scripts includes:
|
||||
>
|
||||
> - Keep track of the genes of upcoming gen0 CryptoKitties
|
||||
> - Introducing the genes of gen0 CryptoKitties to the Core Contract
|
||||
> - Launching the auctions for gen0 CryptoKitties (including price determination)
|
||||
> - Combining the genotypes of two parent CryptoKitties to determine the genotype of the new CryptoKitten
|
||||
> - Managing the auctions of CryptoKitties (both gen-0 cats being auctioned to users and user-to-user auctions) and siring tokens
|
||||
> - Managing siring auctions (including initiating the breeding when successful).
|
||||
>
|
||||
> All functionality for breeding, buying, selling, and transferring cats
|
||||
> will be possible for any user by interacting directly with the contracts on the blockchain.
|
||||
> Any auctions or sales conducted through our auction contract
|
||||
> will include a 3.75% commission (no minimum) taken from the seller's portion.
|
||||
|
||||
(Source: [CryptoKitties Technical Details / Contract Structure](https://www.cryptokitties.co/Technical-details))
|
||||
|
||||
|
||||
The contract inheritance for the main kitty contract looks like this:
|
||||
|
||||
|
||||
``` solidity
|
||||
contract KittyAccessControl
|
||||
contract KittyBase is KittyAccessControl
|
||||
contract KittyOwnership is KittyBase, ERC721
|
||||
contract KittyBreeding is KittyOwnership
|
||||
contract KittyAuction is KittyBreeding
|
||||
contract KittyMinting is KittyAuction
|
||||
contract KittyCore is KittyMinting
|
||||
```
|
||||
|
||||
|
||||
### KittyAccessControl - Who controls the contract? - CEO, CFO, COO
|
||||
|
||||
> This contract manages the various addresses and constraints for operations
|
||||
> that can be executed only by specific roles. Namely CEO, CFO and COO.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
|
||||
### KittyBase - What's a kitty, really? - Kitty data type structure
|
||||
|
||||
> This is where we define the most fundamental code shared throughout the core
|
||||
> functionality. This includes our main data storage, constants and data types, plus
|
||||
> internal functions for managing these items.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
``` solidity
|
||||
/// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy
|
||||
/// of this structure, so great care was taken to ensure that it fits neatly into
|
||||
/// exactly two 256-bit words. Note that the order of the members in this structure
|
||||
/// is important because of the byte-packing rules used by Ethereum.
|
||||
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
|
||||
|
||||
struct Kitty {
|
||||
// The Kitty's genetic code is packed into these 256-bits, the format is
|
||||
// sooper-sekret! A cat's genes never change.
|
||||
uint256 genes;
|
||||
|
||||
// The timestamp from the block when this cat came into existence.
|
||||
uint64 birthTime;
|
||||
|
||||
// The minimum timestamp after which this cat can engage in breeding
|
||||
// activities again. This same timestamp is used for the pregnancy
|
||||
// timer (for matrons) as well as the siring cooldown.
|
||||
uint64 cooldownEndBlock;
|
||||
|
||||
// The ID of the parents of this kitty, set to 0 for gen0 cats.
|
||||
// Note that using 32-bit unsigned integers limits us to a "mere"
|
||||
// 4 billion cats. This number might seem small until you realize
|
||||
// that Ethereum currently has a limit of about 500 million
|
||||
// transactions per year! So, this definitely won't be a problem
|
||||
// for several years (even as Ethereum learns to scale).
|
||||
uint32 matronId;
|
||||
uint32 sireId;
|
||||
|
||||
// Set to the ID of the sire cat for matrons that are pregnant,
|
||||
// zero otherwise. A non-zero value here is how we know a cat
|
||||
// is pregnant. Used to retrieve the genetic material for the new
|
||||
// kitten when the birth transpires.
|
||||
uint32 siringWithId;
|
||||
|
||||
// Set to the index in the cooldown array (see below) that represents
|
||||
// the current cooldown duration for this Kitty. This starts at zero
|
||||
// for gen0 cats, and is initialized to floor(generation/2) for others.
|
||||
// Incremented by one for each successful breeding action, regardless
|
||||
// of whether this cat is acting as matron or sire.
|
||||
uint16 cooldownIndex;
|
||||
|
||||
// The "generation number" of this cat. Cats minted by the CK contract
|
||||
// for sale are called "gen0" and have a generation number of 0. The
|
||||
// generation number of all other cats is the larger of the two generation
|
||||
// numbers of their parents, plus one.
|
||||
// (i.e. max(matron.generation, sire.generation) + 1)
|
||||
uint16 generation;
|
||||
}
|
||||
```
|
||||
|
||||
(Source: [KittyBase.sol](KittyBase.sol))
|
||||
|
||||
|
||||
### KittyOwnership - Kitties as tokens
|
||||
|
||||
> This provides the methods required for basic non fungible token
|
||||
> transactions, following the draft [ERC-721 spec](https://github.com/ethereum/EIPs/issues/721).
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
### KittyBreeding - Cats get down and dirty
|
||||
|
||||
> This file contains the methods necessary to breed cats together, including
|
||||
> keeping track of siring offers, and relies on an external genetic combination contract.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
### KittyAuction - Buying, selling and pimpin' of cats
|
||||
|
||||
> Here we have the public methods for auctioning or bidding on cats or siring
|
||||
> services. The actual auction functionality is handled in two sibling contracts (one
|
||||
> for sales and one for siring), while auction creation and bidding is mostly mediated
|
||||
> through this facet of the core contract.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
### KittyMiniting - The gen0 cat factory
|
||||
|
||||
> This final facet contains the functionality we use for creating new gen0 cats.
|
||||
> We can make up to 5000 "promo" cats that can be given away (especially important when
|
||||
> the community is new), and all others can only be created and then immediately put up
|
||||
> for auction via an algorithmically determined starting price. Regardless of how they
|
||||
> are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
|
||||
> community to breed, breed, breed!
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
``` solidity
|
||||
// Limits the number of cats the contract owner can ever create.
|
||||
|
||||
uint256 public constant PROMO_CREATION_LIMIT = 5000;
|
||||
uint256 public constant GEN0_CREATION_LIMIT = 45000;
|
||||
```
|
||||
|
||||
(Source: [KittyMinting.sol](KittyCore.sol))
|
||||
|
||||
|
||||
|
||||
### KittyCore - The master contract - all together now
|
||||
|
||||
|
||||
``` solidity
|
||||
/// @notice Returns all the relevant information about a specific kitty.
|
||||
/// @param _id The ID of the kitty of interest.
|
||||
|
||||
function getKitty(uint256 _id)
|
||||
external
|
||||
view
|
||||
returns (
|
||||
bool isGestating,
|
||||
bool isReady,
|
||||
uint256 cooldownIndex,
|
||||
uint256 nextActionAt,
|
||||
uint256 siringWithId,
|
||||
uint256 birthTime,
|
||||
uint256 matronId,
|
||||
uint256 sireId,
|
||||
uint256 generation,
|
||||
uint256 genes
|
||||
) {
|
||||
Kitty storage kit = kitties[_id];
|
||||
|
||||
// if this variable is 0 then it's not gestating
|
||||
isGestating = (kit.siringWithId != 0);
|
||||
isReady = (kit.cooldownEndBlock <= block.number);
|
||||
cooldownIndex = uint256(kit.cooldownIndex);
|
||||
nextActionAt = uint256(kit.cooldownEndBlock);
|
||||
siringWithId = uint256(kit.siringWithId);
|
||||
birthTime = uint256(kit.birthTime);
|
||||
matronId = uint256(kit.matronId);
|
||||
sireId = uint256(kit.sireId);
|
||||
generation = uint256(kit.generation);
|
||||
genes = kit.genes;
|
||||
}
|
||||
```
|
||||
|
||||
(Source: [KittyCore.sol](KittyCore.sol))
|
||||
|
||||
|
||||
|
||||
## Articles
|
||||
|
||||
See [How to Code Your Own CryptoKitties-Style Game on Ethereum](https://medium.com/loom-network/how-to-code-your-own-cryptokitties-style-game-on-ethereum-7c8ac86a4eb3)
|
||||
by James Martin Duffy, Dec 2017 --
|
||||
for an in-depth analysis / write-up about the machinery,
|
||||
|
||||
|
||||
|
||||
|
||||
## CryptoKitty Bounty Program
|
||||
|
||||
Documentation from the Official CryptoKitty Bounty Program (github: [axiomzen/cryptokitties-bounty](https://github.com/axiomzen/cryptokitties-bounty)), Nov 2017
|
||||
|
||||
|
||||
> CryptoKitties is composed of 4 public facing contracts. Below we'll provide an overview on these contracts:
|
||||
>
|
||||
> ##### KittyCore.sol - `0x16baf0de678e52367adc69fd067e5edd1d33e3bf`
|
||||
>
|
||||
> Also referred as the main contract, is where Kitties and their ownership are stored.
|
||||
> This also mediates all the main operations, such as breeding, exchange, and part of auctions.
|
||||
>
|
||||
> For this release, the actual bytecode released for the contract is `KittyCoreRinkeby.sol`, explained below.
|
||||
>
|
||||
> ##### SaleClockAuction.sol - `0x8a316edee51b65e1627c801dbc09aa413c8f97c2`
|
||||
>
|
||||
> Where users are expected to acquire their gen0 kitten. It is also a marketplace where anyone can post their kitten for auction.
|
||||
> [See Dutch/Clock auction](https://en.wikipedia.org/wiki/Dutch_auction) - note we also accept an increasing price.
|
||||
> ps: CryptoKitties auctions take an initial time and duration, and after duration is over they are not closed.
|
||||
> Instead they hold the final price indefinitely
|
||||
>
|
||||
> ##### SiringClockAuction.sol - `0x07ca8a3a1446109468c3cf249abb53578a2bbe40`
|
||||
>
|
||||
> A marketplace where any user can offer their Kitty as a potential sire for any takers.
|
||||
>
|
||||
> ##### GeneScience.sol
|
||||
>
|
||||
> It's a mystery! Not public for this release.
|
||||
>
|
||||
>
|
||||
> [...]
|
||||
>
|
||||
> ### Common functions
|
||||
>
|
||||
> Here's what we expect to be the most usual flow, and what function are to be called.
|
||||
>
|
||||
> 1. COO will periodically put a kitten to gen0 auction (Main `createGen0Auction()`)
|
||||
> 1. user go an buy gen0 kittens (Sale Auction `bid()`)
|
||||
> 1. user can get kitty data (Main `getKitty()`)
|
||||
> 1. user can breed their own kittens (Main `breedWith()` or `breedWithAuto()`)
|
||||
> 1. after cooldown is passed, any user can have a pregnant kitty giving birth (Main `giveBirth()`)
|
||||
> 1. user can offer one of their kitties as sire via auction (Main `createSiringAuction()`)
|
||||
> 1. user can offer their kitty as sire to another user (Main `approveSiring()`)
|
||||
> 1. user can bid on an active siring auction (Main `createSiringAuction()`)
|
||||
> 1. user can put their kitty for sale on auction (Main `createSaleAuction()`)
|
||||
> 1. user can buy a kitty that is on auction from another user (Sale Auction `bid()`)
|
||||
> 1. user can check info of a kitty that is to auction (Sale/Siring Auction `getAuction()`)
|
||||
> 1. user can cancel an auction they started (Sale/Siring Auction `cancelAuction()`)
|
||||
> 1. user can transfer a kitty they own to another user (Main `transfer()`)
|
||||
> 1. user can allow another user to take ownership of a kitty they own (Main `approve()`)
|
||||
> 1. once an user has a kitty ownership approved, they can claim a kitty (Main `transferFrom()`)
|
||||
> 1. CEO is the only one that may replace COO or CTO (Main `setCEO()` `setCFO()` `setCOO()`)
|
||||
> 1. COO can mint and distribute promotional kittens (Main `createPromoKitty()`)
|
||||
> 1. COO can transfer the balance from auctions (Main `withdrawAuctionBalances()`)
|
||||
> 1. CFO can drain funds from main contract (Main `withdrawBalance()`)
|
||||
>
|
||||
> -- [Basics of CryptoKitties](https://github.com/axiomzen/cryptokitties-bounty/blob/master/CryptoKitty%20Basics.md)
|
||||
|
||||
|
||||
|
||||
|
||||
## Non Fungible Token (NFT) Standard - Ethereum Request for Comments #721 (ERC-721)
|
||||
|
||||
_CryptoKitties provides a practical use case for digital scarcity
|
||||
and digital collectibles by pioneering ERC-721, a non-fungible token protocol_
|
||||
|
||||
A standard interface allows any Non Fungible Token (NFTs) on Ethereum
|
||||
to be handled by general-purpose applications.
|
||||
In particular, it will allow for Non Fungible Token (NFTs)
|
||||
to be tracked in standardized wallets and traded on exchanges.
|
||||
|
||||
|
||||
Compatibility Functions for Ethereum Request for Comments #20 (ERC-20)
|
||||
|
||||
- function **name**() constant returns (string name)
|
||||
- function **symbol**() constant returns (string symbol)
|
||||
- function **totalSupply**() constant returns (uint256 totalSupply)
|
||||
- function **balanceOf**(address _owner) constant returns (uint256 balance)
|
||||
|
||||
Basic Ownership Functions
|
||||
|
||||
- function **ownerOf**(uint256 _tokenId) constant returns (address owner)
|
||||
- function **approve**(address _to, uint256 _tokenId)
|
||||
- function **takeOwnership**(uint256 _tokenId)
|
||||
- function **transfer**(address _to, uint256 _tokenId)
|
||||
- function **tokenOfOwnerByIndex**(address _owner, uint256 _index) constant returns (uint tokenId)
|
||||
|
||||
Metadata Functions
|
||||
|
||||
- function **tokenMetadata**(uint256 _tokenId) constant returns (string infoUrl)
|
||||
|
||||
Events
|
||||
|
||||
- event **Transfer**(address indexed _from, address indexed _to, uint256 _tokenId)
|
||||
- event **Approval**(address indexed _owner, address indexed _approved, uint256 _tokenId)
|
||||
|
||||
|
||||
(Source: [Ethereum, Non Fungible Token (NFT) Standard #721](https://github.com/ethereum/EIPs/issues/721))
|
||||
|
||||
_Code on the Blockchain - Electronic Contract Scripts_
|
||||
|
||||
# CryptoKitties Blockchain Contracts / Services
|
||||
|
||||
|
||||
Note: Almost all of the CryptoKitties contract scripts are open source and documented with inline running commentary. Thanks!
|
||||
The [KittyCore](./KittyCore.sol) contract script is about 2 000 lines total.
|
||||
|
||||
The only sooper-sekretoo contract is the [GeneScienceInterface](GeneScienceInterface.sol) with the "magic" mixGenes function
|
||||
that given genes of kitten 1 & 2, return a genetic combination.
|
||||
|
||||
Note: The mixGenes got "reverse-engineered" from the opcode - thanks to Sean Soria (see [CryptoKitties mixGenes Function](https://medium.com/@sean.soria/cryptokitties-mixgenes-function-69207883fc80), Dec 2017) -
|
||||
and is now a "public" sooper-sektretoo.
|
||||
See [`mixGenes.rb`](https://github.com/openblockchains/awesome-cryptokitties/blob/master/genes/mixGenes.rb) for a ruby version
|
||||
or [`mixGenes.py`](https://github.com/openblockchains/awesome-cryptokitties/blob/master/genes/mixGenes.py) for a python version.
|
||||
|
||||
|
||||
|
||||
|
||||
## Source Code
|
||||
|
||||
Etherscan
|
||||
|
||||
- KittyCore (Open Source), see contract address [`0x06012c8cf97bead5deae237070f9587f8e7a266d`](https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code)
|
||||
- GeneScienceInterface (Opcode), see contract address [`0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b`](https://etherscan.io/address/0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b#code)
|
||||
|
||||
> The genetic combination algorithm is kept seperate so we can open-source all of
|
||||
> the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
|
||||
> Don't worry, I'm sure someone will reverse engineer it soon enough!
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
- SaleClockAuction (Open Source), see contract address [`0xb1690c08e213a35ed9bab7b318de14420fb57d8c`](https://etherscan.io/address/0xb1690c08e213a35ed9bab7b318de14420fb57d8c#code)
|
||||
- SiringClockAuction (Open Source), see contract address [`0xc7af99fe5513eb6710e6d5f44f9989da40f27f26`](https://etherscan.io/address/0xc7af99fe5513eb6710e6d5f44f9989da40f27f26#code)
|
||||
|
||||
> The auctions are
|
||||
> seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
|
||||
> them in their own contracts, we can upgrade them without disrupting the main contract that tracks
|
||||
> kitty ownership.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
<!-- add why? why not?
|
||||
|
||||
- CEO, see contract address [`0xaf1e54b359b0897133f437fc961dd16f20c045e1`](https://etherscan.io/address/0xaf1e54b359b0897133f437fc961dd16f20c045e1#code)
|
||||
- CFO, see contract address [`0x2041bb7d8b49f0bde3aa1fa7fb506ac6c539394c`](https://etherscan.io/address/0x2041bb7d8b49f0bde3aa1fa7fb506ac6c539394c#code)
|
||||
- COO, see contract address [`0xa21037849678af57f9865c6b9887f4e339f6377a`](https://etherscan.io/address/0xa21037849678af57f9865c6b9887f4e339f6377a#code)
|
||||
-->
|
||||
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
Contract structure:
|
||||
|
||||
> The day-one functionality of the contract scripts includes:
|
||||
>
|
||||
> - Keep track of the genes of upcoming gen0 CryptoKitties
|
||||
> - Introducing the genes of gen0 CryptoKitties to the Core Contract
|
||||
> - Launching the auctions for gen0 CryptoKitties (including price determination)
|
||||
> - Combining the genotypes of two parent CryptoKitties to determine the genotype of the new CryptoKitten
|
||||
> - Managing the auctions of CryptoKitties (both gen-0 cats being auctioned to users and user-to-user auctions) and siring tokens
|
||||
> - Managing siring auctions (including initiating the breeding when successful).
|
||||
>
|
||||
> All functionality for breeding, buying, selling, and transferring cats
|
||||
> will be possible for any user by interacting directly with the contracts on the blockchain.
|
||||
> Any auctions or sales conducted through our auction contract
|
||||
> will include a 3.75% commission (no minimum) taken from the seller's portion.
|
||||
|
||||
(Source: [CryptoKitties Technical Details / Contract Structure](https://www.cryptokitties.co/Technical-details))
|
||||
|
||||
|
||||
The contract inheritance for the main kitty contract looks like this:
|
||||
|
||||
|
||||
``` solidity
|
||||
contract KittyAccessControl
|
||||
contract KittyBase is KittyAccessControl
|
||||
contract KittyOwnership is KittyBase, ERC721
|
||||
contract KittyBreeding is KittyOwnership
|
||||
contract KittyAuction is KittyBreeding
|
||||
contract KittyMinting is KittyAuction
|
||||
contract KittyCore is KittyMinting
|
||||
```
|
||||
|
||||
|
||||
### KittyAccessControl - Who controls the contract? - CEO, CFO, COO
|
||||
|
||||
> This contract manages the various addresses and constraints for operations
|
||||
> that can be executed only by specific roles. Namely CEO, CFO and COO.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
|
||||
### KittyBase - What's a kitty, really? - Kitty data type structure
|
||||
|
||||
> This is where we define the most fundamental code shared throughout the core
|
||||
> functionality. This includes our main data storage, constants and data types, plus
|
||||
> internal functions for managing these items.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
``` solidity
|
||||
/// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy
|
||||
/// of this structure, so great care was taken to ensure that it fits neatly into
|
||||
/// exactly two 256-bit words. Note that the order of the members in this structure
|
||||
/// is important because of the byte-packing rules used by Ethereum.
|
||||
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
|
||||
|
||||
struct Kitty {
|
||||
// The Kitty's genetic code is packed into these 256-bits, the format is
|
||||
// sooper-sekret! A cat's genes never change.
|
||||
uint256 genes;
|
||||
|
||||
// The timestamp from the block when this cat came into existence.
|
||||
uint64 birthTime;
|
||||
|
||||
// The minimum timestamp after which this cat can engage in breeding
|
||||
// activities again. This same timestamp is used for the pregnancy
|
||||
// timer (for matrons) as well as the siring cooldown.
|
||||
uint64 cooldownEndBlock;
|
||||
|
||||
// The ID of the parents of this kitty, set to 0 for gen0 cats.
|
||||
// Note that using 32-bit unsigned integers limits us to a "mere"
|
||||
// 4 billion cats. This number might seem small until you realize
|
||||
// that Ethereum currently has a limit of about 500 million
|
||||
// transactions per year! So, this definitely won't be a problem
|
||||
// for several years (even as Ethereum learns to scale).
|
||||
uint32 matronId;
|
||||
uint32 sireId;
|
||||
|
||||
// Set to the ID of the sire cat for matrons that are pregnant,
|
||||
// zero otherwise. A non-zero value here is how we know a cat
|
||||
// is pregnant. Used to retrieve the genetic material for the new
|
||||
// kitten when the birth transpires.
|
||||
uint32 siringWithId;
|
||||
|
||||
// Set to the index in the cooldown array (see below) that represents
|
||||
// the current cooldown duration for this Kitty. This starts at zero
|
||||
// for gen0 cats, and is initialized to floor(generation/2) for others.
|
||||
// Incremented by one for each successful breeding action, regardless
|
||||
// of whether this cat is acting as matron or sire.
|
||||
uint16 cooldownIndex;
|
||||
|
||||
// The "generation number" of this cat. Cats minted by the CK contract
|
||||
// for sale are called "gen0" and have a generation number of 0. The
|
||||
// generation number of all other cats is the larger of the two generation
|
||||
// numbers of their parents, plus one.
|
||||
// (i.e. max(matron.generation, sire.generation) + 1)
|
||||
uint16 generation;
|
||||
}
|
||||
```
|
||||
|
||||
(Source: [KittyBase.sol](KittyBase.sol))
|
||||
|
||||
|
||||
### KittyOwnership - Kitties as tokens
|
||||
|
||||
> This provides the methods required for basic non fungible token
|
||||
> transactions, following the draft [ERC-721 spec](https://github.com/ethereum/EIPs/issues/721).
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
### KittyBreeding - Cats get down and dirty
|
||||
|
||||
> This file contains the methods necessary to breed cats together, including
|
||||
> keeping track of siring offers, and relies on an external genetic combination contract.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
### KittyAuction - Buying, selling and pimpin' of cats
|
||||
|
||||
> Here we have the public methods for auctioning or bidding on cats or siring
|
||||
> services. The actual auction functionality is handled in two sibling contracts (one
|
||||
> for sales and one for siring), while auction creation and bidding is mostly mediated
|
||||
> through this facet of the core contract.
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
|
||||
### KittyMiniting - The gen0 cat factory
|
||||
|
||||
> This final facet contains the functionality we use for creating new gen0 cats.
|
||||
> We can make up to 5000 "promo" cats that can be given away (especially important when
|
||||
> the community is new), and all others can only be created and then immediately put up
|
||||
> for auction via an algorithmically determined starting price. Regardless of how they
|
||||
> are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
|
||||
> community to breed, breed, breed!
|
||||
>
|
||||
> -- Commentary from the CryptoKitties source code
|
||||
|
||||
``` solidity
|
||||
// Limits the number of cats the contract owner can ever create.
|
||||
|
||||
uint256 public constant PROMO_CREATION_LIMIT = 5000;
|
||||
uint256 public constant GEN0_CREATION_LIMIT = 45000;
|
||||
```
|
||||
|
||||
(Source: [KittyMinting.sol](KittyCore.sol))
|
||||
|
||||
|
||||
|
||||
### KittyCore - The master contract - all together now
|
||||
|
||||
|
||||
``` solidity
|
||||
/// @notice Returns all the relevant information about a specific kitty.
|
||||
/// @param _id The ID of the kitty of interest.
|
||||
|
||||
function getKitty(uint256 _id)
|
||||
external
|
||||
view
|
||||
returns (
|
||||
bool isGestating,
|
||||
bool isReady,
|
||||
uint256 cooldownIndex,
|
||||
uint256 nextActionAt,
|
||||
uint256 siringWithId,
|
||||
uint256 birthTime,
|
||||
uint256 matronId,
|
||||
uint256 sireId,
|
||||
uint256 generation,
|
||||
uint256 genes
|
||||
) {
|
||||
Kitty storage kit = kitties[_id];
|
||||
|
||||
// if this variable is 0 then it's not gestating
|
||||
isGestating = (kit.siringWithId != 0);
|
||||
isReady = (kit.cooldownEndBlock <= block.number);
|
||||
cooldownIndex = uint256(kit.cooldownIndex);
|
||||
nextActionAt = uint256(kit.cooldownEndBlock);
|
||||
siringWithId = uint256(kit.siringWithId);
|
||||
birthTime = uint256(kit.birthTime);
|
||||
matronId = uint256(kit.matronId);
|
||||
sireId = uint256(kit.sireId);
|
||||
generation = uint256(kit.generation);
|
||||
genes = kit.genes;
|
||||
}
|
||||
```
|
||||
|
||||
(Source: [KittyCore.sol](KittyCore.sol))
|
||||
|
||||
|
||||
|
||||
## Articles
|
||||
|
||||
See [How to Code Your Own CryptoKitties-Style Game on Ethereum](https://medium.com/loom-network/how-to-code-your-own-cryptokitties-style-game-on-ethereum-7c8ac86a4eb3)
|
||||
by James Martin Duffy, Dec 2017 --
|
||||
for an in-depth analysis / write-up about the machinery,
|
||||
|
||||
|
||||
|
||||
|
||||
## CryptoKitty Bounty Program
|
||||
|
||||
Documentation from the Official CryptoKitty Bounty Program (github: [axiomzen/cryptokitties-bounty](https://github.com/axiomzen/cryptokitties-bounty)), Nov 2017
|
||||
|
||||
|
||||
> CryptoKitties is composed of 4 public facing contracts. Below we'll provide an overview on these contracts:
|
||||
>
|
||||
> ##### KittyCore.sol - `0x16baf0de678e52367adc69fd067e5edd1d33e3bf`
|
||||
>
|
||||
> Also referred as the main contract, is where Kitties and their ownership are stored.
|
||||
> This also mediates all the main operations, such as breeding, exchange, and part of auctions.
|
||||
>
|
||||
> For this release, the actual bytecode released for the contract is `KittyCoreRinkeby.sol`, explained below.
|
||||
>
|
||||
> ##### SaleClockAuction.sol - `0x8a316edee51b65e1627c801dbc09aa413c8f97c2`
|
||||
>
|
||||
> Where users are expected to acquire their gen0 kitten. It is also a marketplace where anyone can post their kitten for auction.
|
||||
> [See Dutch/Clock auction](https://en.wikipedia.org/wiki/Dutch_auction) - note we also accept an increasing price.
|
||||
> ps: CryptoKitties auctions take an initial time and duration, and after duration is over they are not closed.
|
||||
> Instead they hold the final price indefinitely
|
||||
>
|
||||
> ##### SiringClockAuction.sol - `0x07ca8a3a1446109468c3cf249abb53578a2bbe40`
|
||||
>
|
||||
> A marketplace where any user can offer their Kitty as a potential sire for any takers.
|
||||
>
|
||||
> ##### GeneScience.sol
|
||||
>
|
||||
> It's a mystery! Not public for this release.
|
||||
>
|
||||
>
|
||||
> [...]
|
||||
>
|
||||
> ### Common functions
|
||||
>
|
||||
> Here's what we expect to be the most usual flow, and what function are to be called.
|
||||
>
|
||||
> 1. COO will periodically put a kitten to gen0 auction (Main `createGen0Auction()`)
|
||||
> 1. user go an buy gen0 kittens (Sale Auction `bid()`)
|
||||
> 1. user can get kitty data (Main `getKitty()`)
|
||||
> 1. user can breed their own kittens (Main `breedWith()` or `breedWithAuto()`)
|
||||
> 1. after cooldown is passed, any user can have a pregnant kitty giving birth (Main `giveBirth()`)
|
||||
> 1. user can offer one of their kitties as sire via auction (Main `createSiringAuction()`)
|
||||
> 1. user can offer their kitty as sire to another user (Main `approveSiring()`)
|
||||
> 1. user can bid on an active siring auction (Main `createSiringAuction()`)
|
||||
> 1. user can put their kitty for sale on auction (Main `createSaleAuction()`)
|
||||
> 1. user can buy a kitty that is on auction from another user (Sale Auction `bid()`)
|
||||
> 1. user can check info of a kitty that is to auction (Sale/Siring Auction `getAuction()`)
|
||||
> 1. user can cancel an auction they started (Sale/Siring Auction `cancelAuction()`)
|
||||
> 1. user can transfer a kitty they own to another user (Main `transfer()`)
|
||||
> 1. user can allow another user to take ownership of a kitty they own (Main `approve()`)
|
||||
> 1. once an user has a kitty ownership approved, they can claim a kitty (Main `transferFrom()`)
|
||||
> 1. CEO is the only one that may replace COO or CTO (Main `setCEO()` `setCFO()` `setCOO()`)
|
||||
> 1. COO can mint and distribute promotional kittens (Main `createPromoKitty()`)
|
||||
> 1. COO can transfer the balance from auctions (Main `withdrawAuctionBalances()`)
|
||||
> 1. CFO can drain funds from main contract (Main `withdrawBalance()`)
|
||||
>
|
||||
> -- [Basics of CryptoKitties](https://github.com/axiomzen/cryptokitties-bounty/blob/master/CryptoKitty%20Basics.md)
|
||||
|
||||
|
||||
|
||||
|
||||
## Non Fungible Token (NFT) Standard - Ethereum Request for Comments #721 (ERC-721)
|
||||
|
||||
_CryptoKitties provides a practical use case for digital scarcity
|
||||
and digital collectibles by pioneering ERC-721, a non-fungible token protocol_
|
||||
|
||||
A standard interface allows any Non Fungible Token (NFTs) on Ethereum
|
||||
to be handled by general-purpose applications.
|
||||
In particular, it will allow for Non Fungible Token (NFTs)
|
||||
to be tracked in standardized wallets and traded on exchanges.
|
||||
|
||||
|
||||
Compatibility Functions for Ethereum Request for Comments #20 (ERC-20)
|
||||
|
||||
- function **name**() constant returns (string name)
|
||||
- function **symbol**() constant returns (string symbol)
|
||||
- function **totalSupply**() constant returns (uint256 totalSupply)
|
||||
- function **balanceOf**(address _owner) constant returns (uint256 balance)
|
||||
|
||||
Basic Ownership Functions
|
||||
|
||||
- function **ownerOf**(uint256 _tokenId) constant returns (address owner)
|
||||
- function **approve**(address _to, uint256 _tokenId)
|
||||
- function **takeOwnership**(uint256 _tokenId)
|
||||
- function **transfer**(address _to, uint256 _tokenId)
|
||||
- function **tokenOfOwnerByIndex**(address _owner, uint256 _index) constant returns (uint tokenId)
|
||||
|
||||
Metadata Functions
|
||||
|
||||
- function **tokenMetadata**(uint256 _tokenId) constant returns (string infoUrl)
|
||||
|
||||
Events
|
||||
|
||||
- event **Transfer**(address indexed _from, address indexed _to, uint256 _tokenId)
|
||||
- event **Approval**(address indexed _owner, address indexed _approved, uint256 _tokenId)
|
||||
|
||||
|
||||
(Source: [Ethereum, Non Fungible Token (NFT) Standard #721](https://github.com/ethereum/EIPs/issues/721))
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./ClockAuction.sol";
|
||||
|
||||
/// @title Clock auction modified for sale of kitties
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
pragma solidity 0.4.24;
|
||||
|
||||
import "./ClockAuction.sol";
|
||||
|
||||
/// @title Reverse auction modified for siring
|
||||
/// @notice We omit a fallback function to prevent accidental sends to this contract.
|
||||
|
|
@ -0,0 +1,226 @@
|
|||
/* eslint-disable no-param-reassign */
|
||||
require('dotenv').config()
|
||||
const BigNumber = require('bignumber.js')
|
||||
const Web3 = require('web3')
|
||||
const Tx = require('ethereumjs-tx')
|
||||
const Web3Utils = require('web3-utils')
|
||||
const fetch = require('node-fetch')
|
||||
const assert = require('assert')
|
||||
|
||||
const { HOME_RPC_URL, FOREIGN_RPC_URL, DEPLOYMENT_ACCOUNT_PRIVATE_KEY } = process.env
|
||||
|
||||
const homeProvider = new Web3.providers.HttpProvider(HOME_RPC_URL)
|
||||
const web3Home = new Web3(homeProvider)
|
||||
|
||||
const foreignProvider = new Web3.providers.HttpProvider(FOREIGN_RPC_URL)
|
||||
const web3Foreign = new Web3(foreignProvider)
|
||||
|
||||
const { HOME_DEPLOYMENT_GAS_PRICE, FOREIGN_DEPLOYMENT_GAS_PRICE, DEPLOYMENT_GAS_LIMIT_EXTRA } = process.env
|
||||
const GAS_LIMIT_EXTRA = Number(DEPLOYMENT_GAS_LIMIT_EXTRA)
|
||||
|
||||
const deploymentPrivateKey = Buffer.from(DEPLOYMENT_ACCOUNT_PRIVATE_KEY, 'hex')
|
||||
const receiptInterval = 3000
|
||||
|
||||
async function deployContract(contractJson, args, { from, network, nonce }) {
|
||||
let web3
|
||||
let url
|
||||
let gasPrice
|
||||
if (network === 'foreign') {
|
||||
web3 = web3Foreign
|
||||
url = FOREIGN_RPC_URL
|
||||
gasPrice = FOREIGN_DEPLOYMENT_GAS_PRICE
|
||||
} else {
|
||||
web3 = web3Home
|
||||
url = HOME_RPC_URL
|
||||
gasPrice = HOME_DEPLOYMENT_GAS_PRICE
|
||||
}
|
||||
const options = {
|
||||
from
|
||||
}
|
||||
const instance = new web3.eth.Contract(contractJson.abi, options)
|
||||
const result = await instance
|
||||
.deploy({
|
||||
data: contractJson.bytecode,
|
||||
arguments: args
|
||||
})
|
||||
.encodeABI()
|
||||
const tx = await sendRawTx({
|
||||
data: result,
|
||||
nonce: Web3Utils.toHex(nonce),
|
||||
to: null,
|
||||
privateKey: deploymentPrivateKey,
|
||||
url,
|
||||
gasPrice
|
||||
})
|
||||
if (Web3Utils.hexToNumber(tx.status) !== 1 && !tx.contractAddress) {
|
||||
throw new Error('Tx failed')
|
||||
}
|
||||
instance.options.address = tx.contractAddress
|
||||
instance.deployedBlockNumber = tx.blockNumber
|
||||
return instance
|
||||
}
|
||||
|
||||
async function sendRawTxHome(options) {
|
||||
return sendRawTx({
|
||||
...options,
|
||||
gasPrice: HOME_DEPLOYMENT_GAS_PRICE
|
||||
})
|
||||
}
|
||||
|
||||
async function sendRawTxForeign(options) {
|
||||
return sendRawTx({
|
||||
...options,
|
||||
gasPrice: FOREIGN_DEPLOYMENT_GAS_PRICE
|
||||
})
|
||||
}
|
||||
|
||||
async function sendRawTx({ data, nonce, to, privateKey, url, gasPrice, value }) {
|
||||
try {
|
||||
const txToEstimateGas = {
|
||||
from: privateKeyToAddress(Web3Utils.bytesToHex(privateKey)),
|
||||
value,
|
||||
to,
|
||||
data
|
||||
}
|
||||
const estimatedGas = BigNumber(await sendNodeRequest(url, 'eth_estimateGas', txToEstimateGas))
|
||||
|
||||
const blockData = await sendNodeRequest(url, 'eth_getBlockByNumber', ['latest', false])
|
||||
const blockGasLimit = BigNumber(blockData.gasLimit)
|
||||
if (estimatedGas.isGreaterThan(blockGasLimit)) {
|
||||
throw new Error(
|
||||
`estimated gas greater (${estimatedGas.toString()}) than the block gas limit (${blockGasLimit.toString()})`
|
||||
)
|
||||
}
|
||||
let gas = estimatedGas.multipliedBy(BigNumber(1 + GAS_LIMIT_EXTRA))
|
||||
if (gas.isGreaterThan(blockGasLimit)) {
|
||||
gas = blockGasLimit
|
||||
} else {
|
||||
gas = gas.toFixed(0)
|
||||
}
|
||||
|
||||
const rawTx = {
|
||||
nonce,
|
||||
gasPrice: Web3Utils.toHex(gasPrice),
|
||||
gasLimit: Web3Utils.toHex(gas),
|
||||
to,
|
||||
data,
|
||||
value
|
||||
}
|
||||
|
||||
const tx = new Tx(rawTx)
|
||||
tx.sign(privateKey)
|
||||
const serializedTx = tx.serialize()
|
||||
const txHash = await sendNodeRequest(url, 'eth_sendRawTransaction', `0x${serializedTx.toString('hex')}`)
|
||||
console.log('pending txHash', txHash)
|
||||
return await getReceipt(txHash, url)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
async function sendNodeRequest(url, method, signedData) {
|
||||
if (!Array.isArray(signedData)) {
|
||||
signedData = [signedData]
|
||||
}
|
||||
const request = await fetch(url, {
|
||||
headers: {
|
||||
'Content-type': 'application/json'
|
||||
},
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: signedData,
|
||||
id: 1
|
||||
})
|
||||
})
|
||||
const json = await request.json()
|
||||
if (typeof json.error === 'undefined' || json.error === null) {
|
||||
if (method === 'eth_sendRawTransaction') {
|
||||
assert.strictEqual(json.result.length, 66, `Tx wasn't sent ${json}`)
|
||||
}
|
||||
return json.result
|
||||
}
|
||||
throw new Error(`web3 RPC failed: ${JSON.stringify(json.error)}`)
|
||||
}
|
||||
|
||||
function timeout(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
async function getReceipt(txHash, url) {
|
||||
await timeout(receiptInterval)
|
||||
let receipt = await sendNodeRequest(url, 'eth_getTransactionReceipt', txHash)
|
||||
if (receipt === null || receipt.blockNumber === null) {
|
||||
receipt = await getReceipt(txHash, url)
|
||||
}
|
||||
return receipt
|
||||
}
|
||||
|
||||
function add0xPrefix(s) {
|
||||
if (s.indexOf('0x') === 0) {
|
||||
return s
|
||||
}
|
||||
|
||||
return `0x${s}`
|
||||
}
|
||||
|
||||
function privateKeyToAddress(privateKey) {
|
||||
return new Web3().eth.accounts.privateKeyToAccount(add0xPrefix(privateKey)).address
|
||||
}
|
||||
|
||||
async function upgradeProxy({ proxy, implementationAddress, version, nonce, url }) {
|
||||
const data = await proxy.methods.upgradeTo(version, implementationAddress).encodeABI()
|
||||
const sendTx = getSendTxMethod(url)
|
||||
const result = await sendTx({
|
||||
data,
|
||||
nonce,
|
||||
to: proxy.options.address,
|
||||
privateKey: deploymentPrivateKey,
|
||||
url
|
||||
})
|
||||
assert.strictEqual(Web3Utils.hexToNumber(result.status), 1, 'Transaction Failed')
|
||||
}
|
||||
|
||||
async function transferProxyOwnership({ proxy, newOwner, nonce, url }) {
|
||||
const data = await proxy.methods.transferProxyOwnership(newOwner).encodeABI()
|
||||
const sendTx = getSendTxMethod(url)
|
||||
const result = await sendTx({
|
||||
data,
|
||||
nonce,
|
||||
to: proxy.options.address,
|
||||
privateKey: deploymentPrivateKey,
|
||||
url
|
||||
})
|
||||
assert.strictEqual(Web3Utils.hexToNumber(result.status), 1, 'Transaction Failed')
|
||||
}
|
||||
|
||||
async function transferOwnership({ contract, newOwner, nonce, url }) {
|
||||
const data = await contract.methods.transferOwnership(newOwner).encodeABI()
|
||||
const sendTx = getSendTxMethod(url)
|
||||
const result = await sendTx({
|
||||
data,
|
||||
nonce,
|
||||
to: contract.options.address,
|
||||
privateKey: deploymentPrivateKey,
|
||||
url
|
||||
})
|
||||
assert.strictEqual(Web3Utils.hexToNumber(result.status), 1, 'Transaction Failed')
|
||||
}
|
||||
|
||||
function getSendTxMethod(url) {
|
||||
return url === HOME_RPC_URL ? sendRawTxHome : sendRawTxForeign
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
deployContract,
|
||||
sendRawTxHome,
|
||||
sendRawTxForeign,
|
||||
privateKeyToAddress,
|
||||
upgradeProxy,
|
||||
transferProxyOwnership,
|
||||
transferOwnership,
|
||||
web3Home,
|
||||
web3Foreign,
|
||||
deploymentPrivateKey
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
const assert = require('assert')
|
||||
const Web3Utils = require('web3-utils')
|
||||
const kittyCore = require('../build/contracts/KittyCore')
|
||||
const {
|
||||
deployContract,
|
||||
privateKeyToAddress,
|
||||
web3Foreign,
|
||||
deploymentPrivateKey,
|
||||
sendRawTxForeign
|
||||
} = require('./deploymentUtils')
|
||||
|
||||
const { DEPLOYMENT_ACCOUNT_PRIVATE_KEY, KITTIES_AMOUNT, FOREIGN_RPC_URL } = process.env
|
||||
|
||||
async function main() {
|
||||
const accountAddress = privateKeyToAddress(DEPLOYMENT_ACCOUNT_PRIVATE_KEY)
|
||||
let nonce = await web3Foreign.eth.getTransactionCount(accountAddress)
|
||||
|
||||
// deploy contract
|
||||
console.log('Deploying kittyCore contract')
|
||||
const kittyCoreContract = await deployContract(kittyCore, [], {
|
||||
from: accountAddress,
|
||||
network: 'foreign',
|
||||
nonce
|
||||
})
|
||||
nonce++
|
||||
console.log('kittyCore Address: ', kittyCoreContract.options.address)
|
||||
|
||||
// mint kitties
|
||||
const kittiesAmount = Number(KITTIES_AMOUNT)
|
||||
if (kittiesAmount) {
|
||||
console.log('Minting kitties to', accountAddress)
|
||||
for (let i = 1; i <= kittiesAmount; i++) {
|
||||
const mintData = await kittyCoreContract.methods.createPromoKitty(i, accountAddress).encodeABI()
|
||||
const txMint = await sendRawTxForeign({
|
||||
data: mintData,
|
||||
nonce,
|
||||
to: kittyCoreContract.options.address,
|
||||
privateKey: deploymentPrivateKey,
|
||||
url: FOREIGN_RPC_URL
|
||||
})
|
||||
assert.strictEqual(Web3Utils.hexToNumber(txMint.status), 1, 'Transaction Failed')
|
||||
console.log(`Minted Kitty ID: ${i}`)
|
||||
nonce++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(e => console.log(e))
|
324
genes/README.md
|
@ -1,324 +0,0 @@
|
|||
# Inside CryptoKitties Genetics / Genes / Genome
|
||||
|
||||
|
||||
_cdcd 5656 4744 gfg4 66d4 7877 eccf 251j 77k7 222k gddg ddea_
|
||||
|
||||
|
||||
The 256-bit genome (genes) have over 4-billion variations of phenotypes (what you see)
|
||||
and genotypes (what you don't see).
|
||||
|
||||
![](../i/cryptokitties-genes.png)
|
||||
|
||||
[**The CryptoKitties Genome Project**](https://medium.com/@kaigani/the-cryptokitties-genome-project-68582016f687) by Kai Turner, Dec 19
|
||||
|
||||
> Here's what I've found:
|
||||
> - Genes are stored in 12 blocks of 4x5-bit codes
|
||||
> - Each 5-bit code represents a cattribute associated with the position in the gene (body, pattern type, eye color, eye type, primary color, pattern color, secondary color, fancy type, mouth)
|
||||
> - Each block of 4 codes represents 1 dominant trait expressed in the Kitty followed by 3 recessive traits.
|
||||
> - Codes are passed from either parent to child, with a low probability of swapping from the 1st recessive, and a lower probability of swapping from the 2nd or 3rd recessive.
|
||||
> [...]
|
||||
|
||||
![](../i/cryptokittydex-kaittributes.png)
|
||||
|
||||
(Source: [CryptoKittydex, Kaittributes](https://cryptokittydex.com/kaittributes))
|
||||
|
||||
|
||||
[**The CryptoKitties Genome Project: On Dominance, Inheritance and Mutation**](https://medium.com/@kaigani/the-cryptokitties-genome-project-on-dominance-inheritance-and-mutation-b73059dcd0a4) by Kai Turner, Jan 6, 2018 -- Genome, deciphered
|
||||
|
||||
> The genome represents 12 groups of 4 genes.
|
||||
> Each group of 4 genes maps to a given cattribute trait.
|
||||
> Within each group of 4 genes, there are 3 recessive genes [R1, R2, R3]
|
||||
> and 1 dominant gene [D1] which will be reflected as a cattribute for that trait,
|
||||
> represented in the appearance of that kitty.
|
||||
>
|
||||
> [...]
|
||||
>
|
||||
> Here is a quick sketch of the relative odds of getting a specific gene from the parents
|
||||
>
|
||||
> - 75% - either dominant gene [D1] from parent A or B
|
||||
> - 18.75% (75/4) - chance of getting either 1st recessive [R1] from A or B
|
||||
> - 4.69% (75/4²) - chance of getting either 2nd recessive [R2] from A or B
|
||||
> - 1.17% (75/4³) - chance of getting either 3rd recessive [R3] from A or B
|
||||
> - 25% - chance of getting a mutation given A & B contain the right gene pairs
|
||||
|
||||
![](../i/cryptokitties-genes-ii.png)
|
||||
|
||||
|
||||
|
||||
|
||||
Q: What's kai notation (base58)?
|
||||
|
||||
Kai notation (named to honor Kai who deciphered the kitties genome)
|
||||
is a base58 variant for decoding the 256-bit integer into 5-bit blocks.
|
||||
Each 5-bit block is a gene. The 256-bit genome breaks down into 12 groups of 4 (x 5-bit) genes (that is, 12 x 4 x 5-bit = 240 bits)
|
||||
Example:
|
||||
|
||||
|Kai |Binary |Num|Kai |Binary |Num|Kai |Binary |Num|Kai |Binary |Num|
|
||||
|-------|-------|---|-------|-------|---|-------|-------|---|-------|-------|---|
|
||||
| **1** | 00000 | 0 | **9** | 01000 | 8 | **h** | 10000 |16 | **q** | 11000 |24 |
|
||||
| **2** | 00001 | 1 | **a** | 01001 | 9 | **i** | 10001 |17 | **r** | 11001 |25 |
|
||||
| **3** | 00010 | 2 | **b** | 01010 | 10| **j** | 10010 |18 | **s** | 11010 |26 |
|
||||
| **4** | 00011 | 3 | **c** | 01011 | 11| **k** | 10011 |19 | **t** | 11011 |27 |
|
||||
| **5** | 00100 | 4 | **d** | 01100 | 12| **m** | 10100 |20 | **u** | 11100 |28 |
|
||||
| **6** | 00101 | 5 | **e** | 01101 | 13| **n** | 10101 |21 | **v** | 11101 |29 |
|
||||
| **7** | 00110 | 6 | **f** | 01110 | 14| **o** | 10110 |22 | **w** | 11110 |30 |
|
||||
| **8** | 00111 | 7 | **g** | 01111 | 15| **p** | 10111 |23 | **x** | 11111 |31 |
|
||||
|
||||
Note: The digit-0 and the letter-l are NOT used in kai.
|
||||
|
||||
> Base58 is a group of binary-to-text encoding schemes used to represent large integers as alphanumeric text.
|
||||
> It is similar to Base64 but has been modified to avoid both non-alphanumeric characters
|
||||
> and letters which might look ambiguous when printed [e.g. 1 and l, 0 and o].
|
||||
> It is therefore designed for human users who manually enter the data,
|
||||
> copying from some visual source, but also allows easy copy
|
||||
> and paste because a double-click will usually select the whole string.
|
||||
>
|
||||
> [-- Base58 @ Wikipedia](https://en.wikipedia.org/wiki/Base58)
|
||||
|
||||
|
||||
|
||||
Example - Eyes Gene Mapping (Bits 12 to 15) - Kai-to-Cattributes ("Kaittributes"):
|
||||
|
||||
|Kai|Cattribute |Kai|Cattribute |Kai|Cattribute |Kai|Cattribute |
|
||||
|---|-------------|---|------------|---|------------|---|------------|
|
||||
| 1 | ?? | 9 | ?? | h | ?? | q | ?? |
|
||||
| 2 | wonky | a | ?? | i | alien | r | wingtips |
|
||||
| 3 | serpent | b | ?? | j | fabulous | s | ?? |
|
||||
| 4 | googly | c | ?? | k | raisedbrow | t | ?? |
|
||||
| 5 | otaku | d | ?? | m | ?? | u | ?? |
|
||||
| 6 | simple | e | ?? | n | ?? | v | ?? |
|
||||
| 7 | crazy | f | ?? | o | ?? | w | ?? |
|
||||
| 8 | thicccbrowz | g | stunned | p | ?? | x | ?? |
|
||||
|
||||
Note: ?? - "rare" cattribute not yet seen in kitties
|
||||
|
||||
|
||||
Example - Body Gene Mapping (Bits 0 to 3)
|
||||
|
||||
|Kai|Cattribute |Kai|Cattribute |Kai|Cattribute |Kai|Cattribute |
|
||||
|---|-------------|---|------------|---|------------|---|------------|
|
||||
| 1 | ?? | 9 | ?? | h | ?? | q | ?? |
|
||||
| 2 | selkirk | a | cymric | i | ?? | r | ?? |
|
||||
| 3 | ?? | b | chartreux | j | ?? | s | ?? |
|
||||
| 4 | ?? | c | himalayan | k | ?? | t | manx |
|
||||
| 5 | ?? | d | munchkin | m | ?? | u | ?? |
|
||||
| 6 | ?? | e | sphynx | n | mainecoon | v | ?? |
|
||||
| 7 | ?? | f | ragamuffin | o | laperm | w | ?? |
|
||||
| 8 | ?? | g | ragdoll | p | persian | x | ?? |
|
||||
|
||||
Note: ?? - "rare" cattribute not yet seen in kitties
|
||||
|
||||
|
||||
|
||||
[**CryptoKitties mixGenes Function**](https://medium.com/@sean.soria/cryptokitties-mixgenes-function-69207883fc80) by Sean Soria, Dec 22
|
||||
|
||||
> The mixGenes function gets called when you breed two cats. This is how the baby's genes are calculated. [...]
|
||||
> Here’s the pseudocode to start:
|
||||
|
||||
```
|
||||
def mixGenes(mGenes[48], sGenes[48], babyGenes[48]):
|
||||
# PARENT GENE SWAPPING
|
||||
for (i = 0; i < 12; i++):
|
||||
index = 4 * i
|
||||
for (j = 3; j > 0; j--):
|
||||
if random() < 0.25:
|
||||
swap(mGenes, index+j, index+j-1)
|
||||
if random() < 0.25:
|
||||
swap(sGenes, index+j, index+j-1)
|
||||
# BABY GENES
|
||||
for (i = 0; i < 48; i++):
|
||||
mutation = 0
|
||||
# CHECK MUTATION
|
||||
if i % 4 == 0:
|
||||
gene1 = mGene[i]
|
||||
gene2 = sGene[i]
|
||||
if gene1 > gene2:
|
||||
gene1, gene2 = gene2, gene1
|
||||
if (gene2 - gene1) == 1 and iseven(gene1):
|
||||
probability = 0.25
|
||||
if gene1 > 23:
|
||||
probability /= 2
|
||||
if random() < probability:
|
||||
mutation = (gene1 / 2) + 16
|
||||
# GIVE BABY GENES
|
||||
if mutation:
|
||||
baby[i] = mutation
|
||||
else:
|
||||
if random() < 0.5:
|
||||
babyGenes[i] = mGene[i]
|
||||
else:
|
||||
babyGenes[i] = sGene[i]
|
||||
```
|
||||
|
||||
|
||||
[**CryptoKitties GeneScience algorithm**](https://medium.com/@alexhegyi/cryptokitties-genescience-1f5b41963b0d) by Alex Hegyi, Dec 23
|
||||
|
||||
> My winter holiday thus far has consisted of staring at disassembled bytecode
|
||||
> until I had everything figured out:
|
||||
|
||||
``` python
|
||||
|
||||
# These examples are from Tx 0xa7b0ac87684771f6d6204a09b5a0bf0b97f6adf61b78138e8fd264828e36b956
|
||||
|
||||
# matron.genes
|
||||
arg1 = 0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c
|
||||
|
||||
# sire.genes
|
||||
arg2 = 0x00005a13429085339c6521ef0300011c82438c628cc431a63298e3721f772d29
|
||||
|
||||
# matron.cooldownEndBlock - 1
|
||||
arg3 = 0x000000000000000000000000000000000000000000000000000000000047ff27
|
||||
|
||||
# BLOCKHASH of block number equal to arg3
|
||||
blockhash = 0xf9dd4486d68b13839d2f7b345f5223f17abae39a951f2cea5b0ca0dd6dc8db83
|
||||
|
||||
|
||||
# load arguments into bytes arrays in big-Endian order
|
||||
|
||||
args1 = []
|
||||
for cnt in range(32):
|
||||
args1.append(arg1//((1<<8)**cnt)&0xff)
|
||||
args1.reverse()
|
||||
args1 = bytes(args1)
|
||||
|
||||
args2 = []
|
||||
for cnt in range(32):
|
||||
args2.append(arg2//((1<<8)**cnt)&0xff)
|
||||
args2.reverse()
|
||||
args2 = bytes(args2)
|
||||
|
||||
|
||||
args3 = []
|
||||
for cnt in range(32):
|
||||
args3.append(arg3//((1<<8)**cnt)&0xff)
|
||||
args3.reverse()
|
||||
args3 = bytes(args3)
|
||||
|
||||
blockhashes = []
|
||||
for cnt in range(32):
|
||||
blockhashes.append(blockhash//((1<<8)**cnt)&0xff)
|
||||
blockhashes.reverse()
|
||||
blockhashes = bytes(blockhashes)
|
||||
|
||||
# concatenate bytes arrays
|
||||
|
||||
alls = blockhashes + args1 + args2 + args3
|
||||
|
||||
|
||||
# get hash of bytes arrays. This is your source of "randomness"
|
||||
|
||||
hash = sha3.keccak_256(alls)
|
||||
hash = int.from_bytes(hash.digest(), byteorder = 'big')
|
||||
|
||||
print(hex(hash))
|
||||
|
||||
# => 0xe30dd999bfba6dd6cd4540fb58c5a1c117e6938c0931459b1c9f6e01d865c19e
|
||||
|
||||
|
||||
# get 5-bit chunks of matron and sire
|
||||
|
||||
def masker(arg, start, numbytes):
|
||||
mask = 2**numbytes - 1
|
||||
mask = mask << start
|
||||
out = arg & mask
|
||||
out = out >> start
|
||||
|
||||
return out
|
||||
|
||||
arg1masks = []
|
||||
for cnt in range(0x30):
|
||||
arg1masks.append(masker(arg1, 5*cnt, 5))
|
||||
|
||||
arg2masks = []
|
||||
for cnt in range(0x30):
|
||||
arg2masks.append(masker(arg2, 5*cnt, 5))
|
||||
|
||||
arg1maskscopy = arg1masks.copy()
|
||||
arg2maskscopy = arg2masks.copy()
|
||||
|
||||
# note in worst case hashindex wont reach 256 so no need for modulo
|
||||
hashindex = 0
|
||||
|
||||
# swap dominant/recessive genes according to masked_hash
|
||||
for bigcounter in range(0x0c):
|
||||
for smallcounter in range(3, 0, -1):
|
||||
count = 4*bigcounter + smallcounter
|
||||
|
||||
masked_hash = masker(hash, hashindex, 2)
|
||||
hashindex += 2
|
||||
if masked_hash == 0:
|
||||
tmp = arg1maskscopy[count - 1]
|
||||
arg1maskscopy[count - 1] = arg1maskscopy[count]
|
||||
arg1maskscopy[count] = tmp
|
||||
|
||||
masked_hash = masker(hash, hashindex, 2)
|
||||
hashindex += 2
|
||||
if masked_hash == 0:
|
||||
tmp = arg2maskscopy[count - 1]
|
||||
arg2maskscopy[count - 1] = arg2maskscopy[count]
|
||||
arg2maskscopy[count] = tmp
|
||||
|
||||
# combine genes from swapped parent genes, introducing mutations
|
||||
|
||||
outmasks = []
|
||||
for cnt in range(0x30):
|
||||
rando_byte = 0
|
||||
|
||||
# mutate only on dominant genes
|
||||
if cnt%4 == 0:
|
||||
tmp1 = arg1maskscopy[cnt]&1
|
||||
tmp2 = arg2maskscopy[cnt]&1
|
||||
|
||||
if tmp1 != tmp2:
|
||||
masked_hash = masker(hash, hashindex, 3)
|
||||
hashindex += 3
|
||||
|
||||
mask1 = arg1maskscopy[cnt]
|
||||
mask2 = arg2maskscopy[cnt]
|
||||
|
||||
# mutate only if the two parent dominant genes differ by 1...
|
||||
if abs(mask2 - mask1) == 1:
|
||||
min_mask = min(mask1, mask2)
|
||||
# and the smaller of the two is even...
|
||||
if min_mask % 2 == 0:
|
||||
if min_mask < 0x17:
|
||||
trial = masked_hash > 1
|
||||
else:
|
||||
trial = masked_hash > 0
|
||||
if not trial:
|
||||
# mutation is the smaller of the two parent dominant genes,
|
||||
# divided by two, plus 16
|
||||
rando_byte = (min_mask >> 1) + 0x10
|
||||
|
||||
if rando_byte > 0:
|
||||
print(cnt)
|
||||
outmasks.append(rando_byte)
|
||||
continue
|
||||
|
||||
masked_hash = masker(hash, hashindex, 1)
|
||||
hashindex += 1
|
||||
|
||||
if masked_hash == 0:
|
||||
outmasks.append(arg1maskscopy[cnt])
|
||||
else:
|
||||
outmasks.append(arg2maskscopy[cnt])
|
||||
|
||||
|
||||
# this is where we will accumulate the calculated child genes
|
||||
outs = 0
|
||||
|
||||
# this is where you can put the known child genes, for testing
|
||||
outs2 = 0x5b174298a44b9c6521176000021c53734c9018c431a73298674a5177316c
|
||||
|
||||
for cnt in range(0x30):
|
||||
outs |= outmasks[cnt] << 5*cnt
|
||||
|
||||
# print both for comparison
|
||||
print(hex(outs))
|
||||
print(hex(outs2))
|
||||
|
||||
# => 0x5b174298a44b9c6521176000021c53734c9018c431a73298674a5177316c
|
||||
# => 0x5b174298a44b9c6521176000021c53734c9018c431a73298674a5177316c
|
||||
```
|
||||
|
||||
(Source: [Alex Hegyi, CryptoKitties GeneScience](https://github.com/heglex/gene-science/blob/master/Cryptokitties%20mixGenes%20test.ipynb))
|
|
@ -1,176 +0,0 @@
|
|||
##################################
|
||||
# CryptoKitties GeneScience algorithm by Alex Hegyi, Dec 23
|
||||
# see https://medium.com/@alexhegyi/cryptokitties-genescience-1f5b41963b0d
|
||||
#
|
||||
# > My winter holiday thus far has consisted of staring at disassembled bytecode
|
||||
# > until I had everything figured out:
|
||||
#
|
||||
# Source:
|
||||
# https://github.com/heglex/gene-science/blob/master/Cryptokitties%20mixGenes%20test.ipynb
|
||||
#
|
||||
|
||||
# These examples are from Tx 0xa7b0ac87684771f6d6204a09b5a0bf0b97f6adf61b78138e8fd264828e36b956
|
||||
|
||||
# matron.genes
|
||||
arg1 = 0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c
|
||||
|
||||
# sire.genes
|
||||
arg2 = 0x00005a13429085339c6521ef0300011c82438c628cc431a63298e3721f772d29
|
||||
|
||||
# matron.cooldownEndBlock - 1
|
||||
arg3 = 0x000000000000000000000000000000000000000000000000000000000047ff27
|
||||
|
||||
# BLOCKHASH of block number equal to arg3
|
||||
blockhash = 0xf9dd4486d68b13839d2f7b345f5223f17abae39a951f2cea5b0ca0dd6dc8db83
|
||||
|
||||
|
||||
# load arguments into bytes arrays in big-Endian order
|
||||
|
||||
args1 = []
|
||||
for cnt in range(32):
|
||||
args1.append(arg1//((1<<8)**cnt)&0xff)
|
||||
args1.reverse()
|
||||
args1 = bytes(args1)
|
||||
|
||||
args2 = []
|
||||
for cnt in range(32):
|
||||
args2.append(arg2//((1<<8)**cnt)&0xff)
|
||||
args2.reverse()
|
||||
args2 = bytes(args2)
|
||||
|
||||
|
||||
args3 = []
|
||||
for cnt in range(32):
|
||||
args3.append(arg3//((1<<8)**cnt)&0xff)
|
||||
args3.reverse()
|
||||
args3 = bytes(args3)
|
||||
|
||||
blockhashes = []
|
||||
for cnt in range(32):
|
||||
blockhashes.append(blockhash//((1<<8)**cnt)&0xff)
|
||||
blockhashes.reverse()
|
||||
blockhashes = bytes(blockhashes)
|
||||
|
||||
# concatenate bytes arrays
|
||||
|
||||
alls = blockhashes + args1 + args2 + args3
|
||||
|
||||
|
||||
# get hash of bytes arrays. This is your source of "randomness"
|
||||
|
||||
hash = sha3.keccak_256(alls)
|
||||
hash = int.from_bytes(hash.digest(), byteorder = 'big')
|
||||
|
||||
print(hex(hash))
|
||||
|
||||
# => 0xe30dd999bfba6dd6cd4540fb58c5a1c117e6938c0931459b1c9f6e01d865c19e
|
||||
|
||||
|
||||
# get 5-bit chunks of matron and sire
|
||||
|
||||
def masker(arg, start, numbytes):
|
||||
mask = 2**numbytes - 1
|
||||
mask = mask << start
|
||||
out = arg & mask
|
||||
out = out >> start
|
||||
|
||||
return out
|
||||
|
||||
arg1masks = []
|
||||
for cnt in range(0x30):
|
||||
arg1masks.append(masker(arg1, 5*cnt, 5))
|
||||
|
||||
arg2masks = []
|
||||
for cnt in range(0x30):
|
||||
arg2masks.append(masker(arg2, 5*cnt, 5))
|
||||
|
||||
arg1maskscopy = arg1masks.copy()
|
||||
arg2maskscopy = arg2masks.copy()
|
||||
|
||||
# note in worst case hashindex wont reach 256 so no need for modulo
|
||||
hashindex = 0
|
||||
|
||||
# swap dominant/recessive genes according to masked_hash
|
||||
for bigcounter in range(0x0c):
|
||||
for smallcounter in range(3, 0, -1):
|
||||
count = 4*bigcounter + smallcounter
|
||||
|
||||
masked_hash = masker(hash, hashindex, 2)
|
||||
hashindex += 2
|
||||
if masked_hash == 0:
|
||||
tmp = arg1maskscopy[count - 1]
|
||||
arg1maskscopy[count - 1] = arg1maskscopy[count]
|
||||
arg1maskscopy[count] = tmp
|
||||
|
||||
masked_hash = masker(hash, hashindex, 2)
|
||||
hashindex += 2
|
||||
if masked_hash == 0:
|
||||
tmp = arg2maskscopy[count - 1]
|
||||
arg2maskscopy[count - 1] = arg2maskscopy[count]
|
||||
arg2maskscopy[count] = tmp
|
||||
|
||||
# combine genes from swapped parent genes, introducing mutations
|
||||
|
||||
outmasks = []
|
||||
for cnt in range(0x30):
|
||||
rando_byte = 0
|
||||
|
||||
# mutate only on dominant genes
|
||||
if cnt%4 == 0:
|
||||
tmp1 = arg1maskscopy[cnt]&1
|
||||
tmp2 = arg2maskscopy[cnt]&1
|
||||
|
||||
if tmp1 != tmp2:
|
||||
masked_hash = masker(hash, hashindex, 3)
|
||||
hashindex += 3
|
||||
|
||||
mask1 = arg1maskscopy[cnt]
|
||||
mask2 = arg2maskscopy[cnt]
|
||||
|
||||
# mutate only if the two parent dominant genes differ by 1...
|
||||
if abs(mask2 - mask1) == 1:
|
||||
min_mask = min(mask1, mask2)
|
||||
# and the smaller of the two is even...
|
||||
if min_mask % 2 == 0:
|
||||
if min_mask < 0x17:
|
||||
trial = masked_hash > 1
|
||||
else:
|
||||
trial = masked_hash > 0
|
||||
if not trial:
|
||||
# mutation is the smaller of the two parent dominant genes,
|
||||
# divided by two, plus 16
|
||||
rando_byte = (min_mask >> 1) + 0x10
|
||||
|
||||
if rando_byte > 0:
|
||||
print(cnt)
|
||||
outmasks.append(rando_byte)
|
||||
continue
|
||||
|
||||
masked_hash = masker(hash, hashindex, 1)
|
||||
hashindex += 1
|
||||
|
||||
if masked_hash == 0:
|
||||
outmasks.append(arg1maskscopy[cnt])
|
||||
else:
|
||||
outmasks.append(arg2maskscopy[cnt])
|
||||
|
||||
|
||||
# this is where we will accumulate the calculated child genes
|
||||
outs = 0
|
||||
|
||||
# this is where you can put the known child genes, for testing
|
||||
outs2 = 0x5b174298a44b9c6521176000021c53734c9018c431a73298674a5177316c
|
||||
|
||||
for cnt in range(0x30):
|
||||
outs |= outmasks[cnt] << 5*cnt
|
||||
|
||||
# print both for comparison
|
||||
print(hex(outs))
|
||||
print(hex(outs2))
|
||||
|
||||
# => 0x5b174298a44b9c6521176000021c53734c9018c431a73298674a5177316c
|
||||
# => 0x5b174298a44b9c6521176000021c53734c9018c431a73298674a5177316c
|
||||
|
||||
|
||||
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
#################
|
||||
# CryptoKitties geneScience.mixGenes - "magic" sooper-sekret gene mixing operation forumula (ruby edition)
|
||||
# to run use:
|
||||
# $ ruby ./mixGenes.rb
|
||||
#
|
||||
#
|
||||
# based on the pseudo-code published by Sean Soria
|
||||
# in "CryptoKitties mixGenes Function"
|
||||
# see https://medium.com/@sean.soria/cryptokitties-mixgenes-function-69207883fc80
|
||||
#
|
||||
# original call in kitty script:
|
||||
# uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
|
||||
#
|
||||
# see https://etherscan.io/address/0xf97e0a5b616dffc913e72455fde9ea8bbe946a2b#code
|
||||
# opscode:
|
||||
#
|
||||
# PUSH1 0x60
|
||||
# PUSH1 0x40
|
||||
# MSTORE
|
||||
# PUSH1 0x04
|
||||
# CALLDATASIZE
|
||||
# LT
|
||||
# PUSH2 0x006c
|
||||
# JUMPI
|
||||
# PUSH4 0xffffffff
|
||||
# PUSH29 0x0100000000000000000000000000000000000000000000000000000000
|
||||
# PUSH1 0x00
|
||||
# CALLDATALOAD
|
||||
# DIV
|
||||
# AND
|
||||
# PUSH4 0x0d9f5aed
|
||||
# ...
|
||||
#
|
||||
# pseudo code:
|
||||
#
|
||||
# def mixGenes(mGenes[48], sGenes[48], babyGenes[48]):
|
||||
# # PARENT GENE SWAPPING
|
||||
# for (i = 0; i < 12; i++):
|
||||
# index = 4 * i
|
||||
# for (j = 3; j > 0; j--):
|
||||
# if random() < 0.25:
|
||||
# swap(mGenes, index+j, index+j-1)
|
||||
# if random() < 0.25:
|
||||
# swap(sGenes, index+j, index+j-1)
|
||||
# # BABY GENES
|
||||
# for (i = 0; i < 48; i++):
|
||||
# mutation = 0
|
||||
# # CHECK MUTATION
|
||||
# if i % 4 == 0:
|
||||
# gene1 = mGene[i]
|
||||
# gene2 = sGene[i]
|
||||
# if gene1 > gene2:
|
||||
# gene1, gene2 = gene2, gene1
|
||||
# if (gene2 - gene1) == 1 and iseven(gene1):
|
||||
# probability = 0.25
|
||||
# if gene1 > 23:
|
||||
# probability /= 2
|
||||
# if random() < probability:
|
||||
# mutation = (gene1 / 2) + 16
|
||||
# # GIVE BABY GENES
|
||||
# if mutation:
|
||||
# baby[i] = mutation
|
||||
# else:
|
||||
# if random() < 0.5:
|
||||
# babyGenes[i] = mGene[i]
|
||||
# else:
|
||||
# babyGenes[i] = sGene[i]
|
||||
|
||||
|
||||
|
||||
def mixgenes( mgenes, sgenes ) ## returns babygenes
|
||||
## note: reverse genes strings (in kai) so index 0 is the first number
|
||||
## index 1 is the second number etc.
|
||||
mgenes = mgenes.reverse
|
||||
sgenes = sgenes.reverse
|
||||
|
||||
babygenes = "?"*48 ## string with 48 question marks (?)
|
||||
|
||||
# PARENT GENE SWAPPING
|
||||
12.times do |i| # loop from 0 to 11 # for(i = 0; i < 12; i++)
|
||||
puts "parent gene swapping i: #{i}"
|
||||
index = 4*i # index = 4 * i
|
||||
3.downto(1) do |j| ## loop from 3 to 1 # for (j = 3; j > 0; j--)
|
||||
puts " j: #{j}"
|
||||
if rand(100) < 25 # if random() < 0.25:
|
||||
mgenes[index+j-1], mgenes[index+j] = # swap(mGenes, index+j, index+j-1)
|
||||
mgenes[index+j], mgenes[index+j-1]
|
||||
end
|
||||
if rand(100) < 25 # if random() < 0.25:
|
||||
sgenes[index+j-1], sgenes[index+j] = # swap(sGenes, index+j, index+j-1)
|
||||
sgenes[index+j], sgenes[index+j-1]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# BABY GENES
|
||||
48.times do |i| # loop from 0 to 47 # for (i = 0; i < 48; i++):
|
||||
puts "baby genes i: #{i}"
|
||||
mutation = nil # mutation = 0
|
||||
# # CHECK MUTATION
|
||||
if i % 4 == 0 # if i % 4 == 0:
|
||||
gene1 = Kai::NUMBER[ mgenes[i] ] # gene1 = mGene[i]
|
||||
gene2 = Kai::NUMBER[ sgenes[i] ] # gene2 = sGene[i]
|
||||
if gene1 > gene2 # if gene1 > gene2:
|
||||
gene1, gene2 = gene2, gene1 # gene1, gene2 = gene2, gene1
|
||||
end
|
||||
if (gene2 - gene1) == 1 && gene1.even? # if (gene2 - gene1) == 1 and iseven(gene1):
|
||||
probability = 25 # probability = 0.25
|
||||
if gene1 > 23 # if gene1 > 23:
|
||||
probability /= 2 # probability /= 2
|
||||
end
|
||||
if rand(100) < probability # if random() < probability:
|
||||
mutation = Kai::ALPHABET[ (gene1/2)+16 ] # mutation = (gene1 / 2) + 16
|
||||
end
|
||||
end
|
||||
end
|
||||
# GIVE BABY GENES
|
||||
if mutation # if mutation:
|
||||
babygenes[i]=mutation # baby[i] = mutation
|
||||
else # else:
|
||||
if rand(100) < 50 # if random() < 0.5:
|
||||
babygenes[i] = mgenes[i] # babyGenes[i] = mGene[i]
|
||||
else # else:
|
||||
babygenes[i] = sgenes[i] # babyGenes[i] = sGene[i]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
babygenes.reverse # return bagygenes (reversed back)
|
||||
end # mixgenes
|
||||
|
||||
|
||||
### let's add base32 / kai helper class
|
||||
|
||||
class Base32 ## Base32 (2^5 - 5bits)
|
||||
|
||||
# See https://en.wikipedia.org/wiki/Base58
|
||||
ALPHABET = "123456789abcdefghijkmnopqrstuvwx"
|
||||
BASE = ALPHABET.length ## 32 chars/letters/digits
|
||||
|
||||
# Converts a base10 integer to a base32 string.
|
||||
def self.encode( num )
|
||||
buf = String.new
|
||||
while num >= BASE
|
||||
mod = num % BASE
|
||||
buf = ALPHABET[mod] + buf
|
||||
num = (num - mod)/BASE
|
||||
end
|
||||
ALPHABET[num] + buf
|
||||
end
|
||||
|
||||
NUMBER = {
|
||||
'1' => 0, '2' => 1, '3' => 2, '4' => 3, '5' => 4, '6' => 5, '7' => 6, '8' => 7,
|
||||
'9' => 8, 'a' => 9, 'b' => 10, 'c' => 11, 'd' => 12, 'e' => 13, 'f' => 14, 'g' => 15,
|
||||
'h' => 16, 'i' => 17, 'j' => 18, 'k' => 19, 'm' => 20, 'n' => 21, 'o' => 22, 'p' => 23,
|
||||
'q' => 24, 'r' => 25, 's' => 26, 't' => 27, 'u' => 28, 'v' => 29, 'w' => 30, 'x' => 31
|
||||
}
|
||||
|
||||
def self.fmt( kai )
|
||||
## format in groups of four (4) separated by space
|
||||
## e.g. ccac7787fa7fafaa16467755f9ee444467667366cccceede
|
||||
## : ccac 7787 fa7f afaa 1646 7755 f9ee 4444 6766 7366 cccc eede
|
||||
kai.reverse.gsub( /(.{4})/, '\1 ').reverse.strip
|
||||
end
|
||||
end # class Base32
|
||||
|
||||
|
||||
## add a shortcut (convenience) alias
|
||||
Kai = Base32
|
||||
# why kai?
|
||||
# in honor of Kai Turner who deciphered the genes - thanks!
|
||||
# see https://medium.com/@kaigani/the-cryptokitties-genome-project-on-dominance-inheritance-and-mutation-b73059dcd0a4
|
||||
|
||||
|
||||
|
||||
#####################
|
||||
# let's go
|
||||
|
||||
mgenes_hex = 0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c
|
||||
sgenes_hex = 0x00005a13429085339c6521ef0300011c82438c628cc431a63298e3721f772d29
|
||||
|
||||
|
||||
mgenes = Kai.encode( mgenes_hex ) # convert to 5-bit (base32/kai) notation
|
||||
p mgenes
|
||||
# => "ddca578ka4f7949p4d11535kaeea175h846k2243aa9gfdcd"
|
||||
p Kai.fmt( mgenes )
|
||||
# => "ddca 578k a4f7 949p 4d11 535k aeea 175h 846k 2243 aa9g fdcd"
|
||||
p mgenes.size
|
||||
# => 48
|
||||
|
||||
sgenes = Kai.encode( sgenes_hex )
|
||||
p sgenes
|
||||
# => "c9am65567ff7b9gg1d1138539f77647577k46784f9gpfcaa"
|
||||
p Kai.fmt( sgenes )
|
||||
# => "c9am 6556 7ff7 b9gg 1d11 3853 9f77 6475 77k4 6784 f9gp fcaa"
|
||||
p sgenes.size
|
||||
# => 48
|
||||
|
||||
babygenes = mixgenes( mgenes, sgenes )
|
||||
p babygenes
|
||||
# => "9dca5586aff7b99p1d1133k5aea767h574kk6744aafgffaa"
|
||||
p Kai.fmt( babygenes )
|
||||
# => "9dca 5586 aff7 b99p 1d11 33k5 aea7 67h5 74kk 6744 aafg ffaa"
|
Before Width: | Height: | Size: 79 KiB |
Before Width: | Height: | Size: 197 KiB |
Before Width: | Height: | Size: 47 KiB |
Before Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 32 KiB |
Before Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 98 KiB |
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 57 KiB |
Before Width: | Height: | Size: 50 KiB |
Before Width: | Height: | Size: 42 KiB |
Before Width: | Height: | Size: 53 KiB |
Before Width: | Height: | Size: 92 KiB |
Before Width: | Height: | Size: 833 KiB |
Before Width: | Height: | Size: 338 KiB |
Before Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 137 KiB |
Before Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 50 KiB |
BIN
i/cyperpunks.png
Before Width: | Height: | Size: 636 KiB |
BIN
i/dappradar.png
Before Width: | Height: | Size: 307 KiB |
Before Width: | Height: | Size: 133 KiB |
Before Width: | Height: | Size: 18 KiB |
|
@ -0,0 +1,34 @@
|
|||
{
|
||||
"name": "cryptokitties-xdai-demo",
|
||||
"version": "1.0.0",
|
||||
"repository": "https://github.com/poanetwork/cryptokitties-xdai-demo.git",
|
||||
"license": "GPL-3.0-only",
|
||||
"scripts": {
|
||||
"compile": "truffle compile",
|
||||
"flatten": "bash scripts/flatten.sh",
|
||||
"deploy": "node deploy/index.js",
|
||||
"lint": "eslint ."
|
||||
},
|
||||
"dependencies": {
|
||||
"bignumber.js": "^9.0.0",
|
||||
"dotenv": "^8.1.0",
|
||||
"ethereumjs-tx": "1.3.7",
|
||||
"node-fetch": "^2.6.0",
|
||||
"truffle": "^5.0.35",
|
||||
"web3": "^1.2.1",
|
||||
"web3-utils": "^1.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^6.4.0",
|
||||
"eslint-config-airbnb-base": "^14.0.0",
|
||||
"eslint-config-prettier": "^6.3.0",
|
||||
"eslint-plugin-import": "^2.18.2",
|
||||
"eslint-plugin-node": "^10.0.0",
|
||||
"eslint-plugin-prettier": "^3.1.0",
|
||||
"prettier": "^1.18.2",
|
||||
"truffle-flattener": "^1.4.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.9"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
if [ -d flats ]; then
|
||||
rm -rf flats
|
||||
fi
|
||||
|
||||
mkdir -p flats/kitty
|
||||
|
||||
FLATTENER=./node_modules/.bin/truffle-flattener
|
||||
KITTY_CONTRACTS_DIR=contracts/kitty
|
||||
|
||||
|
||||
echo "Flattening kitty contracts"
|
||||
${FLATTENER} ${KITTY_CONTRACTS_DIR}/KittyCore.sol > flats/kitty/KittyCore_flat.sol
|
||||
${FLATTENER} ${KITTY_CONTRACTS_DIR}/GeneScience.sol > flats/kitty/GeneScience_flat.sol
|
||||
${FLATTENER} ${KITTY_CONTRACTS_DIR}/SaleClockAuction.sol > flats/kitty/SaleClockAuction_flat.sol
|
||||
${FLATTENER} ${KITTY_CONTRACTS_DIR}/SiringClockAuction.sol > flats/kitty/SiringClockAuction_flat.sol
|
|
@ -0,0 +1,95 @@
|
|||
/**
|
||||
* Use this file to configure your truffle project. It's seeded with some
|
||||
* common settings for different networks and features like migrations,
|
||||
* compilation and testing. Uncomment the ones you need or modify
|
||||
* them to suit your project as necessary.
|
||||
*
|
||||
* More information about configuration can be found at:
|
||||
*
|
||||
* truffleframework.com/docs/advanced/configuration
|
||||
*
|
||||
* To deploy via Infura you'll need a wallet provider (like truffle-hdwallet-provider)
|
||||
* to sign your transactions before they're sent to a remote public node. Infura accounts
|
||||
* are available for free at: infura.io/register.
|
||||
*
|
||||
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
|
||||
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
|
||||
* phrase from a file you've .gitignored so it doesn't accidentally become public.
|
||||
*
|
||||
*/
|
||||
|
||||
// const HDWalletProvider = require('truffle-hdwallet-provider');
|
||||
// const infuraKey = "fj4jll3k.....";
|
||||
//
|
||||
// const fs = require('fs');
|
||||
// const mnemonic = fs.readFileSync(".secret").toString().trim();
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* Networks define how you connect to your ethereum client and let you set the
|
||||
* defaults web3 uses to send transactions. If you don't specify one truffle
|
||||
* will spin up a development blockchain for you on port 9545 when you
|
||||
* run `develop` or `test`. You can ask a truffle command to use a specific
|
||||
* network from the command line, e.g
|
||||
*
|
||||
* $ truffle test --network <network-name>
|
||||
*/
|
||||
|
||||
networks: {
|
||||
// Useful for testing. The `development` name is special - truffle uses it by default
|
||||
// if it's defined here and no other network is specified at the command line.
|
||||
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
|
||||
// tab if you use this network and you must also set the `host`, `port` and `network_id`
|
||||
// options below to some value.
|
||||
//
|
||||
// development: {
|
||||
// host: "127.0.0.1", // Localhost (default: none)
|
||||
// port: 8545, // Standard Ethereum port (default: none)
|
||||
// network_id: "*", // Any network (default: none)
|
||||
// },
|
||||
// Another network with more advanced options...
|
||||
// advanced: {
|
||||
// port: 8777, // Custom port
|
||||
// network_id: 1342, // Custom network
|
||||
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
|
||||
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
|
||||
// from: <address>, // Account to send txs from (default: accounts[0])
|
||||
// websockets: true // Enable EventEmitter interface for web3 (default: false)
|
||||
// },
|
||||
// Useful for deploying to a public network.
|
||||
// NB: It's important to wrap the provider as a function.
|
||||
// ropsten: {
|
||||
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
|
||||
// network_id: 3, // Ropsten's id
|
||||
// gas: 5500000, // Ropsten has a lower block limit than mainnet
|
||||
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
|
||||
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
|
||||
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
|
||||
// },
|
||||
// Useful for private networks
|
||||
// private: {
|
||||
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
|
||||
// network_id: 2111, // This network is yours, in the cloud.
|
||||
// production: true // Treats this network as if it was a public net. (default: false)
|
||||
// }
|
||||
},
|
||||
|
||||
// Set default mocha options here, use special reporters etc.
|
||||
mocha: {
|
||||
// timeout: 100000
|
||||
},
|
||||
|
||||
// Configure your compilers
|
||||
compilers: {
|
||||
solc: {
|
||||
version: '0.4.24',
|
||||
settings: {
|
||||
optimizer: {
|
||||
enabled: false,
|
||||
runs: 200
|
||||
},
|
||||
evmVersion: 'byzantium'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|