Full Code of makerdao/sai for AI

master 8b7a7359f402 cached
104 files
245.7 KB
70.1k tokens
1 requests
Download .txt
Showing preview only (268K chars total). Download the full file or copy to clipboard to get everything.
Repository: makerdao/sai
Branch: master
Commit: 8b7a7359f402
Files: 104
Total size: 245.7 KB

Directory structure:
gitextract__3pdc6gn/

├── .gitattributes
├── .gitignore
├── .gitmodules
├── COPYING
├── DEVELOPING.md
├── Makefile
├── README.md
├── bin/
│   ├── deploy
│   ├── deploy-fab
│   ├── deploy-kovan
│   ├── deploy-pre
│   └── sai
├── libexec/
│   └── sai/
│       ├── sai
│       ├── sai---help
│       ├── sai-air
│       ├── sai-axe
│       ├── sai-bite
│       ├── sai-boom
│       ├── sai-bust
│       ├── sai-cage
│       ├── sai-caged
│       ├── sai-cap
│       ├── sai-cash
│       ├── sai-chi
│       ├── sai-cup
│       ├── sai-cupi
│       ├── sai-cups
│       ├── sai-din
│       ├── sai-draw
│       ├── sai-drip
│       ├── sai-exit
│       ├── sai-fee
│       ├── sai-fit
│       ├── sai-fix
│       ├── sai-fog
│       ├── sai-free
│       ├── sai-gem
│       ├── sai-give
│       ├── sai-gov
│       ├── sai-heal
│       ├── sai-help
│       ├── sai-ink
│       ├── sai-join
│       ├── sai-joy
│       ├── sai-lad
│       ├── sai-lock
│       ├── sai-mat
│       ├── sai-off
│       ├── sai-open
│       ├── sai-out
│       ├── sai-par
│       ├── sai-pep
│       ├── sai-per
│       ├── sai-pie
│       ├── sai-pip
│       ├── sai-pit
│       ├── sai-prod
│       ├── sai-rap
│       ├── sai-ray
│       ├── sai-rhi
│       ├── sai-rho
│       ├── sai-s2s
│       ├── sai-safe
│       ├── sai-sai
│       ├── sai-setAxe
│       ├── sai-setCap
│       ├── sai-setFee
│       ├── sai-setMat
│       ├── sai-setTapGap
│       ├── sai-setTax
│       ├── sai-setTubGap
│       ├── sai-setWay
│       ├── sai-shut
│       ├── sai-sin
│       ├── sai-skr
│       ├── sai-tab
│       ├── sai-tag
│       ├── sai-tapAsk
│       ├── sai-tapBid
│       ├── sai-tapGap
│       ├── sai-tau
│       ├── sai-tax
│       ├── sai-tubAsk
│       ├── sai-tubBid
│       ├── sai-tubGap
│       ├── sai-vent
│       ├── sai-vox
│       ├── sai-wad
│       ├── sai-way
│       ├── sai-wipe
│       └── sai-woe
└── src/
    ├── fab.sol
    ├── fab.t.sol
    ├── mom.sol
    ├── pit.sol
    ├── sai.t.sol
    ├── spell.t.sol
    ├── tap.sol
    ├── top.sol
    ├── tub.sol
    ├── tub.t.sol
    ├── vox.sol
    ├── vox.t.sol
    └── weth9.sol

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
*.sol linguist-language=Solidity


================================================
FILE: .gitignore
================================================
/out
load-env*
load-fab*
addresses.json


================================================
FILE: .gitmodules
================================================
[submodule "lib/ds-test"]
	path = lib/ds-test
	url = https://github.com/dapphub/ds-test
[submodule "lib/ds-token"]
	path = lib/ds-token
	url = https://github.com/dapphub/ds-token
[submodule "lib/ds-thing"]
	path = lib/ds-thing
	url = https://github.com/dapphub/ds-thing
[submodule "lib/ds-value"]
	path = lib/ds-value
	url = https://github.com/dapphub/ds-value
[submodule "lib/ds-guard"]
	path = lib/ds-guard
	url = https://github.com/dapphub/ds-guard
[submodule "lib/ds-roles"]
	path = lib/ds-roles
	url = http://github.com/dapphub/ds-roles
[submodule "lib/ds-chief"]
	path = lib/ds-chief
	url = https://github.com/dapphub/ds-chief
[submodule "lib/ds-spell"]
	path = lib/ds-spell
	url = https://github.com/dapphub/ds-spell


================================================
FILE: COPYING
================================================
                    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>.


================================================
FILE: DEVELOPING.md
================================================
# Sai Developer Documentation

This is a developer level guide to the Sai source layout and how the
different objects relate to each other.


## Introduction

Sai is Simple-Dai, a simplification of the Dai Stablecoin System
intended for field testing and refining Dai components. Sai has several
features that distinguish it from Dai:

- trusted price feed
- single collateral type
- global settlement
- liquidations at fixed price (rather than auctions)

This document is an introduction to Sai, aimed at those seeking an
understanding of the Solidity implementation.  We assume knowledge of
the [white paper], a high level overview of Dai.  A reading of the
[purple paper], the (in progress) detailed Dai technical specification
and reference implementation, is strongly encouraged but not required.

[white paper]: https://github.com/makerdao/docs/blob/master/Dai.md
[purple paper]: https://makerdao.com/purple


## Overview

Sai uses the following tokens:

- `gem`: underlying collateral (wrapped ether, in practice)
- `skr`: abstracted collateral claim
- `sai`: stablecoin
- `sin`: anticoin, created when the system takes on debt

Sai has the following core components:

- `vox`: target price feed
- `tub`: CDP record store
- `tap`: liquidation mechanism
- `top`: global settlement facilitator

Sai is configured by the following 'risk parameters':

- `way`: Sai reference price drift
- `cap`: Debt ceiling
- `mat`: Liquidation ratio
- `tax`: Stability fee
- `axe`: Liquidation penalty
- `gap`: Join/Exit and Boom/Bust spread



### `skr`: A Token Wrapper

`skr` is a token wrapper.

- `join`: deposit `gem` in return for `skr`
- `exit`: claim `gem` with their `skr`.

![Join-Exit](https://user-images.githubusercontent.com/5028/30517891-928dd4d8-9bc1-11e7-9398-639233d851ae.png)

`skr` is a simple proportional claim on a collateral pool, with the
initial `gem`<->`skr` exchange ratio being 1:1.  The essential reason
for this abstraction will be developed later, but for now it is
sufficient to see `skr` as a token with intrinsic value.

The `gem`/`skr` exchange rate is called `per`, and is calculated as the
total number of deposited `gem` divided by the total supply of SKR.

The reference price of `gem` (in practice, ETHUSD) is provided by the
`pip`, an external oracle. The `pip` is completely trusted.

The reference price of `skr` is then given by the dynamic `tag`, e.g.
the price of SKR in USD.


### `vox`: Target Price Feed

The `vox` provides the Sai *target price*, given in terms of the
reference unit, by `par`. For example, `par == 2` with USD as the
reference unit implies a target price of 2 USD per Sai.

The target price can vary in time, at a rate given by `way`, which is
the multiplicative rate of change per second.

The `vox` is the same as that in Dai, but with the sensitivity, `how`,
set to zero. Adjustments to the target price are made by adjusting the
rate of change, `way`, directly with `coax`. In future Sai iterations,
`how` may be non-zero and `way` adjustments will then follow
automatically via the feedback mechanism. The `vox` component is subject
to ongoing economic modelling research.


### `tub`: CDP Record Engine

The `tub` is the CDP record system.  An individual CDP is called a `cup`
(i.e. a small container), and has:

- `lad`: an owner
- `ink`: locked SKR collateral
- `art`: debt

It is crucial to know whether a CDP is well collateralised or not:
`safe(cup)` returns a boolean indicating this.

`safe` aggregates price information from the `vox` and the `tub` and
compares the reference value of a CDPs debt and collateral.

The following `tub` acts are not possible if they would transition a CDP
to unsafe:

---

![Open | Give](https://user-images.githubusercontent.com/5028/30352570-b4c0f6a2-9874-11e7-8ca3-336531da4c0d.png)

- `open`: create a new CDP
- `give`: transfer ownership (changes `lad`)
---

![Lock-Free](https://user-images.githubusercontent.com/5028/30517892-928e06ec-9bc1-11e7-91e8-6ae6caae8585.png)


- `lock`: deposit SKR collateral (increases `ink`)
- `free`: withdraw SKR collateral (decreases `ink`)

---

![Draw | Wipe](https://user-images.githubusercontent.com/5028/30463893-97a6aef4-9a22-11e7-9a65-3055ad05b8d6.png)

- `draw`: create Sai (increases `art`, `rum`)
- `wipe`: return Sai (decreases `art`, `rum`)

---

- `shut`: clear all CDP debt, unlock all collateral, and delete the record

---

<img src="https://user-images.githubusercontent.com/5028/30519068-6c871ed2-9be1-11e7-83df-3cbda6a49e3b.png" width="600" />

- `bite`: liquidate CDP (zeros `art`, decreases `ink`, mints `sin` to `tap`)

Unsafe CDPs need to be liquidated. When a `cup` is not `safe`, anyone
can perform `bite(cup)`, which takes on all CDP debt and confiscates
sufficient collateral to cover this, plus a buffer.

This returns the CDP to a safe state (possibly with zero collateral).
There are other possible implementations of `bite`, e.g. only taking
sufficient collateral to just transition the CDP to safe, but the
described implementation is chosen for simplicity.

`bite` mints the `sin` associated with the CDP to the `tap` - the
liquidator.

---


### `tap`: The Liquidator

The `tap` is a liquidator. It has three token balances that determine
its allowed behaviour:

- `joy`: Sai balance, surplus transferred from `drip`
- `woe`: Sin balance, bad debt transferred from `bite`
- `fog`: SKR balance, collateral pending liquidation

and one derived price, `s2s`, which is the price of SKR in Sai. The
`tap` seeks to minimise all of its token balances. Recall that Sai can
be canceled out with Sin via `heal`.

The `tap` has two acts:

- `boom`: sell Sai in return for SKR (decreases `joy` and `woe`, decreases SKR supply)
- `bust`: sell SKR in return for Sai (decreases `fog`, increases `joy` and `woe`, can increase SKR supply)

`boom` is the simpler function and can be thought of as buy and burn.
Given a net Sai balance, sell the Sai in return for SKR, which is
burned.

<img src="https://user-images.githubusercontent.com/5028/30517887-924bec1c-9bc1-11e7-8c25-6d73a1c48340.png" width="500" />

`bust` is really two functions in one: collateral sell off (aka `flip`),
and inflate and sell (aka `flop`). When `fog` is non zero it is sold in
return for Sai, which is used to cancel out the bad debt, `woe`. If
`fog` is zero but the `tap` has a net Sin balance, then SKR is minted
and sold in return for Sai, up to the point that the net Sin balance is
zero.

![Bust](https://user-images.githubusercontent.com/5028/30517888-9287dd76-9bc1-11e7-8726-6b21843e27a5.png)

Through `boom` and `bust` we close the feedback loop on the price of
SKR. When there is surplus Sai, SKR is burned, decreasing the SKR supply
and increasing `per`, giving SKR holders more GEM per SKR. When there is
surplus Woe, SKR is inflated, increasing the SKR supply and decreasing
`per`, giving SKR holders less GEM per SKR.

The reason for wrapping GEM in SKR is now apparent: *it provides a way
to socialise losses and gains incurred in the operation of the system.*

Two features of this mechanism:

1. Whilst SKR can be inflated significantly, there is a finite limit on
   the amount of bad debt the system can absorb - given by the value of
   the underlying GEM collateral.

2. There is a negative feedback between `bust` and `bite`: as SKR is
   inflated it becomes less valuable, reducing the safety level of CDPs.
   Some CDPs will become unsafe and be vulnerable to liquidation,
   creating more bad debt. In an active market, CDP holders will have to
   be vigilant about the potential for SKR inflation if they are holding
   tightly collateralised CDPs.


### `top`: Global Settlement Manager

A key feature of Sai is the possibility of `cage`: shutting down the
system and reimbursing Sai holders. This is provided for easy upgrades
between Sai iterations, and for security in case of implementation flaws
- both in the code and in the design.

An admin can use the `top` to `cage` the system at a specific price (sai
per gem), or by reading the last price from the price feed.

<img src="https://user-images.githubusercontent.com/5028/30519069-6c9ae656-9be1-11e7-9e3f-e75f585024f7.png" width="600" />

First, sufficient real `gem` collateral is taken such that Sai holders
can redeem their Sai at face value. The `gem` is moved from the `tub` to
the `tap` and the `tap.cash` function is unlocked for Sai holders to
call.

![Cash](https://user-images.githubusercontent.com/5028/30519070-6cc4fd6a-9be1-11e7-92d8-5d965721d8ef.png)

Any remaining `gem` remains in the `tub`. SKR holders can now `exit`.
CDP holders must first `bite` their CDPs (although anyone can do this)
and then `free` their SKR.

Some important features of `cage`:

- Sai holders are not guaranteed their face value, only preferential payout.
- *the full real collateral pool is tapped* to make Sai whole. SKR is a
  *risk-bearing* token.
- SKR holders will receive a poor rate if they try to `exit` before all
  CDPs are processed by `bite`. To prevent accidental early `exit`,
  `top.flow` is provided, which will only enable `exit` after all CDPs
  are processed, or a timeout has expired.

The `top` also serves as a useful frontend entrypoint to the system, as it
links to all other components.

### `drip`, `rum`, `art` and `chi`: Dynamic Fee Accumulation

In a simpler system with no interest rates, we could denominate CDP debt,
the `tab`, directly in `sin`. However with non zero interest, `tab` is a
dynamic quantity, computed from `art`, a rate-normalised per-CDP debt unit,
and `chi`, the product of accumulated rates that converts `art` into a real
debt amount. `rum` is the total `art` across all CDPs, and can be used
to determine the total debt backed by CDPs, `din`.

```
tab(cdp) = cdp.art * chi
```

The internal debt price, `chi`, is dynamic and is updated by the `drip`
act, which also collects unprocessed revenue.

The `chi` abstraction allows us to compute the per CDP debt, and the
total unprocessed revenue, with varying `tax`, in constant time.

<img src="https://user-images.githubusercontent.com/5028/30517890-928d0094-9bc1-11e7-936c-544f5bc4d197.png" width="600" />

## Governance Fee

This version of Sai (aka Dai v1) is collectively governed by the holders of
a token, `gov`. The specifics of the governance mechanism are
out of scope for this document. The `gov` token is also used to pay usage
fees: the `fee` is similar to the `tax`, and causes the `rhi` accumulator to
increase relative to `chi`. The difference between `rhi` and `chi` can be
used to determine the total outstanding fee, the `rap`. Fees are paid on
`wipe`, and the amount payable is scaled with the amount wiped.

Fees are paid in `gov`, but the outstanding fee is denominated in Sai.
Therefore we need a price feed for `gov`: this is the `pep`. The mechanism
in `wipe` is meant to be robust against failure of the `pep` feed.

Importantly, unpaid fees _are not_ used to determine a CDPs safety (this may
change in a future release).


## Auth setup

Sai is designed with two authorities, `dad` and `chief`.

- `dad` is a DSGuard, and is used for internal contract-contract
  permissions, allowing e.g. the `tub` to `mint` and `burn` Sai. `dad`
  is the authority of the `tub` and `tap`, and also `sai`, `sin` and
  `skr`.

- `chief` restricts access to `top` and `mom`, which are the admin
  interfaces to the system. `chief` is intended to be a DSRoles
  instance, but any authority implementation could be used.


## Deployment

Sai is a complex multi-contract system and has a slightly involved
deployment process. The prerequisities to the deployment are:

1. `pip`, a collateral price feed
2. `pep`, a governance price feed
3. `gem`, a collateral token
4. `pit`, a token burner
5. `chief`, the external authority

For testing purposes, `bin/deploy` will create the prerequisites for you
if you don't supply them.

In addition, Sai utilises on-chain deployers, called fabs, for creating
fresh basic components on chain. These are defined in `fab.sol`.

The main contract deployment is defined in `DaiFab`, and requires
multiple calls because of the size of the contracts.

The full contracts can be deployed to e.g.  ethlive with the following,
after which the contract addresses will be saved in `load-env-ethlive`.

```
bin/deploy-fab
. load-fab-ethlive
bin/deploy
```


## Glossary

### Prices

- `per`: gem per skr
- `par`: ref per sai
- `tag`: ref per skr
- `pip`: ref per gem
- `fix`: gem per sai after `cage`
- `fit`: ref per skr after `cage`

### Meme Mnemonics

- `pip`: trading pips
- `cup`: small container for CDP info
- `tub`: larger container for cups
- `tap`: liquidity provider
- `top`: top-level system manager

- `way`: which way the target price is heading
- `cap`: upper limit of Sai issuance
- `mat`: lower limit of collateralisation
- `tax`: continually paid by CDP holders
- `axe`: penalty applied to bad CDP holders
- `gap`: gap between buy and sell

- `pie`: Real collateral that SKR holders share
- `air`: Abstracted Collateral backing CDPs
- `ice`: Debt that is locked up with CDPs
- `fog`: Murky liquidated `air`that we want to get rid of
- `joy`: SKR holders are happy about this Sai surplus
- `woe`: SKR holders are sad about this Sin debt


================================================
FILE: Makefile
================================================
all:; dapp build
test:; dapp test

SHELL = bash
dirs = {bin,libexec}
prefix ?= /usr/local

dirs:; mkdir -p $(prefix)/$(dirs)
files = $(shell ls -d $(dirs)/*)
install:; cp -r -n $(dirs) $(prefix)
link: dirs; for x in $(files); do ln -s `pwd`/$$x $(prefix)/$$x; done
uninstall:; rm -r $(addprefix $(prefix)/,$(files))

check:; ! grep '^#!/bin/sh' libexec/*/* && \
grep '^#!/usr/bin/env bash' libexec/*/* | \
cut -d: -f1 | xargs shellcheck


================================================
FILE: README.md
================================================



_Please note that this document temporarily refers to sai instead of dai and skr instead of peth. These are just different variable names and their functionality is identical to what is described in the latest Dai documentation._


`sai` is a simple single-collateral stablecoin that is dependent on a
trusted oracle address and has a kill-switch.

See the [developer documentation](DEVELOPING.md) for a more technical
overview.

There are four tokens in the system:

- `gem`: externally valuable token e.g. ETH
- `gov`: governance token e.g. MKR
- `skr`: a claim to locked `gem`s
- `sai`: the stablecoin, a variable claim on some quantity of `gem`s

Collateral holders deposit their collateral using `join` and receive
`skr` tokens proportional to their deposit. `skr` can be redeemed for
collateral with `exit`. You will get more or less `gem` tokens for each
`skr` depending whether the system made a profit or loss while you
were exposed.

The oracle updates the GEM:REF and GOV:REF price feeds. These are the
only external real-time input to the system.

`skr` is used as the direct backing collateral for CDPs. A prospective
issuer can `open` an empty position, `lock` some `skr` and then `draw`
some `sai`. Debt is covered with `wipe`. Collateral can be reclaimed
with `free` as long as the CDP remains "safe".

If the value of the collateral backing the CDP falls below the
liquidation ratio `mat`, the CDP is vulnerable to liquidation via
`bite`. On liquidation, the CDP `skr` collateral is sold off to cover
the `sai` debt.

Under-collateralized CDPs can be liquidated with `bite`. Liquidation is
immediate: backing `skr` is taken to cover the `sai` debt at the time of
`bite`, plus a liquidation fee (`axe`); any excess remains in the CDP.

`skr` seized from bad CDPs can be purchased with `bust`, in exchange for
`sai` at the `s2s` price. This `sai` pays down the bad CDP debt.

Any remaining Sai surplus (`joy`) can be purchased with `boom`, in
exchange for `skr` at the `s2s` price. This `skr` is burned.


### Fees

Stability fee is continuously charged on all open cups according to `tax`.
It makes their debt (`tab`) increase over time.

Governance fee is continuously charged on all open cups according to `fee`.
It makes their debt (`rap`) increase over time.

### Settlement

`sai` can be shut down at a given price with `cage`, after which `sai`
and `skr` can be exchanged for `gems` via `cash`. All outstanding `cups`
are liquidated and the *entire pool* of `gem` is tapped to redeem `sai`
at their face value, as if the boom/bust trades were instantly settled
at the cage price.  Any remaining `gems` are shared between `skr`
holders.

Practically this means that if the system is undercollateralized on
`cage`, holders of free `skr` will have their `gem` share diluted as
much as necessary to make `sai` whole. *In other words, `skr` is a
risk bearing token*.

Excess collateral contained within a single `cup` can be reclaimed with
`bite(cup)`.


### `sai` glossary (`sai help`)
```
Actions:

   bite            initiate liquidation of an undercollateral cup
   boom            buy some amount of sai to process joy (surplus)
   bust            sell some amount of sai to process woe (bad debt)
   cage            lock the system and initiate settlement
   cash            cash in sai balance for gems after cage
   cupi            get the last cup id
   cups            list cups created by you
   draw            issue the specified amount of sai stablecoins
   drip            recalculate the internal debt price
   exit            sell SKR for gems
   free            remove excess SKR collateral from a cup
   give            transfer ownership of a cup
   heal            cancel debt
   help            print help about sai(1) or one of its subcommands
   join            buy SKR for gems
   lock            post additional SKR collateral to a cup
   open            create a new cup (collateralized debt position)
   prod            recalculate the accrued holder fee (par)
   safe            determine if a cup is safe
   setAxe          update the liquidation penalty
   setFee          update the governance fee
   setCap          update the debt ceiling
   setMat          update the liquidation ratio
   setTapGap       update the spread on `boom` and `bust`
   setTax          update the stability fee
   setTubGap       update the spread on `join` and `exit`
   setWay          update the holder fee (interest rate)
   shut            close a cup
   vent            process a caged tub
   wipe            repay some portion of your existing sai debt
   
Vars, Getters, Utils:

   air             get the amount of backing collateral
   axe             get the liquidation penalty
   caged           get time of cage event (= 0 if system is not caged)
   chi             get the internal debt price
   cup             show the cup info
   fee             get the governance fee
   fit             get the gem per skr settlement price
   fix             get the gem per sai settlement price
   fog             get the amount of skr pending liquidation
   gem             get the collateral token
   gov             get the governance token
   cap             get the debt ceiling
   ice             get the good debt
   ink             get the amount of skr collateral locked in a cup
   joy             get the amount of surplus sai
   lad             get the owner of a cup
   mat             get the liquidation ratio
   off             get the cage flag
   out             get the post cage exit flag
   par             get the accrued holder fee (ref per sai)
   per             get the current entry price (gem per skr)
   pie             get the amount of raw collateral
   pep             get the gov price feed
   pip             get the gem price feed
   pit             get the liquidator vault
   rap             get the amount of governance debt in a cup
   ray             parse and display a 27-decimal fixed-point number
   rho             get the time of last drip
   rhi             get the internal debt price (governance included)
   s2s             get the skr per sai rate (for boom and bust)
   sai             get the sai token
   sin             get the sin token
   skr             get the skr token
   tab             get the amount of debt in a cup
   tag             get the reference price (ref per skr)
   tapAsk          get the amount of skr in sai for bust
   tapBid          get the amount of skr in sai for boom
   tapGap          get the spread on `boom` and `bust`
   tau             get the time of last prod
   tax             get the stability fee
   tubAsk          get the amount of skr in gem for join
   tubBid          get the amount of skr in gem for exit
   tubGap          get the spread on `join` and `exit`
   vox             get the target price engine
   wad             parse and display a 18-decimal fixed-point number
   way             get the holder fee (interest rate)
   woe             get the amount of bad debt


```

### Sample interaction using `sai`

```bash
$ export ETH_FROM=0x(...)
$ export SAI_TUB=0x(...)

# Give the system access to our GEM (W-ETH), SKR and SAI balances
# so we can join()/exit() and also draw()/wipe() sai
$ token approve $(sai gem) $(sai tub) $(seth --to-wei 1000000000 ETH)
$ token approve $(sai skr) $(sai tub) $(seth --to-wei 1000000000 ETH)
$ token approve $(sai sai) $(sai tub) $(seth --to-wei 1000000000 ETH)

# If we also plan on using boom() and bust(), a different component
# (called `tap`) will need to have access to our SKR and SAI balances
$ token approve $(sai skr) $(sai tap) $(seth --to-wei 1000000000 ETH)
$ token approve $(sai sai) $(sai tap) $(seth --to-wei 1000000000 ETH)

# We need to have some GEM (W-ETH) balance to start with
$ token balance $(sai gem) $ETH_FROM
2.467935274974511817

# Join the system by exchanging some GEM (W-ETH) to SKR
$ sai join 2.2
Generating 2.200000000000000000 SKR depositing GEM...
$ token balance $(sai gem) $ETH_FROM
0.267935274974511817
$ token balance $(sai skr) $ETH_FROM
2.200000000000000000

# Open a new cup
$ sai open
Opening cup...
Opened cup 62

# We can list our cups at all times
$ sai cups																
Cups created by you...
62

# Lock some SKR collateral in the cup and then draw some SAI from it
$ sai --cup 62 lock 1.5													
Locking 1.500000000000000000 SKR in cup 62...
$ sai --cup 62 draw 89.0												
Drawing 89.000000000000000000 SAI from cup 62...
$ token balance $(sai skr) $ETH_FROM
0.700000000000000000
$ token balance $(sai sai) $ETH_FROM
89.000000000000000000

# We can examine the cup details, `tab` and `ink` representing
# the amount of debt and the amount of collateral respectively
$ sai --cup 62 cup														
cup id 62...
lad: 0x(...)
ink: 1.500000000000000000
tab: 89.000000000000000000
rap: 0.000000000000000000

# We can check whether the cup is still safe
# (ie. whether the value of collateral locked is high enough)
$ sai --cup 62 safe
true

# At some point we will want to wipe our SAI debt
# which means we can also free the SKR collateral
$ sai --cup 62 wipe 59.0												
Wiping 59.000000000000000000 SAI from cup 62...
$ sai --cup 62 free 1.1													
Freeing 1.100000000000000000 SKR from cup 62...
$ token balance $(sai skr) $ETH_FROM
1.800000000000000000
$ token balance $(sai sai) $ETH_FROM
30.000000000000000000

# The `tab` and `ink` values have changed
$ sai --cup 62 cup
cup id 62...
lad: 0x(...)
ink: 0.400000000000000000
tab: 30.000000000000000000
rap: 0.000000000000000000

# We can also `wipe` and `free` outstanding balances of SAI and SKR by calling `shut`
$ sai --cup 62 shut
Closing cup 62...

$ sai --cup 62 cup
cup id 62...
lad: 0x0000000000000000000000000000000000000000
ink: 0.000000000000000000
tab: 0.000000000000000000
rap: 0.000000000000000000

# Exit the system by exchanging SKR back to GEM (W-ETH)
$ sai exit 2.2
Sending 2.200000000000000000 SKR to TUB...
$ token balance $(sai gem) $ETH_FROM
2.467935274974511817
$ token balance $(sai skr) $ETH_FROM
0.000000000000000000
```

### Dai v1 Current deployments

Names for tokens:
  - Dai: `SAI_SAI`
  - MKR: `SAI_GOV`
  - WETH: `SAI_GEM`
  - PETH: `SAI_SKR`

Mainnet:

```bash
# sai deployment on ethlive from c2031c0f9f3a186e90b6a3c1905282f7cc58b9f5
# Mon 18 Dec 03:12:57 GMT 2017
# SAI_ADM updated 2019-06-11

export SAI_GEM=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
export SAI_GOV=0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2
export SAI_PIP=0x729D19f657BD0614b4985Cf1D82531c67569197B
export SAI_PEP=0x99041F808D598B782D5a3e498681C2452A31da08
export SAI_PIT=0x69076e44a9c70a67d5b79d95795aba299083c275
export SAI_ADM=0x9eF05f7F6deB616fd37aC3c959a2dDD25A54E4F5
export SAI_SAI=0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359
export SAI_SIN=0x79f6d0f646706e1261acf0b93dcb864f357d4680
export SAI_SKR=0xf53ad2c6851052a81b42133467480961b2321c09
export SAI_DAD=0x315cbb88168396d12e1a255f9cb935408fe80710
export SAI_MOM=0xf2c5369cffb8ea6284452b0326e326dbfdcb867c
export SAI_VOX=0x9b0f70df76165442ca6092939132bbaea77f2d7a
export SAI_TUB=0x448a5065aebb8e423f0896e6c5d525c040f59af3
export SAI_TAP=0xbda109309f9fafa6dd6a9cb9f1df4085b27ee8ef
export SAI_TOP=0x9b0ccf7c8994e19f39b2b4cf708e0a7df65fa8a3
```

Kovan:

```bash

# sai deployment on kovan from 7d9c16c056c9fc99cdf2f17bc7958837cd17ee41
# Wed Jan  3 16:06:26 -03 2018

export SAI_GEM=0xd0a1e359811322d97991e03f863a0c30c2cf029c
export SAI_GOV=0xaaf64bfcc32d0f15873a02163e7e500671a4ffcd
export SAI_PIP=0xa944bd4b25c9f186a846fd5668941aa3d3b8425f
export SAI_PEP=0x02998f73fabb52282664094b0ff87741a1ce9030
export SAI_PIT=0xbd747742b0f1f9791d3e6b85f8797a0cf4fbf10b
export SAI_ADM=0x74d41fd874234d9bea31ff6b090ba1d0b9dc8785
export SAI_SAI=0xc4375b7de8af5a38a93548eb8453a498222c4ff2
export SAI_SIN=0xdcdca4371befceafa069ca1e2afd8b925b69e57b
export SAI_SKR=0xf4d791139ce033ad35db2b2201435fad668b1b64
export SAI_DAD=0x6a884c7af48e29a20be9ff04bdde112b5596fcee
export SAI_MOM=0x72ee9496b0867dfe5e8b280254da55e51e34d27b
export SAI_VOX=0xbb4339c0ab5b1d9f14bd6e3426444a1e9d86a1d9
export SAI_TUB=0xa71937147b55deb8a530c7229c442fd3f31b7db2
export SAI_TAP=0xc936749d2d0139174ee0271bd28325074fdbc654
export SAI_TOP=0x5f00393547561da3030ebf30e52f5dc0d5d3362c
```


================================================
FILE: bin/deploy
================================================
#!/usr/bin/env bash
set -ex

export SOLC_FLAGS=${SOLC_FLAGS:-"--optimize"}
export ETH_GAS=${ETH_GAS:-"4500000"}
export ETH_FROM=${ETH_FROM:-$(seth rpc eth_coinbase)}

dapp --use solc:0.4.25 build --extract

# shellcheck disable=SC2153
{ test -z "$GEM_FAB"    || test -z "$VOX_FAB"     || test -z "$TUB_FAB" || \
  test -z "$TAP_FAB"    || test -z "$TOP_FAB"     || test -z "$MOM_FAB" || \
  test -z "$DAD_FAB"; } && \
  exit 1

test -z "$SAI_GEM" && SAI_GEM=$(dapp create DSToken "$(seth --to-bytes32 "$(seth --from-ascii 'ETH')")")
test -z "$SAI_GOV" && SAI_GOV=$(dapp create DSToken "$(seth --to-bytes32 "$(seth --from-ascii 'GOV')")")
test -z "$SAI_PIP" && SAI_PIP=$(dapp create DSValue)
test -z "$SAI_PEP" && SAI_PEP=$(dapp create DSValue)
test -z "$SAI_PIT" && SAI_PIT="0x0000000000000000000000000000000000000123"

DAI_FAB=$(dapp create DaiFab "$GEM_FAB" "$VOX_FAB" "$TUB_FAB" "$TAP_FAB" "$TOP_FAB" "$MOM_FAB" "$DAD_FAB")

if [ -z "$SAI_ADM" ]
then
    SAI_ADM=$(dapp create DSRoles)
    seth send "$SAI_ADM" 'setRootUser(address,bool)' "$ETH_FROM" true
fi

seth send "$DAI_FAB" 'makeTokens()'
seth send "$DAI_FAB" 'makeVoxTub(address,address,address,address,address)' "$SAI_GEM" "$SAI_GOV" "$SAI_PIP" "$SAI_PEP" "$SAI_PIT"
seth send "$DAI_FAB" 'makeTapTop()'
seth send "$DAI_FAB" 'configParams()'
seth send "$DAI_FAB" 'verifyParams()'
seth send "$DAI_FAB" 'configAuth(address)' "$SAI_ADM"

SAI_SAI=0x$(seth call "$DAI_FAB" 'sai()(address)')
SAI_SIN=0x$(seth call "$DAI_FAB" 'sin()(address)')
SAI_SKR=0x$(seth call "$DAI_FAB" 'skr()(address)')
SAI_DAD=0x$(seth call "$DAI_FAB" 'dad()(address)')
SAI_MOM=0x$(seth call "$DAI_FAB" 'mom()(address)')
SAI_VOX=0x$(seth call "$DAI_FAB" 'vox()(address)')
SAI_TUB=0x$(seth call "$DAI_FAB" 'tub()(address)')
SAI_TAP=0x$(seth call "$DAI_FAB" 'tap()(address)')
SAI_TOP=0x$(seth call "$DAI_FAB" 'top()(address)')

cat > "load-env-$(seth chain)" << EOF
#!/bin/bash

# sai deployment on $(seth chain) from $(git rev-parse HEAD)
# $(date)

export SAI_GEM=$SAI_GEM
export SAI_GOV=$SAI_GOV
export SAI_PIP=$SAI_PIP
export SAI_PEP=$SAI_PEP
export SAI_PIT=$SAI_PIT
export SAI_ADM=$SAI_ADM
export SAI_SAI=$SAI_SAI
export SAI_SIN=$SAI_SIN
export SAI_SKR=$SAI_SKR
export SAI_DAD=$SAI_DAD
export SAI_MOM=$SAI_MOM
export SAI_VOX=$SAI_VOX
export SAI_TUB=$SAI_TUB
export SAI_TAP=$SAI_TAP
export SAI_TOP=$SAI_TOP
EOF

cat > addresses.json << EOF
{
    "SAI_GEM": "$SAI_GEM",
    "SAI_GOV": "$SAI_GOV",
    "SAI_PIP": "$SAI_PIP",
    "SAI_PEP": "$SAI_PEP",
    "SAI_PIT": "$SAI_PIT",
    "SAI_ADM": "$SAI_ADM",
    "SAI_SAI": "$SAI_SAI",
    "SAI_SIN": "$SAI_SIN",
    "SAI_SKR": "$SAI_SKR",
    "SAI_DAD": "$SAI_DAD",
    "SAI_MOM": "$SAI_MOM",
    "SAI_VOX": "$SAI_VOX",
    "SAI_TUB": "$SAI_TUB",
    "SAI_TAP": "$SAI_TAP",
    "SAI_TOP": "$SAI_TOP"
}
EOF


================================================
FILE: bin/deploy-fab
================================================
#!/usr/bin/env bash
set -ex

export SOLC_FLAGS=${SOLC_FLAGS:-"--optimize"}
export ETH_GAS=${ETH_GAS:-"3500000"}
export ETH_FROM=${ETH_FROM:-$(seth rpc eth_coinbase)}

dapp --use solc:0.4.25 build --extract

export SETH_ASYNC=yes

ETH_NONCE=$(seth nonce "$ETH_FROM")
GEM_FABtx=$(ETH_NONCE=$ETH_NONCE dapp create GemFab)
VOX_FABtx=$(ETH_NONCE=$((ETH_NONCE + 1)) dapp create VoxFab)
TUB_FABtx=$(ETH_NONCE=$((ETH_NONCE + 2)) dapp create TubFab)
TAP_FABtx=$(ETH_NONCE=$((ETH_NONCE + 3)) dapp create TapFab)
TOP_FABtx=$(ETH_NONCE=$((ETH_NONCE + 4)) dapp create TopFab)
MOM_FABtx=$(ETH_NONCE=$((ETH_NONCE + 5)) dapp create MomFab)
DAD_FABtx=$(ETH_NONCE=$((ETH_NONCE + 6)) dapp create DadFab)

export SETH_ASYNC=no

GEM_FAB=$(seth receipt "$GEM_FABtx" contractAddress)
VOX_FAB=$(seth receipt "$VOX_FABtx" contractAddress)
TUB_FAB=$(seth receipt "$TUB_FABtx" contractAddress)
TAP_FAB=$(seth receipt "$TAP_FABtx" contractAddress)
TOP_FAB=$(seth receipt "$TOP_FABtx" contractAddress)
MOM_FAB=$(seth receipt "$MOM_FABtx" contractAddress)
DAD_FAB=$(seth receipt "$DAD_FABtx" contractAddress)

cat > "load-fab-$(seth chain)" << EOF
#!/bin/bash

# fab deployment on $(seth chain) from $(git rev-parse HEAD)
# $(date)

export GEM_FAB=$GEM_FAB
export VOX_FAB=$VOX_FAB
export TAP_FAB=$TAP_FAB
export TUB_FAB=$TUB_FAB
export TOP_FAB=$TOP_FAB
export MOM_FAB=$MOM_FAB
export DAD_FAB=$DAD_FAB
EOF


================================================
FILE: bin/deploy-kovan
================================================
#!/usr/bin/env bash

export SAI_GEM=0xd0a1e359811322d97991e03f863a0c30c2cf029c
export SAI_GOV=0xaaf64bfcc32d0f15873a02163e7e500671a4ffcd
export SAI_PIP=0xa944bd4b25c9f186a846fd5668941aa3d3b8425f
export SAI_PEP=0x02998f73fabb52282664094b0ff87741a1ce9030
export SAI_PIT=0xbd747742b0f1f9791d3e6b85f8797a0cf4fbf10b

bin/deploy-fab
. load-fab-kovan
bin/deploy


================================================
FILE: bin/deploy-pre
================================================
#!/usr/bin/env bash
set -ex

export SOLC_FLAGS=${SOLC_FLAGS:-"--optimize"}
export ETH_GAS=${ETH_GAS:-"3500000"}
export ETH_FROM=${ETH_FROM:-$(seth rpc eth_coinbase)}

dapp --use solc:0.4.25 build --extract

# ETHUSD feed
export SAI_PIP='0x729D19f657BD0614b4985Cf1D82531c67569197B'

# MKRUSD feed
export SAI_PEP='0x99041F808D598B782D5a3e498681C2452A31da08'

# WETH9
export SAI_GEM='0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'

# Token burner
SAI_PIT=$(dapp create GemPit)
export SAI_PIT

# MKR address
export SAI_GOV='0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2'

# Chief
## Voting IOU
SAI_IOU=$(dapp create DSToken "$(seth --to-bytes32 "$(seth --from-ascii 'IOU')")")
SAI_ADM=$(dapp create DSChief "$SAI_GOV" "$SAI_IOU" 5)
export SAI_IOU
export SAI_ADM
seth send "$SAI_IOU" 'setOwner(address)' "$SAI_ADM"

cat > "load-pre-$(seth chain)" << EOF
test -z $SAI_GEM && GEMtx=$(dapp create DSToken "$(seth --to-bytes32 "$(seth --from-ascii 'ETH')")")
#!/bin/bash

# pre-sai deployment on $(seth chain) from $(git rev-parse HEAD)
# $(date)

export SAI_GEM=$SAI_GEM
export SAI_GOV=$SAI_GOV
export SAI_PIP=$SAI_PIP
export SAI_PEP=$SAI_PEP
export SAI_PIT=$SAI_PIT
export SAI_ADM=$SAI_ADM
export SAI_IOU=$SAI_IOU
EOF


================================================
FILE: bin/sai
================================================
#!/usr/bin/env bash
set -e
PATH=${0%/*/*}/libexec/sai:$PATH sai "$@"


================================================
FILE: libexec/sai/sai
================================================
#!/usr/bin/env bash
### sai -- command-line Ethereum RPC client
### Usage: sai [<options>] <command> [<args>]
###    or: sai <command> --help
###
### Sai is a simple version of the diversely collateralized Dai stablecoin.
###
### In this model there is one type of underlying collateral (called gems).
### The SKR token represents claims on the system's excess gems, and is the
### only admissible type of collateral.  Gems can be converted to/from SKR.
###
### Any transfers of sai or SKR are done using the normal ERC20 interface;
### until settlement mode is triggered, sai users should only need ERC20.
###
### To conveniently perform ERC20 transfers, see the token(1) program
### available at <https://github.com/dapphub/token>.
###
### Sai options:
###
###    -C, --cup=<id>             ID of cup to perform operation on
###        --tub=<address>        address of Tub to perform operation on
###        --tap=<address>        address of Tap to perform operation on
###        --top=<address>        address of Top to perform operation on
###
### Transaction options:
###
###    -F, --from=<account>       account from which to send transaction
###    -G, --gas=<number>         amount of gas to provide with transaction

OPTS="sai [<options>] <command> [<args>]
sai <command> --help
--
  Options
C,cup=id             ID of cup to perform operation on
tub=address          address of Tub to perform operation on
tap=address          address of Tap to perform operation on
top=address          address of Top to perform operation on
F,from=address       account from which to send transaction
G,gas=number         amount of gas to provide with transaction
h                    display output in human-readable form
"

set -e

if [[ $2 = --help ]]; then
  exec "${0##*/}" help -- "$1"
elif [[ $2 = --usage ]]; then
  "${0##*/}" help -- "$1"
  exit 1
elif [[ $3 = --usage ]]; then
  "${0##*/}" help -- "$1-$2"
  exit 1
elif [[ $1 = -* ]] && which "${0##*/}-$1" &>/dev/null; then
  exec "${0##*/}-$1" "${@:2}"
fi

eval "$(git rev-parse --parseopt -- "$@" <<<"$OPTS" || echo exit $?)"

while [[ $1 ]]; do
  case $1 in
    --)              shift; break;;

    -C|--cup)        shift; export SAI_CUP="$(seth --to-hexdata "$(seth --to-uint256 "$1")")";;
       --tub)        shift; export SAI_TUB=$1;;
       --tap)        shift; export SAI_TAP=$1;;
       --top)        shift; export SAI_TOP=$1;;

    -F|--from)       shift; export ETH_FROM=$1;;
    -G|--gas)        shift; export ETH_GAS=$1;;
    
    -h)                     export SAI_HUMAN=1;;

    *) printf "${0##*/}: internal error: %q\n" "$1"; exit 1
  esac; shift
done

export SAI_TUB=${SAI_TUB:-@sai_tub}
export SAI_TAP=${SAI_TAP:-@sai_tap}
export SAI_TOP=${SAI_TOP:-@sai_top}

"${0##*/}-${1-help}" "${@:2}"


================================================
FILE: libexec/sai/sai---help
================================================
#!/usr/bin/env bash
set -e
sai help


================================================
FILE: libexec/sai/sai-air
================================================
#!/usr/bin/env bash
### sai-air -- get the amount of backing collateral
set -e
wad=$(seth call "${SAI_TUB?}" "air()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-axe
================================================
#!/usr/bin/env bash
### sai-axe -- get the liquidation penalty
set -e
ray=$(seth call "${SAI_TUB?}" "axe()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-bite
================================================
#!/usr/bin/env bash
### sai-bite -- initiate liquidation of an undercollateral cup
### Usage: sai --cup=<id> bite
set -e
[ ! -z "$SAI_CUP" ] || sai bite --usage
echo >&2 "Attempting to bite cup id $((${SAI_CUP?}))..."
safe=$(sai safe)
[[ $safe = true ]] && { echo >&2 "${0##*/}: error: cup not unsafe"; exit 1; }
(set -x; seth send "${SAI_TUB?}" "bite(bytes32)" "$SAI_CUP")


================================================
FILE: libexec/sai/sai-boom
================================================
#!/usr/bin/env bash
### sai-boom -- buy some amount of sai to process joy (surplus)
### Usage: sai boom <amount-in-skr>
set -e
[ $# = 1 ] || sai boom --usage
wad=$(sai wad -h "$1")
echo >&2 "Buying $wad SKR-worth amount of SAI from the tub in order to process joy..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_TAP?}" "boom(uint256)" "$wad")


================================================
FILE: libexec/sai/sai-bust
================================================
#!/usr/bin/env bash
### sai-bust -- sell some amount of sai to process woe (bad debt)
### Usage: sai bust <amount-in-skr>
set -e
[ $# = 1 ] || sai bust --usage
wad=$(sai wad -h "$1")
echo >&2 "Selling $wad SKR-worth amount of SAI to the tub in order to process woe..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_TAP?}" "bust(uint256)" "$wad")


================================================
FILE: libexec/sai/sai-cage
================================================
#!/usr/bin/env bash
### sai-cage -- lock the system and initiate settlement
### Usage: sai cage [<final-price>]
###   if <final-price> is not specified, the last value from the feed will be used
set -e
if [ $# = 0 ]
then
  echo >&2 "Caging the tub, using the final price from the feed"
  (set -x; seth send "${SAI_TOP?}" "cage()")
elif [ $# = 1 ]
then
  wad=$(sai wad -h "$1")
  echo >&2 "Caging the tub, final price $wad"
  wad=$(sai wad "$1")
  (set -x; seth send "${SAI_TOP?}" "cage(uint256)" "$wad")
else
  sai cage --usage
fi


================================================
FILE: libexec/sai/sai-caged
================================================
#!/usr/bin/env bash
### sai-caged -- get time of cage event (= 0 if system is not caged)
set -e
echo "$(seth --to-dec $(seth call "${SAI_TOP?}" 'caged()'))"


================================================
FILE: libexec/sai/sai-cap
================================================
#!/usr/bin/env bash
### sai-cap -- get the debt ceiling
set -e
wad=$(seth call "${SAI_TUB?}" "cap()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-cash
================================================
#!/usr/bin/env bash
### sai-cash -- cash in sai balance for gems after cage
set -e
jam=$(token balance "$(sai sai)" "${ETH_FROM?}")
echo >&2 "Cashing in $jam SAI..."
wad=$(sai wad $jam)
(set -x; seth send "${SAI_TAP?}" "cash(uint256)" $wad )


================================================
FILE: libexec/sai/sai-chi
================================================
#!/usr/bin/env bash
### sai-chi -- get the internal debt price
set -e
ray=$(seth call "${SAI_TUB?}" "chi()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-cup
================================================
#!/usr/bin/env bash
### sai-cup -- show the cup info
### Usage: sai --cup=<id> cup
set -e
[ ! -z "$SAI_CUP" ] || sai cup --usage
echo >&2 "cup id $((${SAI_CUP?}))..."
echo "lad: $(sai lad)"
echo "ink: $(sai ink)"
echo "tab: $(sai tab)"
echo "rap: $(sai rap)"


================================================
FILE: libexec/sai/sai-cupi
================================================
#!/usr/bin/env bash
### sai-cupi -- get the last cup id
set -e
id=$(seth call "${SAI_TUB?}" "cupi()")
seth --abi-decode 'f()(uint256)' "$id" | seth --to-dec


================================================
FILE: libexec/sai/sai-cups
================================================
#!/usr/bin/env bash
### sai-cups -- list cups created by you
set -e
echo >&2 "Cups created by you..."
seth rpc eth_getLogs -- -n {} -s "${SAI_TUB?}" -i address \
                                 -s earliest    -i fromBlock \
                                   -n [] -s "$(seth keccak "$(seth --from-ascii 'LogNewCup(address,bytes32)')")" -i append \
                                         -s "0x$(seth --to-uint256 "${ETH_FROM?}")" -i append \
                                   -i topics \
                           -i append \
  | echo "[$(paste -sd , -)]" `# --jsonrpc output is dejsoned :/ ` \
  | jshon -a -e data \
  | seth --to-dec


================================================
FILE: libexec/sai/sai-din
================================================
#!/usr/bin/env bash
### sai-din -- get the debt backed by CDPs
set -e
wad=$(seth call "${SAI_TUB?}" "din()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-draw
================================================
#!/usr/bin/env bash
### sai-draw -- issue the specified amount of sai stablecoins
### Usage: sai --cup=<id> draw <amount-in-sai>
set -e
[ $# = 1 ] || sai draw --usage
[ ! -z "$SAI_CUP" ] || sai draw --usage
wad=$(sai wad -h "$1")
echo >&2 "Drawing $wad SAI from cup $((${SAI_CUP?}))..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_TUB?}" "draw(bytes32,uint256)" "$SAI_CUP" "$wad")


================================================
FILE: libexec/sai/sai-drip
================================================
#!/usr/bin/env bash
### sai-drip -- recalculate the internal debt price
set -e
(set -x; seth send "${SAI_TUB?}" "drip()")


================================================
FILE: libexec/sai/sai-exit
================================================
#!/usr/bin/env bash
### sai-exit -- sell SKR for gems
### Usage: sai exit <amount-in-skr>
set -e
[ $# = 1 ] || sai exit --usage
ink=$(sai wad -h "$1")
echo >&2 "Sending $ink SKR to TUB..."
ink=$(sai wad "$1")
(set -x; seth send "${SAI_TUB?}" "exit(uint256)" "$ink")


================================================
FILE: libexec/sai/sai-fee
================================================
#!/usr/bin/env bash
### sai-fee -- get the governance fee
set -e
ray=$(seth call "${SAI_TUB?}" "fee()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-fit
================================================
#!/usr/bin/env bash
### sai-fit -- get the gem per skr settlement price
set -e
ray=$(seth call "${SAI_TUB?}" "fit()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-fix
================================================
#!/usr/bin/env bash
### sai-fix -- get the gem per sai settlement price
set -e
ray=$(seth call "${SAI_TOP?}" "fix()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-fog
================================================
#!/usr/bin/env bash
### sai-fog -- get the amount of skr pending liquidation
set -e
wad=$(seth call "${SAI_TAP?}" "fog()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-free
================================================
#!/usr/bin/env bash
### sai-free -- remove excess SKR collateral from a cup
### Usage: sai --cup=<id> free <amount-in-skr>
set -e
[ $# = 1 ] || sai free --usage
[ ! -z "$SAI_CUP" ] || sai free --usage
wad=$(sai wad -h "$1")
echo >&2 "Freeing $wad SKR from cup $((${SAI_CUP?}))..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_TUB?}" "free(bytes32,uint256)" "$SAI_CUP" "$wad")


================================================
FILE: libexec/sai/sai-gem
================================================
#!/usr/bin/env bash
### sai-gem -- get the collateral token
set -e
gem=$(seth call "${SAI_TUB?}" 'gem()')
echo "0x$(seth --abi-decode 'f()(address)' "$gem")"


================================================
FILE: libexec/sai/sai-give
================================================
#!/usr/bin/env bash
### sai-give -- transfer ownership of a cup
### Usage: sai --cup=<id> give <address>
set -e
[ $# = 1 ] || sai give --usage
[ ! -z "$SAI_CUP" ] || sai give --usage
echo >&2 "Giving cup $((${SAI_CUP?})) to \"${1?}\"..."
(set -x; seth send "${SAI_TUB?}" "give(bytes32,address)" "$SAI_CUP" "$1")


================================================
FILE: libexec/sai/sai-gov
================================================
#!/usr/bin/env bash
### sai-gov -- get the gov token
set -e
gov=$(seth call "${SAI_TUB?}" 'gov()')
echo "0x$(seth --abi-decode 'f()(address)' "$gov")"


================================================
FILE: libexec/sai/sai-heal
================================================
#!/usr/bin/env bash
### sai-heal -- cancel debt
set -e
(set -x; seth send "${SAI_TAP?}" "heal()")


================================================
FILE: libexec/sai/sai-help
================================================
#!/usr/bin/env bash
### sai-help -- print help about sai(1) or one of its subcommands
### Usage: sai help [<command>]
###    or: sai <command> --help

BUGS=https://github.com/makerdao/sai/issues/new

name=sai
file=${0%-*}${1+-$1}
header=$(perl -ne 'print "$2\n" if /^(\S)\1\1(?: (.*))?/' "$file")

if ! [[ $header ]]; then
  sed "s/^/${0##*/}: /" "$file"
elif [[ $(wc -l <<<"$header") = 1 ]]; then
  echo "$header"
else
  sed "1{/^$name\\S* -- /d;}" <<<"$header"
fi

[[ $1 ]] && exit

for file in ${0%/*}/$name-*; do
  basename=${file##*/}
  if [[ -L $file ]]; then
    continue
  elif [[ ${#basename} = 7 ]] || [[ ${#basename} = 11 ]]; then
    special_commands+=("$file")
  else
    normal_commands+=("$file")
  fi
done

list-commands() {
  cat "$@" |
  perl -ne 'print "$2 $3\n" if /^(\S)\1\1 '"$name"'-(\S+) -- (.*)/' |
  while read -r name label; do
    printf "   %-14s  %s\n" "${name/-/ }" "$label"
  done | LANG=C sort
}

cat <<.

Special commands:

$(list-commands "${special_commands[@]}")

Commands:

$(list-commands "${normal_commands[@]}")

Report bugs to <$BUGS>.
.


================================================
FILE: libexec/sai/sai-ink
================================================
#!/usr/bin/env bash
### sai-ink -- get the amount of skr collateral locked in a cup
### Usage: sai --cup=<id> ink
set -e
[ ! -z "$SAI_CUP" ] || sai ink --usage
wad=$(seth call "${SAI_TUB?}" "ink(bytes32)" "${SAI_CUP?}")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-join
================================================
#!/usr/bin/env bash
### sai-join -- buy SKR for gems
### Usage: sai join <amount-in-skr>
set -e
[ $# = 1 ] || sai join --usage
jam=$(sai wad -h "$1")
echo >&2 "Generating $jam SKR depositing GEM..."
jam=$(sai wad "$1")
(set -x; seth send "${SAI_TUB?}" "join(uint256)" "$jam")


================================================
FILE: libexec/sai/sai-joy
================================================
#!/usr/bin/env bash
### sai-joy -- get the amount of surplus sai
set -e
wad=$(seth call "${SAI_TAP?}" "joy()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-lad
================================================
#!/usr/bin/env bash
### sai-lad -- get the owner of a cup
### Usage: sai --cup=<id> lad
set -e
[ ! -z "$SAI_CUP" ] || sai lad --usage
lad=$(seth call "${SAI_TUB?}" 'lad(bytes32)' "${SAI_CUP?}")
echo "0x$(seth --abi-decode 'f()(address)' "$lad")"


================================================
FILE: libexec/sai/sai-lock
================================================
#!/usr/bin/env bash
### sai-lock -- post additional SKR collateral to a cup
### Usage: sai --cup=<id> lock <amount-in-skr>
set -e
[ $# = 1 ] || sai lock --usage
[ ! -z "$SAI_CUP" ] || sai lock --usage
wad=$(sai wad -h "$1")
echo >&2 "Locking $wad SKR in cup $((${SAI_CUP?}))..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_TUB?}" "lock(bytes32,uint256)" "$SAI_CUP" "$wad")


================================================
FILE: libexec/sai/sai-mat
================================================
#!/usr/bin/env bash
### sai-mat -- get the liquidation ratio
set -e
ray=$(seth call "${SAI_TUB?}" "mat()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-off
================================================
#!/usr/bin/env bash
### sai-off -- get the cage flag
set -e
seth call "${SAI_TUB?}" "off()(bool)"


================================================
FILE: libexec/sai/sai-open
================================================
#!/usr/bin/env bash
### sai-open -- create a new cup (collateralized debt position)
set -e
echo >&2 "Opening cup..."
export SETH_ASYNC=yes
tx=$(set -x; seth send "${SAI_TUB?}" "open()(bytes32)")
export SETH_ASYNC=no
echo >&2 -n "Waiting for transaction receipt..."
number=$(SETH_TICK=true seth receipt "$tx" blockNumber)
echo >&2
seth rpc eth_getLogs -- -n {} -s "${SAI_TUB?}" -i address \
                                 -s "$number"  -i fromBlock \
                                 -s "$number"  -i toBlock \
                                   -n [] -s "$(seth keccak "$(seth --from-ascii 'LogNewCup(address,bytes32)')")" -i append \
                                         -s "0x$(seth --to-uint256 "${ETH_FROM?}")" -i append \
                                   -i topics \
                           -i append \
  | echo "[$(paste -sd , -)]" `# --jsonrpc output is dejsoned :/ ` \
  | jshon -a -e data -u -p -e transactionHash -u \
  | grep -B 1 "$tx" \
  | head -1 \
  | seth --to-dec \
  | { read -r id; echo "Opened cup $id"; }


================================================
FILE: libexec/sai/sai-out
================================================
#!/usr/bin/env bash
### sai-out -- get the post cage exit flag
set -e
seth call "${SAI_TUB?}" "out()(bool)"


================================================
FILE: libexec/sai/sai-par
================================================
#!/usr/bin/env bash
### sai-par -- get the accrued holder fee (ref per sai)
set -e
vox=$(seth call "${SAI_TUB?}" 'vox()')
vox_address="0x$(seth --abi-decode 'f()(address)' "$vox")"
ray=$(seth call "$vox_address" "par()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-pep
================================================
#!/usr/bin/env bash
### sai-pep -- get the gov price feed
set -e
pep=$(seth call "${SAI_TUB?}" 'pep()')
echo "0x$(seth --abi-decode 'f()(address)' "$pep")"


================================================
FILE: libexec/sai/sai-per
================================================
#!/usr/bin/env bash
### sai-per -- get the current entry price (gem per skr)
set -e
ray=$(seth call "${SAI_TUB?}" "per()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-pie
================================================
#!/usr/bin/env bash
### sai-pie -- get the amount of raw collateral
set -e
wad=$(seth call "${SAI_TUB?}" "pie()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-pip
================================================
#!/usr/bin/env bash
### sai-pip -- get the gem price feed
set -e
pip=$(seth call "${SAI_TUB?}" 'pip()')
echo "0x$(seth --abi-decode 'f()(address)' "$pip")"


================================================
FILE: libexec/sai/sai-pit
================================================
#!/usr/bin/env bash
### sai-pit -- get the liquidator vault
set -e
pit=$(seth call "${SAI_TUB?}" 'pit()')
echo "0x$(seth --abi-decode 'f()(address)' "$pit")"


================================================
FILE: libexec/sai/sai-prod
================================================
#!/usr/bin/env bash
### sai-prod -- recalculate the accrued holder fee (par)
set -e
vox=$(seth call "${SAI_TUB?}" 'vox()')
vox_address="0x$(seth --abi-decode 'f()(address)' "$vox")"
(set -x; seth send "$vox_address" "prod()")


================================================
FILE: libexec/sai/sai-rap
================================================
#!/usr/bin/env bash
### sai-rap -- get the amount of governance debt
### Usage: sai --cup=<id> rap
set -e
[ ! -z "$SAI_CUP" ] || sai rap --usage
wad=$(seth call "${SAI_TUB?}" "rap(bytes32)" "${SAI_CUP?}")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-ray
================================================
#!/usr/bin/env node
/// sai-ray -- parse and display a 27-decimal fixed-point number
var BigNumber = require("bignumber.js")
var ray = process.argv[2], match
var rpad = (x, y, n) => x + repeat(y, n - x.length)
var lpad = (x, y, n) => repeat(y, n - x.length) + x
var repeat = (x, n) => n > 0 ? new Array(n + 1).join(x) : ""
var toHex = ray => new BigNumber(ray.replace(".", "")).toString(16)
   
if (match = ray.match(/^(\d+\.)(\d{1,27})$/)) {
  ray = match[1] + rpad(match[2], "0", 27)
} else if (/^0x[0-9a-f]+/.test(ray)) {
  ray = lpad(new BigNumber(ray).toString(10), "0", 27)
  ray = ray.replace(/.{27}$/, ".$&").replace(/^\./, "0.")
} else {
  console.error("sai---ray: error: number must have decimal point")
  process.exit(1)
}

if (process.env.SAI_HUMAN) {
  console.log(ray)
} else {
  console.log(`0x${lpad(toHex(ray), "0", 64)}`)
}


================================================
FILE: libexec/sai/sai-rhi
================================================
#!/usr/bin/env bash
### sai-rhi -- get the internal debt price including governance fee
set -e
ray=$(seth call "${SAI_TUB?}" "rhi()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-rho
================================================
#!/usr/bin/env bash
### sai-rho -- get the time of last drip
set -e
time=$(seth call "${SAI_TUB?}" "rho()")
time_unix=$(seth --to-dec "$time")
echo "$time_unix"


================================================
FILE: libexec/sai/sai-s2s
================================================
#!/usr/bin/env bash
### sai-s2s -- get the skr per sai rate (for boom and bust)
set -e
ray=$(seth call "${SAI_TAP?}" "s2s()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-safe
================================================
#!/usr/bin/env bash
### sai-safe -- determine if a cup is safe
### Usage: sai --cup=<id> safe
set -e
[ ! -z "$SAI_CUP" ] || sai safe --usage
safe=$(seth call "${SAI_TUB?}" 'safe(bytes32)' "${SAI_CUP?}")
seth --abi-decode 'f(bytes32)(bool)' "$safe"


================================================
FILE: libexec/sai/sai-sai
================================================
#!/usr/bin/env bash
### sai-sai -- get the sai token
set -e
sai=$(seth call "${SAI_TUB?}" 'sai()')
echo "0x$(seth --abi-decode 'f()(address)' "$sai")"


================================================
FILE: libexec/sai/sai-setAxe
================================================
#!/usr/bin/env bash
### sai-setAxe -- update the liquidation penalty
### Usage: sai setAxe <new-axe>
set -e
[ $# = 1 ] || sai setAxe --usage
ray=$(sai ray -h "$1")
echo >&2 "Setting axe to $ray..."
ray=$(sai ray "$1")
(set -x; seth send "${SAI_MOM?}" "setAxe(uint256)" "$ray")


================================================
FILE: libexec/sai/sai-setCap
================================================
#!/usr/bin/env bash
### sai-setCap -- update the debt ceiling
### Usage: sai setCap <new-cap>
set -e
[ $# = 1 ] || sai setCap --usage
wad=$(sai wad -h "$1")
echo >&2 "Setting cap to $wad..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_MOM?}" "setCap(uint256)" "$wad")


================================================
FILE: libexec/sai/sai-setFee
================================================
#!/usr/bin/env bash
### sai-setFee -- update the stability fee
### Usage: sai setFee <new-fee>
set -e
[ $# = 1 ] || sai setFee --usage
ray=$(sai ray -h "$1")
echo >&2 "Setting fee to $ray..."
ray=$(sai ray "$1")
(set -x; seth send "${SAI_MOM?}" "setFee(uint256)" "$ray")


================================================
FILE: libexec/sai/sai-setMat
================================================
#!/usr/bin/env bash
### sai-setMat -- update the liquidation ratio
### Usage: sai setMat <new-mat>
set -e
[ $# = 1 ] || sai setMat --usage
ray=$(sai ray -h "$1")
echo >&2 "Setting mat to $ray..."
ray=$(sai ray "$1")
(set -x; seth send "${SAI_MOM?}" "setMat(uint256)" "$ray")


================================================
FILE: libexec/sai/sai-setTapGap
================================================
#!/usr/bin/env bash
### sai-setTapGap -- update the spread on `boom` and `bust`
### Usage: sai tapGap <new-gap>
set -e
[ $# = 1 ] || sai tap tapGap --usage
wad=$(sai wad -h "$1")
echo >&2 "Setting gap to $wad..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_MOM?}" "setTapGap(uint256)" "$wad")


================================================
FILE: libexec/sai/sai-setTax
================================================
#!/usr/bin/env bash
### sai-setTax -- update the stability fee
### Usage: sai setTax <new-tax>
set -e
[ $# = 1 ] || sai setTax --usage
ray=$(sai ray -h "$1")
echo >&2 "Setting tax to $ray..."
ray=$(sai ray "$1")
(set -x; seth send "${SAI_MOM?}" "setTax(uint256)" "$ray")


================================================
FILE: libexec/sai/sai-setTubGap
================================================
#!/usr/bin/env bash
### sai-setTubGap -- update the spread on `join` and `exit`
### Usage: sai setTubGap <new-gap>
set -e
[ $# = 1 ] || sai setTubGap --usage
wad=$(sai wad -h "$1")
echo >&2 "Setting tubGap to $wad..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_MOM?}" "setTubGap(uint256)" "$wad")


================================================
FILE: libexec/sai/sai-setWay
================================================
#!/usr/bin/env bash
### sai-setWay -- update the holder fee (interest rate)
### Usage: sai setWay <new-way>
set -e
[ $# = 1 ] || sai setWay --usage
ray=$(sai ray -h "$1")
echo >&2 "Setting way to $ray..."
ray=$(sai ray "$1")
(set -x; seth send "${SAI_MOM}" "setWay(uint256)" "$ray")


================================================
FILE: libexec/sai/sai-shut
================================================
#!/usr/bin/env bash
### sai-shut -- close a cup
### Usage: sai --cup=<id> shut
set -e
[ ! -z "$SAI_CUP" ] || sai shut --usage
echo >&2 "Closing cup $((${SAI_CUP?}))..."
(set -x; seth send "${SAI_TUB?}" "shut(bytes32)" "$SAI_CUP")


================================================
FILE: libexec/sai/sai-sin
================================================
#!/usr/bin/env bash
### sai-sin -- get the sin token
set -e
sin=$(seth call "${SAI_TUB?}" 'sin()')
echo "0x$(seth --abi-decode 'f()(address)' "$sin")"


================================================
FILE: libexec/sai/sai-skr
================================================
#!/usr/bin/env bash
### sai-skr -- get the skr token
set -e
skr=$(seth call "${SAI_TUB?}" 'skr()')
echo "0x$(seth --abi-decode 'f()(address)' "$skr")"


================================================
FILE: libexec/sai/sai-tab
================================================
#!/usr/bin/env bash
### sai-tab -- get the amount of debt in a cup
### Usage: sai --cup=<id> tab
set -e
[ ! -z "$SAI_CUP" ] || sai tab --usage
wad=$(seth call "${SAI_TUB?}" "tab(bytes32)" "${SAI_CUP?}")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-tag
================================================
#!/usr/bin/env bash
### sai-tag -- get the reference price (ref per skr)
set -e
ray=$(seth call "${SAI_TUB?}" "tag()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-tapAsk
================================================
#!/usr/bin/env bash
### sai-tapAsk -- get the amount of skr in sai for bust
set -e
[ $# = 1 ] || sai tapAsk --usage
wad=$(seth call "${SAI_TAP?}" "ask(uint256)" $(sai wad "$1"))
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-tapBid
================================================
#!/usr/bin/env bash
### sai-tapBid -- get the amount of skr in sai for boom
set -e
[ $# = 1 ] || sai tapBid --usage
wad=$(seth call "${SAI_TAP?}" "bid(uint256)" $(sai wad "$1"))
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-tapGap
================================================
#!/usr/bin/env bash
### sai-tapGap -- get the spread on `boom` and `bust`
set -e
wad=$(seth call "${SAI_TAP?}" "gap()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-tau
================================================
#!/usr/bin/env bash
### sai-tau -- get the time of last prod
set -e
vox=$(seth call "${SAI_TUB?}" 'vox()')
vox_address="0x$(seth --abi-decode 'f()(address)' "$vox")"
time=$(seth call "$vox_address" "tau()")
time_unix=$(seth --to-dec "$time")
echo "$time_unix"


================================================
FILE: libexec/sai/sai-tax
================================================
#!/usr/bin/env bash
### sai-tax -- get the stability fee
set -e
ray=$(seth call "${SAI_TUB?}" "tax()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-tubAsk
================================================
#!/usr/bin/env bash
### sai-tubAsk -- get the amount of skr in gem for join
set -e
[ $# = 1 ] || sai tubAsk --usage
wad=$(seth call "${SAI_TUB?}" "ask(uint256)" $(sai wad "$1"))
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-tubBid
================================================
#!/usr/bin/env bash
### sai-tubBid -- get the amount of skr in gem for exit
set -e
[ $# = 1 ] || sai tubBid --usage
wad=$(seth call "${SAI_TUB?}" "bid(uint256)" $(sai wad "$1"))
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-tubGap
================================================
#!/usr/bin/env bash
### sai-tubGap -- get the spread on `join` and `exit`
set -e
wad=$(seth call "$SAI_TUB" "gap()")
sai wad -h "$wad"


================================================
FILE: libexec/sai/sai-vent
================================================
#!/usr/bin/env bash
### sai-vent -- process a caged tub
set -e
(set -x; seth send "${SAI_TAP?}" "vent()")


================================================
FILE: libexec/sai/sai-vox
================================================
#!/usr/bin/env bash
### sai-vox -- get the target price engine
set -e
vox=$(seth call "${SAI_TUB?}" 'vox()')
echo "0x$(seth --abi-decode 'f()(address)' "$vox")"


================================================
FILE: libexec/sai/sai-wad
================================================
#!/usr/bin/env node
/// sai-wad -- parse and display a 18-decimal fixed-point number
var BigNumber = require("bignumber.js")
var wad = process.argv[2], match
var rpad = (x, y, n) => x + repeat(y, n - x.length)
var lpad = (x, y, n) => repeat(y, n - x.length) + x
var repeat = (x, n) => n > 0 ? new Array(n + 1).join(x) : ""
var toHex = wad => new BigNumber(wad.replace(".", "")).toString(16)
   
if (match = wad.match(/^(\d+\.)(\d{1,18})$/)) {
  wad = match[1] + rpad(match[2], "0", 18)
} else if (/^0x[0-9a-f]+/.test(wad)) {
  wad = lpad(new BigNumber(wad).toString(10), "0", 18)
  wad = wad.replace(/.{18}$/, ".$&").replace(/^\./, "0.")
} else {
  console.error("sai---wad: error: number must have decimal point")
  process.exit(1)
}

if (process.env.SAI_HUMAN) {
  console.log(wad)
} else {
  console.log(`0x${lpad(toHex(wad), "0", 64)}`)
}


================================================
FILE: libexec/sai/sai-way
================================================
#!/usr/bin/env bash
### sai-way -- get the holder fee (interest rate)
set -e
vox=$(seth call "${SAI_TUB?}" 'vox()')
vox_address="0x$(seth --abi-decode 'f()(address)' "$vox")"
ray=$(seth call "$vox_address" "way()")
sai ray -h "$ray"


================================================
FILE: libexec/sai/sai-wipe
================================================
#!/usr/bin/env bash
### sai-wipe -- repay some portion of your existing sai debt
### Usage: sai --cup=<id> wipe <amount-in-sai>
set -e
[ $# = 1 ] || sai wipe --usage
[ ! -z "$SAI_CUP" ] || sai wipe --usage
wad=$(sai wad -h "$1")
echo >&2 "Wiping $wad SAI from cup $((${SAI_CUP?}))..."
wad=$(sai wad "$1")
(set -x; seth send "${SAI_TUB?}" "wipe(bytes32,uint256)" "$SAI_CUP" "$wad")


================================================
FILE: libexec/sai/sai-woe
================================================
#!/usr/bin/env bash
### sai-woe -- get the amount of bad debt
set -e
wad=$(seth call "${SAI_TAP?}" "woe()")
sai wad -h "$wad"


================================================
FILE: src/fab.sol
================================================
pragma solidity ^0.4.18;

import "ds-auth/auth.sol";
import 'ds-token/token.sol';
import 'ds-guard/guard.sol';
import 'ds-roles/roles.sol';
import 'ds-value/value.sol';

import './mom.sol';

contract GemFab {
    function newTok(bytes32 name) public returns (DSToken token) {
        token = new DSToken(name);
        token.setOwner(msg.sender);
    }
}

contract VoxFab {
    function newVox() public returns (SaiVox vox) {
        vox = new SaiVox(10 ** 27);
        vox.setOwner(msg.sender);
    }
}

contract TubFab {
    function newTub(DSToken sai, DSToken sin, DSToken skr, ERC20 gem, DSToken gov, DSValue pip, DSValue pep, SaiVox vox, address pit) public returns (SaiTub tub) {
        tub = new SaiTub(sai, sin, skr, gem, gov, pip, pep, vox, pit);
        tub.setOwner(msg.sender);
    }
}

contract TapFab {
    function newTap(SaiTub tub) public returns (SaiTap tap) {
        tap = new SaiTap(tub);
        tap.setOwner(msg.sender);
    }
}

contract TopFab {
    function newTop(SaiTub tub, SaiTap tap) public returns (SaiTop top) {
        top = new SaiTop(tub, tap);
        top.setOwner(msg.sender);
    }
}

contract MomFab {
    function newMom(SaiTub tub, SaiTap tap, SaiVox vox) public returns (SaiMom mom) {
        mom = new SaiMom(tub, tap, vox);
        mom.setOwner(msg.sender);
    }
}

contract DadFab {
    function newDad() public returns (DSGuard dad) {
        dad = new DSGuard();
        dad.setOwner(msg.sender);
    }
}

contract DaiFab is DSAuth {
    GemFab public gemFab;
    VoxFab public voxFab;
    TapFab public tapFab;
    TubFab public tubFab;
    TopFab public topFab;
    MomFab public momFab;
    DadFab public dadFab;

    DSToken public sai;
    DSToken public sin;
    DSToken public skr;

    SaiVox public vox;
    SaiTub public tub;
    SaiTap public tap;
    SaiTop public top;

    SaiMom public mom;
    DSGuard public dad;

    uint8 public step = 0;

    function DaiFab(GemFab gemFab_, VoxFab voxFab_, TubFab tubFab_, TapFab tapFab_, TopFab topFab_, MomFab momFab_, DadFab dadFab_) public {
        gemFab = gemFab_;
        voxFab = voxFab_;
        tubFab = tubFab_;
        tapFab = tapFab_;
        topFab = topFab_;
        momFab = momFab_;
        dadFab = dadFab_;
    }

    function makeTokens() public auth {
        require(step == 0);
        sai = gemFab.newTok('DAI');
        sin = gemFab.newTok('SIN');
        skr = gemFab.newTok('PETH');
        sai.setName('Dai Stablecoin v1.0');
        sin.setName('SIN');
        skr.setName('Pooled Ether');
        step += 1;
    }

    function makeVoxTub(ERC20 gem, DSToken gov, DSValue pip, DSValue pep, address pit) public auth {
        require(step == 1);
        require(address(gem) != 0x0);
        require(address(gov) != 0x0);
        require(address(pip) != 0x0);
        require(address(pep) != 0x0);
        require(pit != 0x0);
        vox = voxFab.newVox();
        tub = tubFab.newTub(sai, sin, skr, gem, gov, pip, pep, vox, pit);
        step += 1;
    }

    function makeTapTop() public auth {
        require(step == 2);
        tap = tapFab.newTap(tub);
        tub.turn(tap);
        top = topFab.newTop(tub, tap);
        step += 1;
    }

    function S(string s) internal pure returns (bytes4) {
        return bytes4(keccak256(s));
    }

    function ray(uint256 wad) internal pure returns (uint256) {
        return wad * 10 ** 9;
    }

    // Liquidation Ratio   150%
    // Liquidation Penalty 13%
    // Stability Fee       0.05%
    // PETH Fee            0%
    // Boom/Bust Spread   -3%
    // Join/Exit Spread    0%
    // Debt Ceiling        0
    function configParams() public auth {
        require(step == 3);

        tub.mold("cap", 0);
        tub.mold("mat", ray(1.5  ether));
        tub.mold("axe", ray(1.13 ether));
        tub.mold("fee", 1000000000158153903837946257);  // 0.5% / year
        tub.mold("tax", ray(1 ether));
        tub.mold("gap", 1 ether);

        tap.mold("gap", 0.97 ether);

        step += 1;
    }

    function verifyParams() public auth {
        require(step == 4);

        require(tub.cap() == 0);
        require(tub.mat() == 1500000000000000000000000000);
        require(tub.axe() == 1130000000000000000000000000);
        require(tub.fee() == 1000000000158153903837946257);
        require(tub.tax() == 1000000000000000000000000000);
        require(tub.gap() == 1000000000000000000);

        require(tap.gap() == 970000000000000000);

        require(vox.par() == 1000000000000000000000000000);
        require(vox.how() == 0);

        step += 1;
    }

    function configAuth(DSAuthority authority) public auth {
        require(step == 5);
        require(address(authority) != 0x0);

        mom = momFab.newMom(tub, tap, vox);
        dad = dadFab.newDad();

        vox.setAuthority(dad);
        vox.setOwner(0);
        tub.setAuthority(dad);
        tub.setOwner(0);
        tap.setAuthority(dad);
        tap.setOwner(0);
        sai.setAuthority(dad);
        sai.setOwner(0);
        sin.setAuthority(dad);
        sin.setOwner(0);
        skr.setAuthority(dad);
        skr.setOwner(0);

        top.setAuthority(authority);
        top.setOwner(0);
        mom.setAuthority(authority);
        mom.setOwner(0);

        dad.permit(top, tub, S("cage(uint256,uint256)"));
        dad.permit(top, tub, S("flow()"));
        dad.permit(top, tap, S("cage(uint256)"));

        dad.permit(tub, skr, S('mint(address,uint256)'));
        dad.permit(tub, skr, S('burn(address,uint256)'));

        dad.permit(tub, sai, S('mint(address,uint256)'));
        dad.permit(tub, sai, S('burn(address,uint256)'));

        dad.permit(tub, sin, S('mint(address,uint256)'));

        dad.permit(tap, sai, S('mint(address,uint256)'));
        dad.permit(tap, sai, S('burn(address,uint256)'));
        dad.permit(tap, sai, S('burn(uint256)'));
        dad.permit(tap, sin, S('burn(uint256)'));

        dad.permit(tap, skr, S('mint(uint256)'));
        dad.permit(tap, skr, S('burn(uint256)'));
        dad.permit(tap, skr, S('burn(address,uint256)'));

        dad.permit(mom, vox, S("mold(bytes32,uint256)"));
        dad.permit(mom, vox, S("tune(uint256)"));
        dad.permit(mom, tub, S("mold(bytes32,uint256)"));
        dad.permit(mom, tap, S("mold(bytes32,uint256)"));
        dad.permit(mom, tub, S("setPip(address)"));
        dad.permit(mom, tub, S("setPep(address)"));
        dad.permit(mom, tub, S("setVox(address)"));

        dad.setOwner(0);
        step += 1;
    }
}


================================================
FILE: src/fab.t.sol
================================================
pragma solidity ^0.4.18;

import "ds-test/test.sol";
import './fab.sol';

contract BinTest is DSTest {
    GemFab gemFab;
    VoxFab voxFab;
    TubFab tubFab;
    TapFab tapFab;
    TopFab topFab;
    MomFab momFab;
    DadFab dadFab;

    DaiFab daiFab;

    DSToken gem;
    DSToken gov;
    DSValue pip;
    DSValue pep;
    address pit;

    DSRoles authority;

    function setUp() public {
        gemFab = new GemFab();
        voxFab = new VoxFab();
        tubFab = new TubFab();
        tapFab = new TapFab();
        topFab = new TopFab();
        momFab = new MomFab();
        dadFab = new DadFab();

        uint startGas = msg.gas;
        daiFab = new DaiFab(gemFab, voxFab, tubFab, tapFab, topFab, momFab, dadFab);
        uint endGas = msg.gas;
        log_named_uint('Deploy DaiFab', startGas - endGas);

        gem = new DSToken('GEM');
        gov = new DSToken('GOV');
        pip = new DSValue();
        pep = new DSValue();
        pit = address(0x123);
        authority = new DSRoles();
        authority.setRootUser(this, true);
    }

    function testMake() public {
        uint startGas = msg.gas;
        daiFab.makeTokens();
        uint endGas = msg.gas;
        log_named_uint('Make Tokens', startGas - endGas);

        startGas = msg.gas;
        daiFab.makeVoxTub(gem, gov, pip, pep, pit);
        endGas = msg.gas;
        log_named_uint('Make Vox Tub', startGas - endGas);

        startGas = msg.gas;
        daiFab.makeTapTop();
        endGas = msg.gas;
        log_named_uint('Make Tap Top', startGas - endGas);

        startGas = msg.gas;
        daiFab.configParams();
        endGas = msg.gas;
        log_named_uint('Config Params', startGas - endGas);

        startGas = msg.gas;
        daiFab.verifyParams();
        endGas = msg.gas;
        log_named_uint('Verify Params', startGas - endGas);

        startGas = msg.gas;
        daiFab.configAuth(authority);
        endGas = msg.gas;
        log_named_uint('Config Auth', startGas - endGas);
    }

    function testFailStep() public {
        daiFab.makeTokens();
        daiFab.makeTokens();
    }

    function testFailStep2() public {
        daiFab.makeTokens();
        daiFab.makeTapTop();
    }

    function testFailStep3() public {
        daiFab.makeTokens();
        daiFab.makeVoxTub(gem, gov, pip, pep, pit);
        daiFab.makeTapTop();
        daiFab.makeVoxTub(gem, gov, pip, pep, pit);
    }

    function testFailStep4() public {
        daiFab.makeTokens();
        daiFab.makeVoxTub(gem, gov, pip, pep, pit);
        daiFab.makeTapTop();
        daiFab.configAuth(authority);
        daiFab.makeTokens();
    }
}


================================================
FILE: src/mom.sol
================================================
/// mom.sol -- admin manager

// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>
// Copyright (C) 2017  Daniel Brockman <daniel@dapphub.com>
// Copyright (C) 2017  Rain <rainbreak@riseup.net>

// 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/>.

pragma solidity ^0.4.18;

import 'ds-thing/thing.sol';
import './tub.sol';
import './top.sol';
import './tap.sol';

contract SaiMom is DSThing {
    SaiTub  public  tub;
    SaiTap  public  tap;
    SaiVox  public  vox;

    function SaiMom(SaiTub tub_, SaiTap tap_, SaiVox vox_) public {
        tub = tub_;
        tap = tap_;
        vox = vox_;
    }
    // Debt ceiling
    function setCap(uint wad) public note auth {
        tub.mold("cap", wad);
    }
    // Liquidation ratio
    function setMat(uint ray) public note auth {
        tub.mold("mat", ray);
        var axe = tub.axe();
        var mat = tub.mat();
        require(axe >= RAY && axe <= mat);
    }
    // Stability fee
    function setTax(uint ray) public note auth {
        tub.mold("tax", ray);
        var tax = tub.tax();
        require(RAY <= tax);
        require(tax < 1000001100000000000000000000);  // 10% / day
    }
    // Governance fee
    function setFee(uint ray) public note auth {
        tub.mold("fee", ray);
        var fee = tub.fee();
        require(RAY <= fee);
        require(fee < 1000001100000000000000000000);  // 10% / day
    }
    // Liquidation fee
    function setAxe(uint ray) public note auth {
        tub.mold("axe", ray);
        var axe = tub.axe();
        var mat = tub.mat();
        require(axe >= RAY && axe <= mat);
    }
    // Join/Exit Spread
    function setTubGap(uint wad) public note auth {
        tub.mold("gap", wad);
    }
    // ETH/USD Feed
    function setPip(DSValue pip_) public note auth {
        tub.setPip(pip_);
    }
    // MKR/USD Feed
    function setPep(DSValue pep_) public note auth {
        tub.setPep(pep_);
    }
    // TRFM
    function setVox(SaiVox vox_) public note auth {
        tub.setVox(vox_);
    }
    // Boom/Bust Spread
    function setTapGap(uint wad) public note auth {
        tap.mold("gap", wad);
        var gap = tap.gap();
        require(gap <= 1.05 ether);
        require(gap >= 0.95 ether);
    }
    // Rate of change of target price (per second)
    function setWay(uint ray) public note auth {
        require(ray < 1000001100000000000000000000);  // 10% / day
        require(ray >  999998800000000000000000000);
        vox.mold("way", ray);
    }
    function setHow(uint ray) public note auth {
        vox.tune(ray);
    }
}


================================================
FILE: src/pit.sol
================================================
/// pit.sol -- a simple token burner

// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>

// 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/>.

pragma solidity ^0.4.18;

import "ds-token/token.sol";

contract GemPit {
    function burn(DSToken gem) public {
        gem.burn(gem.balanceOf(this));
    }
}


================================================
FILE: src/sai.t.sol
================================================
pragma solidity ^0.4.18;

import "ds-test/test.sol";

import "ds-math/math.sol";

import 'ds-token/token.sol';
import 'ds-roles/roles.sol';
import 'ds-value/value.sol';

import './weth9.sol';
import './mom.sol';
import './fab.sol';
import './pit.sol';

contract TestWarp is DSNote {
    uint256  _era;

    function TestWarp() public {
        _era = now;
    }

    function era() public view returns (uint256) {
        return _era == 0 ? now : _era;
    }

    function warp(uint age) public note {
        require(_era != 0);
        _era = age == 0 ? 0 : _era + age;
    }
}

contract DevTub is SaiTub, TestWarp {
    function DevTub(
        DSToken  sai_,
        DSToken  sin_,
        DSToken  skr_,
        ERC20    gem_,
        DSToken  gov_,
        DSValue  pip_,
        DSValue  pep_,
        SaiVox   vox_,
        address  pit_
    ) public
      SaiTub(sai_, sin_, skr_, gem_, gov_, pip_, pep_, vox_, pit_) {}
}

contract DevTop is SaiTop, TestWarp {
    function DevTop(SaiTub tub_, SaiTap tap_) public SaiTop(tub_, tap_) {}
}

contract DevVox is SaiVox, TestWarp {
    function DevVox(uint par_) SaiVox(par_) public {}
}

contract DevVoxFab {
    function newVox() public returns (DevVox vox) {
        vox = new DevVox(10 ** 27);
        vox.setOwner(msg.sender);
    }
}

contract DevTubFab {
    function newTub(DSToken sai, DSToken sin, DSToken skr, DSToken gem, DSToken gov, DSValue pip, DSValue pep, SaiVox vox, address pit) public returns (DevTub tub) {
        tub = new DevTub(sai, sin, skr, gem, gov, pip, pep, vox, pit);
        tub.setOwner(msg.sender);
    }
}

contract DevTopFab {
    function newTop(DevTub tub, SaiTap tap) public returns (DevTop top) {
        top = new DevTop(tub, tap);
        top.setOwner(msg.sender);
    }
}

contract DevDadFab {
    function newDad() public returns (DSGuard dad) {
        dad = new DSGuard();
        // convenience in tests
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('mint(uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('burn(uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('mint(address,uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('burn(address,uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('mint(uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('burn(uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('mint(address,uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('burn(address,uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('mint(uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('burn(uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('mint(address,uint256)')));
        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('burn(address,uint256)')));
        dad.setOwner(msg.sender);
    }
}

contract FakePerson {
    SaiTap  public tap;
    DSToken public sai;

    function FakePerson(SaiTap _tap) public {
        tap = _tap;
        sai = tap.sai();
        sai.approve(tap);
    }

    function cash() public {
        tap.cash(sai.balanceOf(this));
    }
}

contract SaiTestBase is DSTest, DSMath {
    DevVox   vox;
    DevTub   tub;
    DevTop   top;
    SaiTap   tap;

    SaiMom   mom;

    WETH9    gem;
    DSToken  sai;
    DSToken  sin;
    DSToken  skr;
    DSToken  gov;

    GemPit   pit;

    DSValue  pip;
    DSValue  pep;
    DSRoles  dad;

    function ray(uint256 wad) internal pure returns (uint256) {
        return wad * 10 ** 9;
    }
    function wad(uint256 ray_) internal pure returns (uint256) {
        return wdiv(ray_, RAY);
    }

    function mark(uint price) internal {
        pip.poke(bytes32(price));
    }
    function mark(DSToken tkn, uint price) internal {
        if (address(tkn) == address(gov)) pep.poke(bytes32(price));
        else if (address(tkn) == address(gem)) mark(price);
    }
    function warp(uint256 age) internal {
        vox.warp(age);
        tub.warp(age);
        top.warp(age);
    }

    function setUp() public {
        GemFab gemFab = new GemFab();
        DevVoxFab voxFab = new DevVoxFab();
        DevTubFab tubFab = new DevTubFab();
        TapFab tapFab = new TapFab();
        DevTopFab topFab = new DevTopFab();
        MomFab momFab = new MomFab();
        DevDadFab dadFab = new DevDadFab();

        DaiFab daiFab = new DaiFab(gemFab, VoxFab(voxFab), TubFab(tubFab), tapFab, TopFab(topFab), momFab, DadFab(dadFab));

        gem = new WETH9();
        gem.deposit.value(100 ether)();
        gov = new DSToken('GOV');
        pip = new DSValue();
        pep = new DSValue();
        pit = new GemPit();

        daiFab.makeTokens();
        daiFab.makeVoxTub(ERC20(gem), gov, pip, pep, pit);
        daiFab.makeTapTop();
        daiFab.configParams();
        daiFab.verifyParams();
        DSRoles authority = new DSRoles();
        authority.setRootUser(this, true);
        daiFab.configAuth(authority);

        sai = DSToken(daiFab.sai());
        sin = DSToken(daiFab.sin());
        skr = DSToken(daiFab.skr());
        vox = DevVox(daiFab.vox());
        tub = DevTub(daiFab.tub());
        tap = SaiTap(daiFab.tap());
        top = DevTop(daiFab.top());
        mom = SaiMom(daiFab.mom());
        dad = DSRoles(daiFab.dad());

        sai.approve(tub);
        skr.approve(tub);
        gem.approve(tub, uint(-1));
        gov.approve(tub);

        sai.approve(tap);
        skr.approve(tap);

        mark(1 ether);
        mark(gov, 1 ether);

        mom.setCap(20 ether);
        mom.setAxe(ray(1 ether));
        mom.setMat(ray(1 ether));
        mom.setTax(ray(1 ether));
        mom.setFee(ray(1 ether));
        mom.setTubGap(1 ether);
        mom.setTapGap(1 ether);
    }
}

contract SaiTubTest is SaiTestBase {
    function testBasic() public {
        assertEq( skr.balanceOf(tub), 0 ether );
        assertEq( skr.balanceOf(this), 0 ether );
        assertEq( gem.balanceOf(tub), 0 ether );

        // edge case
        assertEq( uint256(tub.per()), ray(1 ether) );
        tub.join(10 ether);
        assertEq( uint256(tub.per()), ray(1 ether) );

        assertEq( skr.balanceOf(this), 10 ether );
        assertEq( gem.balanceOf(tub), 10 ether );
        // price formula
        tub.join(10 ether);
        assertEq( uint256(tub.per()), ray(1 ether) );
        assertEq( skr.balanceOf(this), 20 ether );
        assertEq( gem.balanceOf(tub), 20 ether );

        var cup = tub.open();

        assertEq( skr.balanceOf(this), 20 ether );
        assertEq( skr.balanceOf(tub), 0 ether );
        tub.lock(cup, 10 ether); // lock skr token
        assertEq( skr.balanceOf(this), 10 ether );
        assertEq( skr.balanceOf(tub), 10 ether );

        assertEq( sai.balanceOf(this), 0 ether);
        tub.draw(cup, 5 ether);
        assertEq( sai.balanceOf(this), 5 ether);


        assertEq( sai.balanceOf(this), 5 ether);
        tub.wipe(cup, 2 ether);
        assertEq( sai.balanceOf(this), 3 ether);

        assertEq( sai.balanceOf(this), 3 ether);
        assertEq( skr.balanceOf(this), 10 ether );
        tub.shut(cup);
        assertEq( sai.balanceOf(this), 0 ether);
        assertEq( skr.balanceOf(this), 20 ether );
    }
    function testGive() public {
        var cup = tub.open();
        assertEq(tub.lad(cup), this);

        address ali = 0x456;
        tub.give(cup, ali);
        assertEq(tub.lad(cup), ali);
    }
    function testFailGiveNotLad() public {
        var cup = tub.open();
        address ali = 0x456;
        tub.give(cup, ali);

        address bob = 0x789;
        tub.give(cup, bob);
    }
    function testMold() public {
        var setAxe = bytes4(keccak256('setAxe(uint256)'));
        var setCap = bytes4(keccak256('setCap(uint256)'));
        var setMat = bytes4(keccak256('setMat(uint256)'));

        assertTrue(mom.call(setCap, 0 ether));
        assertTrue(mom.call(setCap, 5 ether));

        assertTrue(!mom.call(setAxe, ray(2 ether)));
        assertTrue( mom.call(setMat, ray(2 ether)));
        assertTrue( mom.call(setAxe, ray(2 ether)));
        assertTrue(!mom.call(setMat, ray(1 ether)));
    }
    function testTune() public {
        assertEq(vox.how(), 0);
        mom.setHow(2 * 10 ** 25);
        assertEq(vox.how(), 2 * 10 ** 25);
    }
    function testPriceFeedSetters() public {
        var setPip = bytes4(keccak256('setPip(address)'));
        var setPep = bytes4(keccak256('setPep(address)'));
        var setVox = bytes4(keccak256('setVox(address)'));

        assertTrue(tub.pip() != address(0x1));
        assertTrue(tub.pep() != address(0x2));
        assertTrue(tub.vox() != address(0x3));
        assertTrue(mom.call(setPip, address(0x1)));
        assertTrue(mom.call(setPep, address(0x2)));
        assertTrue(mom.call(setVox, address(0x3)));
        assertTrue(tub.pip() == address(0x1));
        assertTrue(tub.pep() == address(0x2));
        assertTrue(tub.vox() == address(0x3));
    }
    function testJoinInitial() public {
        assertEq(skr.totalSupply(),     0 ether);
        assertEq(skr.balanceOf(this),   0 ether);
        assertEq(gem.balanceOf(this), 100 ether);
        tub.join(10 ether);
        assertEq(skr.balanceOf(this), 10 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        assertEq(gem.balanceOf(tub),  10 ether);
    }
    function testJoinExit() public {
        assertEq(skr.balanceOf(this), 0 ether);
        assertEq(gem.balanceOf(this), 100 ether);
        tub.join(10 ether);
        assertEq(skr.balanceOf(this), 10 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        assertEq(gem.balanceOf(tub),  10 ether);

        tub.exit(5 ether);
        assertEq(skr.balanceOf(this),  5 ether);
        assertEq(gem.balanceOf(this), 95 ether);
        assertEq(gem.balanceOf(tub),   5 ether);

        tub.join(2 ether);
        assertEq(skr.balanceOf(this),  7 ether);
        assertEq(gem.balanceOf(this), 93 ether);
        assertEq(gem.balanceOf(tub),   7 ether);

        tub.exit(1 ether);
        assertEq(skr.balanceOf(this),  6 ether);
        assertEq(gem.balanceOf(this), 94 ether);
        assertEq(gem.balanceOf(tub),   6 ether);
    }
    function testFailOverDraw() public {
        mom.setMat(ray(1 ether));
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        tub.draw(cup, 11 ether);
    }
    function testFailOverDrawExcess() public {
        mom.setMat(ray(1 ether));
        tub.join(20 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        tub.draw(cup, 11 ether);
    }
    function testDraw() public {
        mom.setMat(ray(1 ether));
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        assertEq(sai.balanceOf(this),  0 ether);
        tub.draw(cup, 10 ether);
        assertEq(sai.balanceOf(this), 10 ether);
    }
    function testWipe() public {
        mom.setMat(ray(1 ether));
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 10 ether);

        assertEq(sai.balanceOf(this), 10 ether);
        tub.wipe(cup, 5 ether);
        assertEq(sai.balanceOf(this),  5 ether);
    }
    function testUnsafe() public {
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 9 ether);

        assertTrue(tub.safe(cup));
        mark(1 ether / 2);
        assertTrue(!tub.safe(cup));
    }
    function testBiteUnderParity() public {
        assertEq(uint(tub.axe()), uint(ray(1 ether)));  // 100% collateralisation limit
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 5 ether);           // 200% collateralisation
        mark(1 ether / 4);                // 50% collateralisation

        assertEq(tap.fog(), uint(0));
        tub.bite(cup);
        assertEq(tap.fog(), uint(10 ether));
    }
    function testBiteOverParity() public {
        mom.setMat(ray(2 ether));  // require 200% collateralisation
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        tub.draw(cup, 4 ether);  // 250% collateralisation
        assertTrue(tub.safe(cup));
        mark(1 ether / 2);       // 125% collateralisation
        assertTrue(!tub.safe(cup));

        assertEq(tub.din(),    4 ether);
        assertEq(tub.tab(cup), 4 ether);
        assertEq(tap.fog(),    0 ether);
        assertEq(tap.woe(),    0 ether);
        tub.bite(cup);
        assertEq(tub.din(),    0 ether);
        assertEq(tub.tab(cup), 0 ether);
        assertEq(tap.fog(),    8 ether);
        assertEq(tap.woe(),    4 ether);

        // cdp should now be safe with 0 sai debt and 2 skr remaining
        var skr_before = skr.balanceOf(this);
        tub.free(cup, 1 ether);
        assertEq(skr.balanceOf(this) - skr_before, 1 ether);
    }
    function testLock() public {
        tub.join(10 ether);
        var cup = tub.open();

        assertEq(skr.balanceOf(tub),  0 ether);
        tub.lock(cup, 10 ether);
        assertEq(skr.balanceOf(tub), 10 ether);
    }
    function testFree() public {
        mom.setMat(ray(2 ether));  // require 200% collateralisation
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 4 ether);  // 250% collateralisation

        var skr_before = skr.balanceOf(this);
        tub.free(cup, 2 ether);  // 225%
        assertEq(skr.balanceOf(this) - skr_before, 2 ether);
    }
    function testFailFreeToUnderCollat() public {
        mom.setMat(ray(2 ether));  // require 200% collateralisation
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 4 ether);  // 250% collateralisation

        tub.free(cup, 3 ether);  // 175% -- fails
    }
    function testFailDrawOverDebtCeiling() public {
        mom.setCap(4 ether);
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        tub.draw(cup, 5 ether);
    }
    function testDebtCeiling() public {
        mom.setCap(5 ether);
        mom.setMat(ray(2 ether));  // require 200% collat
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        tub.draw(cup, 5 ether);          // 200% collat, full debt ceiling
        mark(1 ether / 2);  // 100% collat

        assertEq(tub.air(), uint(10 ether));
        assertEq(tap.fog(), uint(0 ether));
        tub.bite(cup);
        assertEq(tub.air(), uint(0 ether));
        assertEq(tap.fog(), uint(10 ether));

        tub.join(10 ether);
        // skr hasn't been diluted yet so still 1:1 skr:gem
        assertEq(skr.balanceOf(this), 10 ether);
    }
}

contract CageTest is SaiTestBase {
    // ensure cage sets the settle prices right
    function cageSetup() public returns (bytes32) {
        mom.setCap(5 ether);            // 5 sai debt ceiling
        mark(1 ether);   // price 1:1 gem:ref
        mom.setMat(ray(2 ether));       // require 200% collat
        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 5 ether);       // 200% collateralisation

        return cup;
    }
    function testCageSafeOverCollat() public {
        cageSetup();

        assertEq(top.fix(), 0);
        assertEq(tub.fit(), 0);
        assertEq(tap.woe(), 0);         // no bad debt
        assertEq(tub.pie(), 10 ether);

        tub.join(20 ether);   // give us some more skr
        mark(1 ether);
        top.cage();

        assertEq(tub.din(),      5 ether);  // debt remains in tub
        assertEq(wad(top.fix()), 1 ether);  // sai redeems 1:1 with gem
        assertEq(wad(tub.fit()), 1 ether);  // skr redeems 1:1 with gem just before pushing gem to tub

        assertEq(gem.balanceOf(tap),  5 ether);  // saved for sai
        assertEq(gem.balanceOf(tub), 25 ether);  // saved for skr
    }
    function testCageUnsafeOverCollat() public {
        cageSetup();

        assertEq(top.fix(), 0);
        assertEq(tub.fit(), 0);
        assertEq(tub.per(), ray(1 ether));

        tub.join(20 ether);   // give us some more skr
        var price = wdiv(3 ether, 4 ether);
        mark(price);
        top.cage();        // 150% collat

        assertEq(top.fix(), rdiv(1 ether, price));  // sai redeems 4:3 with gem
        assertEq(tub.fit(), ray(price));                 // skr redeems 1:1 with gem just before pushing gem to tub

        // gem needed for sai is 5 * 4 / 3
        var saved = rmul(5 ether, rdiv(WAD, price));
        assertEq(gem.balanceOf(tap),  saved);             // saved for sai
        assertEq(gem.balanceOf(tub),  30 ether - saved);  // saved for skr
    }
    function testCageAtCollat() public {
        cageSetup();

        assertEq(top.fix(), 0);
        assertEq(tub.fit(), 0);
        assertEq(tub.per(), ray(1 ether));

        var price = wdiv(1 ether, 2 ether);  // 100% collat
        mark(price);
        top.cage();

        assertEq(top.fix(), ray(2 ether));  // sai redeems 1:2 with gem, 1:1 with ref
        assertEq(tub.per(), 0);       // skr redeems 1:0 with gem after cage
    }
    function testCageAtCollatFreeSkr() public {
        cageSetup();

        assertEq(top.fix(), 0);
        assertEq(tub.fit(), 0);
        assertEq(tub.per(), ray(1 ether));

        tub.join(20 ether);   // give us some more skr
        var price = wdiv(1 ether, 2 ether);  // 100% collat
        mark(price);
        top.cage();

        assertEq(top.fix(), ray(2 ether));  // sai redeems 1:2 with gem, 1:1 with ref
        assertEq(tub.fit(), ray(price));       // skr redeems 1:1 with gem just before pushing gem to tub
    }
    function testCageUnderCollat() public {
        cageSetup();

        assertEq(top.fix(), 0);
        assertEq(tub.fit(), 0);
        assertEq(tub.per(), ray(1 ether));

        var price = wdiv(1 ether, 4 ether);   // 50% collat
        mark(price);
        top.cage();

        assertEq(2 * sai.totalSupply(), gem.balanceOf(tap));
        assertEq(top.fix(), ray(2 ether));  // sai redeems 1:2 with gem, 2:1 with ref
        assertEq(tub.per(), 0);       // skr redeems 1:0 with gem after cage
    }
    function testCageUnderCollatFreeSkr() public {
        cageSetup();

        assertEq(top.fix(), 0);
        assertEq(tub.fit(), 0);
        assertEq(tub.per(), ray(1 ether));

        tub.join(20 ether);   // give us some more skr
        var price = wdiv(1 ether, 4 ether);   // 50% collat
        mark(price);
        top.cage();

        assertEq(4 * sai.totalSupply(), gem.balanceOf(tap));
        assertEq(top.fix(), ray(4 ether));                 // sai redeems 1:4 with gem, 1:1 with ref
    }

    function testCageNoSai() public {
        var cup = cageSetup();
        tub.wipe(cup, 5 ether);
        assertEq(sai.totalSupply(), 0);

        top.cage();
        assertEq(top.fix(), ray(1 ether));
    }
    function testMock() public {
        cageSetup();
        top.cage();

        gem.deposit.value(1000 ether)();
        gem.approve(tap, uint(-1));
        tap.mock(1000 ether);
        assertEq(sai.balanceOf(this), 1005 ether);
        assertEq(gem.balanceOf(tap),  1005 ether);
    }
    function testMockNoSai() public {
        var cup = cageSetup();
        tub.wipe(cup, 5 ether);
        assertEq(sai.totalSupply(), 0);

        top.cage();

        gem.deposit.value(1000 ether)();
        gem.approve(tap, uint(-1));
        tap.mock(1000 ether);
        assertEq(sai.balanceOf(this), 1000 ether);
        assertEq(gem.balanceOf(tap),  1000 ether);
    }

    // ensure cash returns the expected amount
    function testCashSafeOverCollat() public {
        var cup = cageSetup();
        mark(1 ether);
        top.cage();

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(skr.balanceOf(this),  0 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        assertEq(gem.balanceOf(tub),   5 ether);
        assertEq(gem.balanceOf(tap),   5 ether);

        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),   0 ether);
        assertEq(skr.balanceOf(this),   0 ether);
        assertEq(gem.balanceOf(this),  95 ether);
        assertEq(gem.balanceOf(tub),    5 ether);

        assertEq(tub.ink(cup), 10 ether);
        tub.bite(cup);
        assertEq(tub.ink(cup), 5 ether);
        tub.free(cup, tub.ink(cup));
        assertEq(skr.balanceOf(this),   5 ether);
        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        assertEq(skr.totalSupply(), 0);
    }
    function testCashSafeOverCollatWithFreeSkr() public {
        var cup = cageSetup();
        tub.join(20 ether);   // give us some more skr
        mark(1 ether);
        top.cage();

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(skr.balanceOf(this), 20 ether);
        assertEq(gem.balanceOf(this), 70 ether);
        assertEq(gem.balanceOf(tub),  25 ether);
        assertEq(gem.balanceOf(tap),   5 ether);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        tap.vent();
        top.flow();
        assertEq(skr.balanceOf(this), 25 ether);
        tap.cash(sai.balanceOf(this));
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(sai.balanceOf(this),   0 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        tap.vent();
        assertEq(sai.totalSupply(), 0);
        assertEq(skr.totalSupply(), 0);
    }
    function testFailCashSafeOverCollatWithFreeSkrExitBeforeBail() public {
        // fails because exit is before bail
        var cup = cageSetup();
        tub.join(20 ether);   // give us some more skr
        mark(1 ether);
        top.cage();

        tap.cash(sai.balanceOf(this));
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(skr.balanceOf(this), 0 ether);
        uint256 gemBySAI = 5 ether; // Adding 5 gem from 5 sai
        uint256 gemBySKR = wdiv(wmul(20 ether, 30 ether - gemBySAI), 30 ether);
        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);

        assertEq(sai.balanceOf(this), 0);
        assertEq(sai.totalSupply(), 0);
        assertEq(sin.totalSupply(), 0);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        tap.vent();
        top.flow();
        assertEq(skr.balanceOf(this), 5 ether); // skr retrieved by bail(cup)

        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(sai.balanceOf(this),   0 ether);
        assertEq(gem.balanceOf(tub),    0 ether);
        assertEq(sai.totalSupply(), 0);
        assertEq(sin.totalSupply(), 0);

        assertEq(skr.totalSupply(), 0);
    }
    function testCashUnsafeOverCollat() public {
        var cup = cageSetup();
        tub.join(20 ether);   // give us some more skr
        var price = wdiv(3 ether, 4 ether);
        mark(price);
        top.cage();        // 150% collat

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(skr.balanceOf(this), 20 ether);
        assertEq(gem.balanceOf(this), 70 ether);

        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),   0 ether);
        assertEq(skr.balanceOf(this),  20 ether);

        uint256 gemBySAI = wdiv(wmul(5 ether, 4 ether), 3 ether);
        uint256 gemBySKR = 0;

        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);
        assertEq(gem.balanceOf(tub),  30 ether - gemBySAI - gemBySKR);

        // how much gem should be returned?
        // there were 10 gems initially, of which 5 were 100% collat
        // at the cage price, 5 * 4 / 3 are 100% collat,
        // leaving 10 - 5 * 4 / 3 as excess = 3.333
        // this should all be returned
        var ink = tub.ink(cup);
        var tab = tub.tab(cup);
        var skrToRecover = sub(ink, wdiv(tab, price));
        tub.bite(cup);
        tub.free(cup, tub.ink(cup));

        assertEq(skr.balanceOf(this), 20 ether + skrToRecover);
        assertEq(skr.balanceOf(tub),  0 ether);

        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        tap.vent();
        assertEq(skr.totalSupply(), 0);
        assertEq(sai.totalSupply(), 0);
    }
    function testCashAtCollat() public {
        var cup = cageSetup();
        var price = wdiv(1 ether, 2 ether);  // 100% collat
        mark(price);
        top.cage();

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(skr.balanceOf(this),  0 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),   0 ether);
        assertEq(skr.balanceOf(this),   0 ether);

        var saved = rmul(5 ether, rdiv(WAD, price));

        assertEq(gem.balanceOf(this),  90 ether + saved);
        assertEq(gem.balanceOf(tub),   10 ether - saved);

        // how much gem should be returned?
        // none :D
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);
        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        tap.vent();
        assertEq(skr.totalSupply(), 0);
        assertEq(sai.totalSupply(), 0);
    }
    function testCashAtCollatFreeSkr() public {
        var cup = cageSetup();
        tub.join(20 ether);   // give us some more skr
        var price = wdiv(1 ether, 2 ether);  // 100% collat
        mark(price);
        top.cage();

        assertEq(sai.balanceOf(this),   5 ether);
        assertEq(skr.balanceOf(this),  20 ether);
        assertEq(gem.balanceOf(this),  70 ether);

        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),   0 ether);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        assertEq(skr.totalSupply(), 0);
    }
    function testFailCashAtCollatFreeSkrExitBeforeBail() public {
        var cup = cageSetup();
        tub.join(20 ether);   // give us some more skr
        var price = wdiv(1 ether, 2 ether);  // 100% collat
        mark(price);
        top.cage();

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(skr.balanceOf(this), 20 ether);
        assertEq(gem.balanceOf(this), 70 ether);

        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),   0 ether);
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(skr.balanceOf(this),   0 ether);


        var gemBySAI = wmul(5 ether, 2 ether);
        var gemBySKR = wdiv(wmul(20 ether, 30 ether - gemBySAI), 30 ether);

        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);
        assertEq(gem.balanceOf(tub),  30 ether - gemBySAI - gemBySKR);

        assertEq(sai.totalSupply(), 0);
        assertEq(sin.totalSupply(), 0);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        tap.vent();
        tub.exit(uint256(skr.balanceOf(this)));

        // Cup did not have skr to free, then the ramaining gem in tub can not be shared as there is not more skr to exit
        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);
        assertEq(gem.balanceOf(tub),  30 ether - gemBySAI - gemBySKR);

        assertEq(skr.totalSupply(), 0);
    }
    function testCashUnderCollat() public {
        var cup = cageSetup();
        var price = wdiv(1 ether, 4 ether);  // 50% collat
        mark(price);
        top.cage();

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(skr.balanceOf(this),  0 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),   0 ether);
        assertEq(skr.balanceOf(this),   0 ether);

        // get back all 10 gems, which are now only worth 2.5 ref
        // so you've lost 50% on you sai
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        // how much gem should be returned?
        // none :D
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);
        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        tap.vent();
        assertEq(skr.totalSupply(), 0);
        assertEq(sai.totalSupply(), 0);
    }
    function testCashUnderCollatFreeSkr() public {
        var cup = cageSetup();
        tub.join(20 ether);   // give us some more skr
        var price = wdiv(1 ether, 4 ether);   // 50% collat
        mark(price);
        top.cage();

        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(gem.balanceOf(this), 70 ether);
        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),  0 ether);
        // returns 20 gems, taken from the free skr,
        // sai is made whole
        assertEq(gem.balanceOf(this), 90 ether);

        assertEq(skr.balanceOf(this),  20 ether);
        tub.bite(cup);
        tub.free(cup, tub.ink(cup));

        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this)));
        assertEq(skr.balanceOf(this),   0 ether);
        // the skr has taken a 50% loss - 10 gems returned from 20 put in
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(gem.balanceOf(tub),    0 ether);

        assertEq(sai.totalSupply(), 0);
        assertEq(skr.totalSupply(), 0);
    }
    function testCashSafeOverCollatAndMock() public {
        testCashSafeOverCollat();
        gem.approve(tap, uint(-1));
        tap.mock(5 ether);
        assertEq(sai.balanceOf(this), 5 ether);
        assertEq(gem.balanceOf(this), 95 ether);
        assertEq(gem.balanceOf(tap), 5 ether);
    }
    function testCashSafeOverCollatWithFreeSkrAndMock() public {
        testCashSafeOverCollatWithFreeSkr();
        gem.approve(tap, uint(-1));
        tap.mock(5 ether);
        assertEq(sai.balanceOf(this), 5 ether);
        assertEq(gem.balanceOf(this), 95 ether);
        assertEq(gem.balanceOf(tap), 5 ether);
    }
    function testFailCashSafeOverCollatWithFreeSkrExitBeforeBailAndMock() public {
        testFailCashSafeOverCollatWithFreeSkrExitBeforeBail();
        gem.approve(tap, uint(-1));
        tap.mock(5 ether);
        assertEq(sai.balanceOf(this), 5 ether);
        assertEq(gem.balanceOf(this), 95 ether);
        assertEq(gem.balanceOf(tap), 5 ether);
    }

    function testThreeCupsOverCollat() public {
        var cup = cageSetup();
        tub.join(90 ether);   // give us some more skr
        var cup2 = tub.open(); // open a new cup
        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI
        var cup3 = tub.open(); // open a new cup
        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI

        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(tub), 100 ether);
        assertEq(gem.balanceOf(this), 0);
        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 50 ether); // locked skr

        uint256 price = 1 ether;
        mark(price);
        top.cage();

        assertEq(gem.balanceOf(tap), 5 ether); // Needed to payout 5 sai
        assertEq(gem.balanceOf(tub), 95 ether);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup)); // 5 skr recovered, and 5 skr burnt

        assertEq(skr.balanceOf(this), 55 ether); // free skr
        assertEq(skr.balanceOf(tub), 40 ether); // locked skr

        tub.bite(cup2);
        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 75 ether); // free skr
        assertEq(skr.balanceOf(tub), 20 ether); // locked skr

        tub.bite(cup3);
        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 95 ether); // free skr
        assertEq(skr.balanceOf(tub), 0); // locked skr

        tap.cash(sai.balanceOf(this));

        assertEq(sai.balanceOf(this), 0);
        assertEq(gem.balanceOf(this), 5 ether);

        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this))); // exit 95 skr at price 95/95

        assertEq(gem.balanceOf(tub), 0);
        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(skr.totalSupply(), 0);
    }
    function testThreeCupsAtCollat() public {
        var cup = cageSetup();
        tub.join(90 ether);   // give us some more skr
        var cup2 = tub.open(); // open a new cup
        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI
        var cup3 = tub.open(); // open a new cup
        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI

        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(tub), 100 ether);
        assertEq(gem.balanceOf(this), 0);
        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 50 ether); // locked skr

        var price = wdiv(1 ether, 2 ether);
        mark(price);
        top.cage();

        assertEq(gem.balanceOf(tap), 10 ether); // Needed to payout 10 sai
        assertEq(gem.balanceOf(tub), 90 ether);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup)); // 10 skr burnt

        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 40 ether); // locked skr

        tub.bite(cup2);
        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 70 ether); // free skr
        assertEq(skr.balanceOf(tub), 20 ether); // locked skr

        tub.bite(cup3);
        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 90 ether); // free skr
        assertEq(skr.balanceOf(tub), 0); // locked skr

        tap.cash(sai.balanceOf(this));

        assertEq(sai.balanceOf(this), 0);
        assertEq(gem.balanceOf(this), 10 ether);

        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this))); // exit 90 skr at price 90/90

        assertEq(gem.balanceOf(tub), 0);
        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(skr.totalSupply(), 0);
    }
    function testThreeCupsUnderCollat() public {
        var cup = cageSetup();
        tub.join(90 ether);   // give us some more skr
        var cup2 = tub.open(); // open a new cup
        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI
        var cup3 = tub.open(); // open a new cup
        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI

        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(tub), 100 ether);
        assertEq(gem.balanceOf(this), 0);
        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 50 ether); // locked skr

        var price = wdiv(1 ether, 4 ether);
        mark(price);
        top.cage();

        assertEq(gem.balanceOf(tap), 20 ether); // Needed to payout 5 sai
        assertEq(gem.balanceOf(tub), 80 ether);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup)); // No skr is retrieved as the cup doesn't even cover the debt. 10 locked skr in cup are burnt from tub

        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 40 ether); // locked skr

        tub.bite(cup2);
        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 70 ether); // free skr
        assertEq(skr.balanceOf(tub), 20 ether); // locked skr

        tub.bite(cup3);
        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 90 ether); // free skr
        assertEq(skr.balanceOf(tub), 0); // locked skr

        tap.cash(sai.balanceOf(this));

        assertEq(sai.balanceOf(this), 0);
        assertEq(gem.balanceOf(this), 20 ether);

        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this))); // exit 90 skr at price 80/90

        assertEq(gem.balanceOf(tub), 0);
        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(skr.totalSupply(), 0);
    }
    function testThreeCupsSKRZeroValue() public {
        var cup = cageSetup();
        tub.join(90 ether);   // give us some more skr
        var cup2 = tub.open(); // open a new cup
        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI
        var cup3 = tub.open(); // open a new cup
        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI

        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(tub), 100 ether);
        assertEq(gem.balanceOf(this), 0);
        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 50 ether); // locked skr

        var price = wdiv(1 ether, 20 ether);
        mark(price);
        top.cage();

        assertEq(gem.balanceOf(tap), 100 ether); // Needed to payout 5 sai
        assertEq(gem.balanceOf(tub), 0 ether);

        tub.bite(cup);
        tub.free(cup, tub.ink(cup)); // No skr is retrieved as the cup doesn't even cover the debt. 10 locked skr in cup are burnt from tub

        assertEq(skr.balanceOf(this), 50 ether); // free skr
        assertEq(skr.balanceOf(tub), 40 ether); // locked skr

        tub.bite(cup2);
        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 70 ether); // free skr
        assertEq(skr.balanceOf(tub), 20 ether); // locked skr

        tub.bite(cup3);
        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered

        assertEq(skr.balanceOf(this), 90 ether); // free skr
        assertEq(skr.balanceOf(tub), 0); // locked skr

        tap.cash(sai.balanceOf(this));

        assertEq(sai.balanceOf(this), 0);
        assertEq(gem.balanceOf(this), 100 ether);

        tap.vent();
        top.flow();
        tub.exit(uint256(skr.balanceOf(this))); // exit 90 skr at price 0/90

        assertEq(gem.balanceOf(tub), 0);
        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(this), 100 ether);
        assertEq(skr.totalSupply(), 0);
    }

    function testPeriodicFixValue() public {
        cageSetup();

        assertEq(gem.balanceOf(tap), 0);
        assertEq(gem.balanceOf(tub), 10 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        assertEq(skr.balanceOf(this), 0 ether); // free skr
        assertEq(skr.balanceOf(tub), 10 ether); // locked skr

        FakePerson person = new FakePerson(tap);
        sai.transfer(person, 2.5 ether); // Transfer half of SAI balance to the other user

        var price = rdiv(9 ether, 8 ether);
        mark(price);
        top.cage();

        assertEq(gem.balanceOf(tap), rmul(5 ether, top.fix())); // Needed to payout 5 sai
        assertEq(gem.balanceOf(tub), sub(10 ether, rmul(5 ether, top.fix())));

        tap.cash(sai.balanceOf(this));

        assertEq(sai.balanceOf(this),     0 ether);
        assertEq(sai.balanceOf(person), 2.5 ether);
        assertEq(gem.balanceOf(this), add(90 ether, rmul(2.5 ether, top.fix())));

        person.cash();
    }

    function testCageExitAfterPeriod() public {
        var cup = cageSetup();
        mom.setMat(ray(1 ether));  // 100% collat limit
        tub.free(cup, 5 ether);  // 100% collat

        assertEq(uint(top.caged()), 0);
        top.cage();
        assertEq(uint(top.caged()), vox.era());

        // exit fails because ice != 0 && fog !=0 and not enough time passed
        assertTrue(!tub.call(bytes4(keccak256('exit(uint256)')), 5 ether));

        top.setCooldown(1 days);
        warp(1 days);
        assertTrue(!tub.call(bytes4(keccak256('exit(uint256)')), 5 ether));

        warp(1 seconds);
        top.flow();
        assertEq(skr.balanceOf(this), 5 ether);
        assertEq(gem.balanceOf(this), 90 ether);
        assertTrue(tub.call(bytes4(keccak256('exit(uint256)')), 4 ether));
        assertEq(skr.balanceOf(this), 1 ether);
        // n.b. we don't get back 4 as there is still skr in the cup
        assertEq(gem.balanceOf(this), 92 ether);

        // now we can cash in our sai
        assertEq(sai.balanceOf(this), 5 ether);
        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this), 0 ether);
        assertEq(gem.balanceOf(this), 97 ether);

        // the remaining gem can be claimed only if the cup skr is burned
        assertEq(tub.air(), 5 ether);
        assertEq(tap.fog(), 0 ether);
        assertEq(tub.din(), 5 ether);
        assertEq(tap.woe(), 0 ether);
        tub.bite(cup);
        assertEq(tub.air(), 0 ether);
        assertEq(tap.fog(), 5 ether);
        assertEq(tub.din(), 0 ether);
        assertEq(tap.woe(), 5 ether);

        tap.vent();
        assertEq(tap.fog(), 0 ether);

        // now this remaining 1 skr will claim all the remaining 3 ether.
        // this is why exiting early is bad if you want to maximise returns.
        // if we had exited with all the skr earlier, there would be 2.5 gem
        // trapped in the tub.
        tub.exit(1 ether);
        assertEq(skr.balanceOf(this),   0 ether);
        assertEq(gem.balanceOf(this), 100 ether);
    }

    function testShutEmptyCup() public {
        var cup = tub.open();
        var (lad,,,) = tub.cups(cup);
        assertEq(lad, this);
        tub.shut(cup);
        (lad,,,) = tub.cups(cup);
        assertEq(lad, 0);
    }
}

contract LiquidationTest is SaiTestBase {
    function liq(bytes32 cup) internal returns (uint256) {
        // compute the liquidation price of a cup
        var jam = rmul(tub.ink(cup), tub.per());  // this many eth
        var con = rmul(tub.tab(cup), vox.par());  // this much ref debt
        var min = rmul(con, tub.mat());        // minimum ref debt
        return wdiv(min, jam);
    }
    function testLiq() public {
        mom.setCap(100 ether);
        mark(2 ether);

        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 10 ether);        // 200% collateralisation

        mom.setMat(ray(1 ether));         // require 100% collateralisation
        assertEq(liq(cup), 1 ether);

        mom.setMat(ray(3 ether / 2));     // require 150% collateralisation
        assertEq(liq(cup), wdiv(3 ether, 2 ether));

        mark(6 ether);
        assertEq(liq(cup), wdiv(3 ether, 2 ether));

        tub.draw(cup, 30 ether);
        assertEq(liq(cup), 6 ether);

        tub.join(10 ether);
        assertEq(liq(cup), 6 ether);

        tub.lock(cup, 10 ether);  // now 40 drawn on 20 gem == 120 ref
        assertEq(liq(cup), 3 ether);
    }
    function collat(bytes32 cup) internal returns (uint256) {
        // compute the collateralised fraction of a cup
        var pro = rmul(tub.ink(cup), tub.tag());
        var con = rmul(tub.tab(cup), vox.par());
        return wdiv(pro, con);
    }
    function testCollat() public {
        mom.setCap(100 ether);
        mark(2 ether);

        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 10 ether);

        assertEq(collat(cup), 2 ether);  // 200%

        mark(4 ether);
        assertEq(collat(cup), 4 ether);  // 400%

        tub.draw(cup, 15 ether);
        assertEq(collat(cup), wdiv(8 ether, 5 ether));  // 160%

        mark(5 ether);
        tub.free(cup, 5 ether);
        assertEq(collat(cup), 1 ether);  // 100%

        mark(4 ether);
        assertEq(collat(cup), wdiv(4 ether, 5 ether));  // 80%

        tub.wipe(cup, 9 ether);
        assertEq(collat(cup), wdiv(5 ether, 4 ether));  // 125%
    }

    function testBustMint() public {
        mom.setCap(100 ether);
        mom.setMat(ray(wdiv(3 ether, 2 ether)));  // 150% liq limit
        mark(2 ether);

        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);

        mark(3 ether);
        tub.draw(cup, 16 ether);  // 125% collat
        mark(2 ether);

        assertTrue(!tub.safe(cup));
        tub.bite(cup);
        // 20 ref of gem on 16 ref of sai
        // 125%
        // 100% = 16ref of gem == 8 gem
        assertEq(tap.fog(), 8 ether);

        // 8 skr for sale
        assertEq(tub.per(), ray(1 ether));

        // get 2 skr, pay 4 sai (25% of the debt)
        var sai_before = sai.balanceOf(this);
        var skr_before = skr.balanceOf(this);
        assertEq(sai_before, 16 ether);
        tap.bust(2 ether);
        var sai_after = sai.balanceOf(this);
        var skr_after = skr.balanceOf(this);
        assertEq(sai_before - sai_after, 4 ether);
        assertEq(skr_after - skr_before, 2 ether);

        // price drop. now remaining 6 skr cannot cover bad debt (12 sai)
        mark(1 ether);

        // get 6 skr, pay 6 sai
        tap.bust(6 ether);
        // no more skr remaining to sell
        assertEq(tap.fog(), 0);
        // but skr supply unchanged
        assertEq(skr.totalSupply(), 10 ether);

        // now skr will be minted
        tap.bust(2 ether);
        assertEq(skr.totalSupply(), 12 ether);
    }
    function testBustNoMint() public {
        mom.setCap(1000 ether);
        mom.setMat(ray(2 ether));    // 200% liq limit
        mom.setAxe(ray(1.5 ether));  // 150% liq penalty
        mark(20 ether);

        tub.join(10 ether);
        var cup = tub.open();
        tub.lock(cup, 10 ether);
        tub.draw(cup, 100 ether);  // 200 % collat

        mark(15 ether);
        tub.bite(cup);

        // nothing remains in the cup
        assertEq(tub.tab(cup), 0);
        assertEq(tub.ink(cup), 0);

        // all collateral is now fog
        assertEq(tap.fog(), 10 ether);
        assertEq(tap.woe(), 100 ether);

        // the fog is worth 150 sai and the woe is worth 100 sai.
        // If all the fog is sold, there will be a sai surplus.

        // get some more sai to buy with
        tub.join(10 ether);
        var mug = tub.open();
        tub.lock(mug, 10 ether);
        tub.draw(mug, 50 ether);

        tap.bust(10 ether);
        assertEq(sai.balanceOf(this), 0 ether);
        assertEq(skr.balanceOf(this), 10 ether);
        assertEq(tap.fog(), 0 ether);
        assertEq(tap.woe(), 0 ether);
        assertEq(tap.joy(), 50 ether);

        // joy is available through boom
        assertEq(tap.bid(1 ether), 15 ether);
        tap.boom(2 ether);
        assertEq(sai.balanceOf(this), 30 ether);
        assertEq(skr.balanceOf(this),  8 ether);
        assertEq(tap.fog(), 0 ether);
        assertEq(tap.woe(), 0 ether);
        assertEq(tap.joy(), 20 ether);
    }
}

contract TapTest is SaiTestBase {
    function testTapSetup() public {
        assertEq(sai.balanceOf(tap), tap.joy());
        assertEq(sin.balanceOf(tap), tap.woe());
        assertEq(skr.balanceOf(tap), tap.fog());

        assertEq(tap.joy(), 0);
        assertEq(tap.woe(), 0);
        assertEq(tap.fog(), 0);

        sai.mint(tap, 3);
        sin.mint(tap, 4);
        skr.mint(tap, 5);

        assertEq(tap.joy(), 3);
        assertEq(tap.woe(), 4);
        assertEq(tap.fog(), 5);
    }
    // boom (flap) is surplus sale (sai for skr->burn)
    function testTapBoom() public {
        sai.mint(tap, 50 ether);
        tub.join(60 ether);

        assertEq(sai.balanceOf(this),  0 ether);
        assertEq(skr.balanceOf(this), 60 ether);
        tap.boom(50 ether);
        assertEq(sai.balanceOf(this), 50 ether);
        assertEq(skr.balanceOf(this), 10 ether);
        assertEq(tap.joy(), 0);
    }
    function testFailTapBoomOverJoy() public {
        sai.mint(tap, 50 ether);
        tub.join(60 ether);
        tap.boom(51 ether);
    }
    function testTapBoomHeals() public {
        sai.mint(tap, 60 ether);
        sin.mint(tap, 50 ether);
        tub.join(10 ether);

        tap.boom(0 ether);
        assertEq(tap.joy(), 10 ether);
    }
    function testFailTapBoomNetWoe() public {
        sai.mint(tap, 50 ether);
        sin.mint(tap, 60 ether);
        tub.join(10 ether);
        tap.boom(1 ether);
    }
    function testTapBoomBurnsSkr() public {
        sai.mint(tap, 50 ether);
        tub.join(60 ether);

        assertEq(skr.totalSupply(), 60 ether);
        tap.boom(20 ether);
        assertEq(skr.totalSupply(), 40 ether);
    }
    function testTapBoomIncreasesPer() public {
        sai.mint(tap, 50 ether);
        tub.join(60 ether);

        assertEq(tub.per(), ray(1 ether));
        tap.boom(30 ether);
        assertEq(tub.per(), ray(2 ether));
    }
    function testTapBoomMarkDep() public {
        sai.mint(tap, 50 ether);
        tub.join(50 ether);

        mark(2 ether);
        tap.boom(10 ether);
        assertEq(sai.balanceOf(this), 20 ether);
        assertEq(sai.balanceOf(tap),  30 ether);
        assertEq(skr.balanceOf(this), 40 ether);
    }
    function testTapBoomPerDep() public {
        sai.mint(tap, 50 ether);
        tub.join(50 ether);

        assertEq(tub.per(), ray(1 ether));
        skr.mint(50 ether);  // halves per
        assertEq(tub.per(), ray(.5 ether));

        tap.boom(10 ether);
        assertEq(sai.balanceOf(this),  5 ether);
        assertEq(sai.balanceOf(tap),  45 ether);
        assertEq(skr.balanceOf(this), 90 ether);
    }
    // flip is collateral sale (skr for sai)
    function testTapBustFlip() public {
        sai.mint(50 ether);
        tub.join(50 ether);
        skr.push(tap, 50 ether);
        assertEq(tap.fog(), 50 ether);

        assertEq(skr.balanceOf(this),  0 ether);
        assertEq(sai.balanceOf(this), 50 ether);
        tap.bust(30 ether);
        assertEq(skr.balanceOf(this), 30 ether);
        assertEq(sai.balanceOf(this), 20 ether);
    }
    function testFailTapBustFlipOverFog() public { // FAIL
        sai.mint(50 ether);
        tub.join(50 ether);
        skr.push(tap, 50 ether);

        tap.bust(51 ether);
    }
    function testTapBustFlipHealsNetJoy() public {
        sai.mint(tap, 10 ether);
        sin.mint(tap, 20 ether);
        tub.join(50 ether);
        skr.push(tap, 50 ether);

        sai.mint(15 ether);
        tap.bust(15 ether);
        assertEq(tap.joy(), 5 ether);
        assertEq(tap.woe(), 0 ether);
    }
    function testTapBustFlipHealsNetWoe() public {
        sai.mint(tap, 10 ether);
        sin.mint(tap, 20 ether);
        tub.join(50 ether);
        skr.push(tap, 50 ether);

        sai.mint(5 ether);
        tap.bust(5 ether);
        assertEq(tap.joy(), 0 ether);
        assertEq(tap.woe(), 5 ether);
    }
    // flop is debt sale (woe->skr for sai)
    function testTapBustFlop() public {
        tub.join(50 ether);  // avoid per=1 init case
        sai.mint(100 ether);
        sin.mint(tap, 50 ether);
        assertEq(tap.woe(), 50 ether);

        assertEq(skr.balanceOf(this),  50 ether);
        assertEq(sai.balanceOf(this), 100 ether);
        tap.bust(50 ether);
        assertEq(skr.balanceOf(this), 100 ether);
        assertEq(sai.balanceOf(this),  75 ether);
    }
    function testFailTapBustFlopNetJoy() public {
        tub.join(50 ether);  // avoid per=1 init case
        sai.mint(100 ether);
        sin.mint(tap, 50 ether);
        sai.mint(tap, 100 ether);

        tap.bust(1);  // anything but zero should fail
    }
    function testTapBustFlopMintsSkr() public {
        tub.join(50 ether);  // avoid per=1 init case
        sai.mint(100 ether);
        sin.mint(tap, 50 ether);

        assertEq(skr.totalSupply(),  50 ether);
        tap.bust(20 ether);
        assertEq(skr.totalSupply(),  70 ether);
    }
    function testTapBustFlopDecreasesPer() public {
        tub.join(50 ether);  // avoid per=1 init case
        sai.mint(100 ether);
        sin.mint(tap, 50 ether);

        assertEq(tub.per(), ray(1 ether));
        tap.bust(50 ether);
        assertEq(tub.per(), ray(.5 ether));
    }

    function testTapBustAsk() public {
        tub.join(50 ether);
        assertEq(tap.ask(50 ether), 50 ether);

        skr.mint(50 ether);
        assertEq(tap.ask(50 ether), 25 ether);

        skr.mint(100 ether);
        assertEq(tap.ask(50 ether), 12.5 ether);

        skr.burn(175 ether);
        assertEq(tap.ask(50 ether), 100 ether);

        skr.mint(25 ether);
        assertEq(tap.ask(50 ether), 50 ether);

        skr.mint(10 ether);
        // per = 5 / 6
        assertEq(tap.ask(60 ether), 50 ether);

        skr.mint(30 ether);
        // per = 5 / 9
        assertEq(tap.ask(90 ether), 50 ether);

        skr.mint(10 ether);
        // per = 1 / 2
        assertEq(tap.ask(100 ether), 50 ether);
    }
    // flipflop is debt sale when collateral present
    function testTapBustFlipFlopRounding() public {
        tub.join(50 ether);  // avoid per=1 init case
        sai.mint(100 ether);
        sin.mint(tap, 100 ether);
        skr.push(tap,  50 ether);
        assertEq(tap.joy(),   0 ether);
        assertEq(tap.woe(), 100 ether);
        assertEq(tap.fog(),  50 ether);

        assertEq(skr.balanceOf(this),   0 ether);
        assertEq(sai.balanceOf(this), 100 ether);
        assertEq(skr.totalSupply(),    50 ether);

        assertEq(tub.per(), ray(1 ether));
        assertEq(tap.s2s(), ray(1 ether));
        assertEq(tub.tag(), ray(1 ether));
        assertEq(tap.ask(60 ether), 60 ether);
        tap.bust(60 ether);
        assertEq(tub.per(), rdiv(5, 6));
        assertEq(tap.s2s(), rdiv(5, 6));
        assertEq(tub.tag(), rdiv(5, 6));
        // non ray prices would give small rounding error because wad math
        assertEq(tap.ask(60 ether), 50 ether);
        assertEq(skr.totalSupply(),    60 ether);
        assertEq(tap.fog(),             0 ether);
        assertEq(skr.balanceOf(this),  60 ether);
        assertEq(sai.balanceOf(this),  50 ether);
    }
    function testTapBustFlipFlop() public {
        tub.join(50 ether);  // avoid per=1 init case
        sai.mint(100 ether);
        sin.mint(tap, 100 ether);
        skr.push(tap,  50 ether);
        assertEq(tap.joy(),   0 ether);
        assertEq(tap.woe(), 100 ether);
        assertEq(tap.fog(),  50 ether);

        assertEq(skr.balanceOf(this),   0 ether);
        assertEq(sai.balanceOf(this), 100 ether);
        assertEq(skr.totalSupply(),    50 ether);
        assertEq(tub.per(), ray(1 ether));
        tap.bust(80 ether);
        assertEq(tub.per(), rdiv(5, 8));
        assertEq(skr.totalSupply(),    80 ether);
        assertEq(tap.fog(),             0 ether);
        assertEq(skr.balanceOf(this),  80 ether);
        assertEq(sai.balanceOf(this),  50 ether);  // expected 50, actual 50 ether + 2???!!!
    }
}

contract TaxTest is SaiTestBase {
    function testEraInit() public {
        assertEq(uint(vox.era()), now);
    }
    function testEraWarp() public {
        warp(20);
        assertEq(uint(vox.era()), now + 20);
    }
    function taxSetup() public returns (bytes32 cup) {
        mark(10 ether);
        gem.deposit.value(1000 ether)();

        mom.setCap(1000 ether);
        mom.setTax(1000000564701133626865910626);  // 5% / day
        cup = tub.open();
        tub.join(100 ether);
        tub.lock(cup, 100 ether);
        tub.draw(cup, 100 ether);
    }
    function testTaxEra() public {
        var cup = taxSetup();
        assertEq(tub.tab(cup), 100 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 105 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 110.25 ether);
    }
    // rum doesn't change on drip
    function testTaxRum() public {
        taxSetup();
        assertEq(tub.rum(),    100 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.rum(),    100 ether);
    }
    // din increases on drip
    function testTaxDin() public {
        taxSetup();
        assertEq(tub.din(),    100 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.din(),    105 ether);
    }
    // Tax accumulates as sai surplus, and CDP debt
    function testTaxJoy() public {
        var cup = taxSetup();
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),      0 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),      5 ether);
    }
    function testTaxJoy2() public {
        var cup = taxSetup();
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),      0 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),      5 ether);
        // now ensure din != rum
        tub.wipe(cup, 5 ether);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),      5 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),     10 ether);
    }
    function testTaxJoy3() public {
        var cup = taxSetup();
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),      0 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),      5 ether);
        // now ensure rum changes
        tub.wipe(cup, 5 ether);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),      5 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),     10 ether);
        // and ensure the last rum != din either
        tub.wipe(cup, 5 ether);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),     10 ether);
        warp(1 days);
        tub.drip();
        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),     15 ether);
    }
    function testTaxDraw() public {
        var cup = taxSetup();
        warp(1 days);
        assertEq(tub.tab(cup), 105 ether);
        tub.draw(cup, 100 ether);
        assertEq(tub.tab(cup), 205 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 215.25 ether);
    }
    function testTaxWipe() public {
        var cup = taxSetup();
        warp(1 days);
        assertEq(tub.tab(cup), 105 ether);
        tub.wipe(cup, 50 ether);
        assertEq(tub.tab(cup), 55 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 57.75 ether);
    }
    // collected fees are available through boom
    function testTaxBoom() public {
        taxSetup();
        warp(1 days);
        // should have 5 sai available == 0.5 skr
        tub.join(0.5 ether);  // get some unlocked skr

        assertEq(skr.totalSupply(),   100.5 ether);
        assertEq(sai.balanceOf(tap),    0 ether);
        assertEq(sin.balanceOf(tap),    0 ether);
        assertEq(sai.balanceOf(this), 100 ether);
        tub.drip();
        assertEq(sai.balanceOf(tap),    5 ether);
        tap.boom(0.5 ether);
        assertEq(skr.totalSupply(),   100 ether);
        assertEq(sai.balanceOf(tap),    0 ether);
        assertEq(sin.balanceOf(tap),    0 ether);
        assertEq(sai.balanceOf(this), 105 ether);
    }
    // Tax can flip a cup to unsafe
    function testTaxSafe() public {
        var cup = taxSetup();
        mark(1 ether);
        assertTrue(tub.safe(cup));
        warp(1 days);
        assertTrue(!tub.safe(cup));
    }
    function testTaxBite() public {
        var cup = taxSetup();
        mark(1 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 105 ether);
        tub.bite(cup);
        assertEq(tub.tab(cup),   0 ether);
        assertEq(tap.woe(),    105 ether);
    }
    function testTaxBiteRounding() public {
        var cup = taxSetup();
        mark(1 ether);
        mom.setMat(ray(1.5 ether));
        mom.setAxe(ray(1.4 ether));
        mom.setTax(ray(1.000000001547126 ether));
        // log_named_uint('tab', tub.tab(cup));
        // log_named_uint('sin', tub.din());
        for (uint i=0; i<=50; i++) {
            warp(10);
            // log_named_uint('tab', tub.tab(cup));
            // log_named_uint('sin', tub.din());
        }
        uint256 debtAfterWarp = rmul(100 ether, rpow(tub.tax(), 510));
        assertEq(tub.tab(cup), debtAfterWarp);
        tub.bite(cup);
        assertEq(tub.tab(cup), 0 ether);
        assertEq(tap.woe(), rmul(100 ether, rpow(tub.tax(), 510)));
    }
    function testTaxBail() public {
        var cup = taxSetup();
        warp(1 days);
        tub.drip();
        mark(10 ether);
        top.cage();

        warp(1 days);  // should have no effect
        tub.drip();

        assertEq(skr.balanceOf(this),  0 ether);
        assertEq(skr.balanceOf(tub), 100 ether);
        tub.bite(cup);
        tub.free(cup, tub.ink(cup));
        assertEq(skr.balanceOf(this), 89.5 ether);
        assertEq(skr.balanceOf(tub),     0 ether);

        assertEq(sai.balanceOf(this),  100 ether);
        assertEq(gem.balanceOf(this), 1000 ether);
        tap.cash(sai.balanceOf(this));
        assertEq(sai.balanceOf(this),    0 ether);
        assertEq(gem.balanceOf(this), 1010 ether);
    }
    function testTaxCage() public {
        // after cage, un-distributed tax revenue remains as joy - sai
        // surplus in the tap. The remaining joy, plus all outstanding
        // sai, balances the sin debt in the tub, plus any debt (woe) in
        // the tap.

        // The effect of this is that joy remaining in tap is
        // effectively distributed to all skr holders.
        var cup = taxSetup();
        warp(1 days);
        mark(10 ether);

        assertEq(tap.joy(), 0 ether);
        top.cage();                // should drip up to date
        assertEq(tap.joy(), 5 ether);
        warp(1 days);  tub.drip();  // should have no effect
        assertEq(tap.joy(), 5 ether);

        var owe = tub.tab(cup);
        assertEq(owe, 105 ether);
        assertEq(tub.din(), owe);
        assertEq(tap.woe(), 0);
        tub.bite(cup);
        assertEq(tub.din(), 0);
        assertEq(tap.woe(), owe);
        assertEq(tap.joy(), 5 ether);
    }
}

contract WayTest is SaiTestBase {
    function waySetup() public returns (bytes32 cup) {
        mark(10 ether);
        gem.deposit.value(1000 ether)();

        mom.setCap(1000 ether);

        cup = tub.open();
        tub.join(100 ether);
        tub.lock(cup, 100 ether);
        tub.draw(cup, 100 ether);
    }
    // what does way actually do?
    // it changes the value of sai relative to ref
    // way > 1 -> par increasing, more ref per sai
    // way < 1 -> par decreasing, less ref per sai

    // this changes the safety level of cups,
    // affecting `draw`, `wipe`, `free` and `bite`

    // if way < 1, par is decreasing and the con (in ref)
    // of a cup is decreasing, so cup holders need
    // less ref to wipe (but the same sai)
    // This makes cups *more* collateralised with time.
    function testTau() public {
        assertEq(uint(vox.era()), now);
        assertEq(uint(vox.tau()), now);
    }
    function testWayPar() public {
        mom.setWay(999999406327787478619865402);  // -5% / day

        assertEq(wad(vox.par()), 1.00 ether);
        warp(1 days);
        assertEq(wad(vox.par()), 0.95 ether);

        mom.setWay(1000000021979553151239153027);  // 200% / year
        warp(1 years);
        assertEq(wad(vox.par()), 1.90 ether);
    }
    function testWayDecreasingPrincipal() public {
        var cup = waySetup();
        mark(0.98 ether);
        assertTrue(!tub.safe(cup));

        mom.setWay(999999406327787478619865402);  // -5% / day
        warp(1 days);
        assertTrue(tub.safe(cup));
    }
    // `cage` is slightly affected: the cage price is
    // now in *sai per gem*, where before ref per gem
    // was equivalent.
    // `bail` is unaffected, as all values are in sai.
    function testWayCage() public {
        waySetup();

        mom.setWay(1000000021979553151239153027);  // 200% / year
        warp(1 years);  // par now 2

        // we have 100 sai
        // gem is worth 10 ref
        // sai is worth 2 ref
        // we should get back 100 / (10 / 2) = 20 gem

        top.cage();

        assertEq(gem.balanceOf(this), 1000 ether);
        assertEq(sai.balanceOf(this),  100 ether);
        assertEq(sai.balanceOf(tap),     0 ether);
        tap.cash(sai.balanceOf(this));
        assertEq(gem.balanceOf(this), 1020 ether);
        assertEq(sai.balanceOf(this),    0 ether);
        assertEq(sai.balanceOf(tap),     0 ether);
    }

    // `boom` and `bust` as par is now needed to determine
    // the skr / sai price.
    function testWayBust() public {
        var cup = waySetup();
        mark(0.5 ether);
        tub.bite(cup);

        assertEq(tap.joy(),   0 ether);
        assertEq(tap.woe(), 100 ether);
        assertEq(tap.fog(), 100 ether);
        assertEq(sai.balanceOf(this), 100 ether);

        tap.bust(50 ether);

        assertEq(tap.fog(),  50 ether);
        assertEq(tap.woe(),  75 ether);
        assertEq(sai.balanceOf(this), 75 ether);

        mom.setWay(999999978020447331861593082);  // -50% / year
        warp(1 years);
        assertEq(wad(vox.par()), 0.5 ether);
        // sai now worth half as much, so we cover twice as much debt
        // for the same skr
        tap.bust(50 ether);

        assertEq(tap.fog(),   0 ether);
        assertEq(tap.woe(),  25 ether);
        assertEq(sai.balanceOf(this), 25 ether);
    }
}

contract GapTest is SaiTestBase {
    // boom and bust have a spread parameter
    function setUp() public {
        super.setUp();

        gem.deposit.value(500 ether)();
        tub.join(500 ether);

        sai.mint(500 ether);
        sin.mint(500 ether);

        mark(2 ether);  // 2 ref per eth => 2 sai per skr
    }
    function testGapSaiTapBid() public {
        mark(1 ether);
        mom.setTapGap(1.01 ether);  // 1% spread
        assertEq(tap.bid(1 ether), 0.99 ether);
        mark(2 ether);
        assertEq(tap.bid(1 ether), 1.98 ether);
    }
    function testGapSaiTapAsk() public {
        mark(1 ether);
        mom.setTapGap(1.01 ether);  // 1% spread
        assertEq(tap.ask(1 ether), 1.01 ether);
        mark(2 ether);
        assertEq(tap.ask(1 ether), 2.02 ether);
    }
    function testGapBoom() public {
        sai.push(tap, 198 ether);
        assertEq(tap.joy(), 198 ether);

        mom.setTapGap(1.01 ether);  // 1% spread

        var sai_before = sai.balanceOf(this);
        var skr_before = skr.balanceOf(this);
        tap.boom(50 ether);
        var sai_after = sai.balanceOf(this);
        var skr_after = skr.balanceOf(this);
        assertEq(sai_after - sai_before, 99 ether);
        assertEq(skr_before - skr_after, 50 ether);
    }
    function testGapBust() public {
        skr.push(tap, 100 ether);
        sin.push(tap, 200 ether);
        assertEq(tap.fog(), 100 ether);
        assertEq(tap.woe(), 200 ether);

        mom.setTapGap(1.01 ether);

        var sai_before = sai.balanceOf(this);
        var skr_before = skr.balanceOf(this);
        tap.bust(50 ether);
        var sai_after = sai.balanceOf(this);
        var skr_after = skr.balanceOf(this);
        assertEq(skr_after - skr_before,  50 ether);
        assertEq(sai_before - sai_after, 101 ether);
    }
    function testGapLimits() public {
        uint256 legal   = 1.04 ether;
        uint256 illegal = 1.06 ether;

        var setGap = bytes4(keccak256("setTapGap(uint256)"));

        assertTrue(mom.call(setGap, legal));
        assertEq(tap.gap(), legal);

        assertTrue(!mom.call(setGap, illegal));
        assertEq(tap.gap(), legal);
    }

    // join and exit have a spread parameter
    function testGapJarBidAsk() public {
        assertEq(tub.per(), ray(1 ether));
        assertEq(tub.bid(1 ether), 1 ether);
        assertEq(tub.ask(1 ether), 1 ether);

        mom.setTubGap(1.01 ether);
        assertEq(tub.bid(1 ether), 0.99 ether);
        assertEq(tub.ask(1 ether), 1.01 ether);

        assertEq(skr.balanceOf(this), 500 ether);
        assertEq(skr.totalSupply(),   500 ether);
        skr.burn(250 ether);

        assertEq(tub.per(), ray(2 ether));
        assertEq(tub.bid(1 ether), 1.98 ether);
        assertEq(tub.ask(1 ether), 2.02 ether);
    }
    function testGapJoin() public {
        gem.deposit.value(100 ether)();

        mom.setTubGap(1.05 ether);
        var skr_before = skr.balanceOf(this);
        var gem_before = gem.balanceOf(this);
        tub.join(100 ether);
        var skr_after = skr.balanceOf(this);
        var gem_after = gem.balanceOf(this);

        assertEq(skr_after - skr_before, 100 ether);
        assertEq(gem_before - gem_after, 105 ether);
    }
    function testGapExit() public {
        gem.deposit.value(100 ether)();
        tub.join(100 ether);

        mom.setTubGap(1.05 ether);
        var skr_before = skr.balanceOf(this);
        var gem_before = gem.balanceOf(this);
        tub.exit(100 ether);
        var skr_after = skr.balanceOf(this);
        var gem_after = gem.balanceOf(this);

        assertEq(gem_after - gem_before,  95 ether);
        assertEq(skr_before - skr_after, 100 ether);
    }
}

contract GasTest is SaiTestBase {
    bytes32 cup;
    function setUp() public {
        super.setUp();

        mark(1 ether);
        gem.deposit.value(1000 ether)();

        mom.setCap(1000 ether);
        mom.setAxe(ray(1 ether));
        mom.setMat(ray(1 ether));
        mom.setTax(ray(1 ether));
        mom.setFee(ray(1 ether));
        mom.setTubGap(1 ether);
        mom.setTapGap(1 ether);

        cup = tub.open();
        tub.join(1000 ether);
        tub.lock(cup, 500 ether);
        tub.draw(cup, 100 ether);
    }
    function doLock(uint256 wad) public logs_gas {
        tub.lock(cup, wad);
    }
    function doFree(uint256 wad) public logs_gas {
        tub.free(cup, wad);
    }
    function doDraw(uint256 wad) public logs_gas {
        tub.draw(cup, wad);
    }
    function doWipe(uint256 wad) public logs_gas {
        tub.wipe(cup, wad);
    }
    function doDrip() public logs_gas {
        tub.drip();
    }
    function doBoom(uint256 wad) public logs_gas {
        tap.boom(wad);
    }

    uint256 tic = 15 seconds;

    function testGasLock() public {
        warp(tic);
        doLock(100 ether);
        // assertTrue(false);
    }
    function testGasFree() public {
        warp(tic);
        doFree(100 ether);
        // assertTrue(false);
    }
    function testGasDraw() public {
        warp(tic);
        doDraw(100 ether);
        // assertTrue(false);
    }
    function testGasWipe() public {
        warp(tic);
        doWipe(100 ether);
        // assertTrue(false);
    }
    function testGasBoom() public {
        warp(tic);
        tub.join(10 ether);
        sai.mint(100 ether);
        sai.push(tap, 100 ether);
        skr.approve(tap, uint(-1));
        doBoom(1 ether);
        // assertTrue(false);
    }
    function testGasBoomHeal() public {
        warp(tic);
        tub.join(10 ether);
        sai.mint(100 ether);
        sin.mint(100 ether);
        sai.push(tap, 100 ether);
        sin.push(tap,  50 ether);
        skr.approve(tap, uint(-1));
        doBoom(1 ether);
        // assertTrue(false);
    }
    function testGasDripNoop() public {
        tub.drip();
        doDrip();
    }
    function testGasDrip1s() public {
        warp(1 seconds);
        doDrip();
    }
    function testGasDrip1m() public {
        warp(1 minutes);
        doDrip();
    }
    function testGasDrip1h() public {
        warp(1 hours);
        doDrip();
    }
    function testGasDrip1d() public {
        warp(1 days);
        doDrip();
    }
}

contract FeeTest is SaiTestBase {
    function feeSetup() public returns (bytes32 cup) {
        mark(10 ether);
        mark(gov, 1 ether / 2);
        gem.deposit.value(1000 ether)();
        gov.mint(100 ether);

        mom.setCap(1000 ether);
        mom.setFee(1000000564701133626865910626);  // 5% / day

        // warp(1 days);  // make chi,rhi != 1

        cup = tub.open();
        tub.join(100 ether);
        tub.lock(cup, 100 ether);
        tub.draw(cup, 100 ether);
    }
    function testFeeSet() public {
        assertEq(tub.fee(), ray(1 ether));
        mom.setFee(ray(1.000000001 ether));
        assertEq(tub.fee(), ray(1.000000001 ether));
    }
    function testFeeSetup() public {
        feeSetup();
        assertEq(tub.chi(), ray(1 ether));
        assertEq(tub.rhi(), ray(1 ether));
    }
    function testFeeDrip() public {
        feeSetup();
        warp(1 days);
        assertEq(tub.chi() / 10 ** 9, 1.00 ether);
        assertEq(tub.rhi() / 10 ** 9, 1.05 ether);
    }
    // Unpaid fees do not accumulate as sin
    function testFeeIce() public {
        var cup = feeSetup();
        assertEq(tub.din(),    100 ether);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.rap(cup),   0 ether);
        warp(1 days);
        assertEq(tub.din(),    100 ether);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.rap(cup),   5 ether);
    }
    function testFeeDraw() public {
        var cup = feeSetup();
        warp(1 days);
        assertEq(tub.rap(cup),   5 ether);
        tub.draw(cup, 100 ether);
        assertEq(tub.rap(cup),   5 ether);
        warp(1 days);
        assertEq(tub.rap(cup),  15.25 ether);
    }
    function testFeeWipe() public {
        var cup = feeSetup();
        warp(1 days);
        assertEq(tub.rap(cup),   5 ether);
        tub.wipe(cup, 50 ether);
        assertEq(tub.rap(cup),  2.5 ether);
        warp(1 days);
        assertEq(tub.rap(cup),  5.125 ether);
    }
    function testFeeCalcFromRap() public {
        var cup = feeSetup();

        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.rap(cup),   0 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.rap(cup),   5 ether);
    }
    function testFeeWipePays() public {
        var cup = feeSetup();
        warp(1 days);

        assertEq(tub.rap(cup),          5 ether);
        assertEq(gov.balanceOf(this), 100 ether);
        tub.wipe(cup, 50 ether);
        assertEq(tub.tab(cup),         50 ether);
        assertEq(gov.balanceOf(this),  95 ether);
    }
    function testFeeWipeMoves() public {
        var cup = feeSetup();
        warp(1 days);

        assertEq(gov.balanceOf(this), 100 ether);
        assertEq(gov.balanceOf(pit),    0 ether);
        tub.wipe(cup, 50 ether);
        assertEq(gov.balanceOf(this),  95 ether);
        assertEq(gov.balanceOf(pit),    5 ether);
    }
    function testFeeWipeAll() public {
        var cup = feeSetup();
        warp(1 days);

        var wad = tub.tab(cup);
        assertEq(wad, 100 ether);
        var owe = tub.rap(cup);
        assertEq(owe, 5 ether);

        var ( , , art, ire) = tub.cups(cup);
        assertEq(art, 100 ether);
        assertEq(ire, 100 ether);
        assertEq(rdiv(wad, tub.chi()), art);
        assertEq(rdiv(add(wad, owe), tub.rhi()), ire);

        assertEq(tub.rap(cup),   5 ether);
        assertEq(tub.tab(cup), 100 ether);
        assertEq(gov.balanceOf(this), 100 ether);
        tub.wipe(cup, 100 ether);
        assertEq(tub.rap(cup), 0 ether);
        assertEq(tub.tab(cup), 0 ether);
        assertEq(gov.balanceOf(this), 90 ether);
    }
    function testFeeWipeNoFeed() public {
        var cup = feeSetup();
        pep.void();
        warp(1 days);

        // fees continue to accumulate
        assertEq(tub.rap(cup),   5 ether);

        // gov is no longer taken
        assertEq(gov.balanceOf(this), 100 ether);
        tub.wipe(cup, 50 ether);
        assertEq(gov.balanceOf(this), 100 ether);

        // fees are still wiped proportionally
        assertEq(tub.rap(cup),  2.5 ether);
        warp(1 days);
        assertEq(tub.rap(cup),  5.125 ether);
    }
    function testFeeWipeShut() public {
        var cup = feeSetup();
        warp(1 days);
        tub.shut(cup);
    }
    function testFeeWipeShutEmpty() public {
        feeSetup();
        var cup = tub.open();
        tub.join(100 ether);
        tub.lock(cup, 100 ether);
        warp(1 days);
        tub.shut(cup);
    }
}

contract PitTest is SaiTestBase {
    function testPitBurns() public {
        gov.mint(1 ether);
        assertEq(gov.balanceOf(pit), 0 ether);
        gov.push(pit, 1 ether);

        // mock gov authority
        var guard = new DSGuard();
        guard.permit(pit, gov, bytes4(keccak256('burn(uint256)')));
        gov.setAuthority(guard);

        assertEq(gov.balanceOf(pit), 1 ether);
        pit.burn(gov);
        assertEq(gov.balanceOf(pit), 0 ether);
    }
}

contract FeeTaxTest is SaiTestBase {
    function feeSetup() public returns (bytes32 cup) {
        mark(10 ether);
        mark(gov, 1 ether / 2);
        gem.deposit.value(1000 ether)();
        gov.mint(100 ether);

        mom.setCap(1000 ether);
        mom.setFee(1000000564701133626865910626);  // 5% / day
        mom.setTax(1000000564701133626865910626);  // 5% / day

        // warp(1 days);  // make chi,rhi != 1

        cup = tub.open();
        tub.join(100 ether);
        tub.lock(cup, 100 ether);
        tub.draw(cup, 100 ether);
    }
    function testFeeTaxDrip() public {
        feeSetup();
        warp(1 days);
        assertEq(tub.chi() / 10 ** 9, 1.0500 ether);
        assertEq(tub.rhi() / 10 ** 9, 1.1025 ether);
    }
    // Unpaid fees do not accumulate as sin
    function testFeeTaxIce() public {
        var cup = feeSetup();

        assertEq(tub.tab(cup), 100 ether);
        assertEq(tub.rap(cup),   0 ether);

        assertEq(tub.din(),    100 ether);
        assertEq(tap.joy(),      0 ether);

        warp(1 days);

        assertEq(tub.tab(cup), 105 ether);
        assertEq(tub.rap(cup),   5.25 ether);

        assertEq(tub.din(),    105 ether);
        assertEq(tap.joy(),      5 ether);
    }
    function testFeeTaxDraw() public {
        var cup = feeSetup();
        warp(1 days);
        assertEq(tub.tab(cup), 105 ether);
        tub.draw(cup, 100 ether);
        assertEq(tub.tab(cup), 205 ether);
    }
    function testFeeTaxCalcFromRap() public {
        var cup = feeSetup();

        assertEq(tub.tab(cup), 100.00 ether);
        assertEq(tub.rap(cup),   0.00 ether);
        warp(1 days);
        assertEq(tub.tab(cup), 105.00 ether);
        assertEq(tub.rap(cup),   5.25 ether);
    }
    function testFeeTaxWipeAll() public {
        var cup = feeSetup();
        warp(1 days);

        var wad = tub.tab(cup);
        assertEq(wad, 105 ether);
        var owe = tub.rap(cup);
        assertEq(owe, 5.25 ether);

        var ( , , art, ire) = tub.cups(cup);
        assertEq(art, 100 ether);
        assertEq(ire, 100 ether);
        assertEq(rdiv(wad, tub.chi()), art);
        assertEq(rdiv(add(wad, owe), tub.rhi()), ire);

        sai.mint(5 ether);  // need to magic up some extra sai to pay tax

        assertEq(tub.rap(cup), 5.25 ether);
        assertEq(gov.balanceOf(this), 100 ether);
        tub.wipe(cup, 105 ether);
        assertEq(tub.rap(cup), 0 ether);
        assertEq(gov.balanceOf(this), 89.5 ether);
    }
}

contract AxeTest is SaiTestBase {
    function axeSetup() public returns (bytes32) {
        mom.setCap(1000 ether);
        mark(1 ether);
        mom.setMat(ray(2 ether));       // require 200% collat
        tub.join(20 ether);
        var cup = tub.open();
        tub.lock(cup, 20 ether);
        tub.draw(cup, 10 ether);       // 200% collateralisation

        return cup;
    }
    function testAxeBite1() public {
        var cup = axeSetup();

        mom.setAxe(ray(1.5 ether));
        mom.setMat(ray(2.1 ether));

        assertEq(tub.ink(cup), 20 ether);
        tub.bite(cup);
        assertEq(tub.ink(cup), 5 ether);
    }
    function testAxeBite2() public {
        var cup = axeSetup();

        mom.setAxe(ray(1.5 ether));
        mark(0.8 ether);    // collateral value 20 -> 16

        assertEq(tub.ink(cup), 20 ether);
        tub.bite(cup);
        assertEq(tub.ink(cup), 1.25 ether);  // (1 / 0.8)
    }
    function testAxeBiteParity() public {
        var cup = axeSetup();

        mom.setAxe(ray(1.5 ether));
        mark(0.5 ether);    // collateral value 20 -> 10

        assertEq(tub.ink(cup), 20 ether);
        tub.bite(cup);
        assertEq(tub.ink(cup), 0 ether);
    }
    function testAxeBiteUnder() public {
        var cup = axeSetup();

        mom.setAxe(ray(1.5 ether));
        mark(0.4 ether);    // collateral value 20 -> 8

        assertEq(tub.ink(cup), 20 ether);
        tub.bite(cup);
        assertEq(tub.ink(cup), 0 ether);
    }
    function testZeroAxeCage() public {
        var cup = axeSetup();

        mom.setAxe(ray(1 ether));

        assertEq(tub.ink(cup), 20 ether);
        top.cage();
        tub.bite(cup);
        tap.vent();
        top.flow();
        assertEq(tub.ink(cup), 10 ether);
    }
    function testAxeCage() public {
        var cup = axeSetup();

        mom.setAxe(ray(1.5 ether));

        assertEq(tub.ink(cup), 20 ether);
        top.cage();
        tub.bite(cup);
        tap.vent();
        top.flow();
        assertEq(tub.ink(cup), 10 ether);
    }
}

contract DustTest is SaiTestBase {
    function testFailLockUnderDust() public {
        tub.join(1 ether);
        var cup = tub.open();
        tub.lock(cup, 0.0049 ether);
    }
    function testFailFreeUnderDust() public {
        tub.join(1 ether);
        var cup = tub.open();
        tub.lock(cup, 1 ether);
        tub.free(cup, 0.995 ether);
    }
}

contract SymbologyTest is SaiTestBase {
    function testSymbology() public {
        assertEq(sai.symbol(), 'DAI');
        assertEq(sin.symbol(), 'SIN');
        assertEq(skr.symbol(), 'PETH');

        assertEq(sai.name(), 'Dai Stablecoin v1.0');
        assertEq(sin.name(), 'SIN');
        assertEq(skr.name(), 'Pooled Ether');
    }
}


================================================
FILE: src/spell.t.sol
================================================
// (c) Nikolai Mushegian, 2017

// Testing using a `DSSpell` as the `hat` in a `DSChief` for one-off
// root calls or role changes.

pragma solidity ^0.4.18;

import 'ds-test/test.sol';

import 'ds-spell/spell.sol';
import 'ds-chief/chief.sol';
import 'ds-token/token.sol';

contract Target is DSThing {
    bool public ouch;
    function poke() public auth {
        ouch = true;
    }
}

contract SpellTest is DSTest {
    Target t;
    DSChief c;
    DSSpell s;
    function setUp() public {
        var gov = new DSToken("GOV");
        var iou = new DSToken("IOU");
        t = new Target();
        c = new DSChief(gov, iou, 1);
    }
    function testRootCall() public {
        // poke() sig: 0x18178358
        bytes memory data = hex"18178358";
        s = new DSSpell(t, 0, data);
    }
    // function testRoleChange() public {
        // require(false);
        // // setUserRole(address,uint8,bool) sig:
        // // TODO complex packing
    // }
}


================================================
FILE: src/tap.sol
================================================
/// tap.sol -- liquidation engine (see also `vow`)

// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>
// Copyright (C) 2017  Daniel Brockman <daniel@dapphub.com>
// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>

// 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/>.

pragma solidity ^0.4.18;

import "./tub.sol";

contract SaiTap is DSThing {
    DSToken  public  sai;
    DST
Download .txt
gitextract__3pdc6gn/

├── .gitattributes
├── .gitignore
├── .gitmodules
├── COPYING
├── DEVELOPING.md
├── Makefile
├── README.md
├── bin/
│   ├── deploy
│   ├── deploy-fab
│   ├── deploy-kovan
│   ├── deploy-pre
│   └── sai
├── libexec/
│   └── sai/
│       ├── sai
│       ├── sai---help
│       ├── sai-air
│       ├── sai-axe
│       ├── sai-bite
│       ├── sai-boom
│       ├── sai-bust
│       ├── sai-cage
│       ├── sai-caged
│       ├── sai-cap
│       ├── sai-cash
│       ├── sai-chi
│       ├── sai-cup
│       ├── sai-cupi
│       ├── sai-cups
│       ├── sai-din
│       ├── sai-draw
│       ├── sai-drip
│       ├── sai-exit
│       ├── sai-fee
│       ├── sai-fit
│       ├── sai-fix
│       ├── sai-fog
│       ├── sai-free
│       ├── sai-gem
│       ├── sai-give
│       ├── sai-gov
│       ├── sai-heal
│       ├── sai-help
│       ├── sai-ink
│       ├── sai-join
│       ├── sai-joy
│       ├── sai-lad
│       ├── sai-lock
│       ├── sai-mat
│       ├── sai-off
│       ├── sai-open
│       ├── sai-out
│       ├── sai-par
│       ├── sai-pep
│       ├── sai-per
│       ├── sai-pie
│       ├── sai-pip
│       ├── sai-pit
│       ├── sai-prod
│       ├── sai-rap
│       ├── sai-ray
│       ├── sai-rhi
│       ├── sai-rho
│       ├── sai-s2s
│       ├── sai-safe
│       ├── sai-sai
│       ├── sai-setAxe
│       ├── sai-setCap
│       ├── sai-setFee
│       ├── sai-setMat
│       ├── sai-setTapGap
│       ├── sai-setTax
│       ├── sai-setTubGap
│       ├── sai-setWay
│       ├── sai-shut
│       ├── sai-sin
│       ├── sai-skr
│       ├── sai-tab
│       ├── sai-tag
│       ├── sai-tapAsk
│       ├── sai-tapBid
│       ├── sai-tapGap
│       ├── sai-tau
│       ├── sai-tax
│       ├── sai-tubAsk
│       ├── sai-tubBid
│       ├── sai-tubGap
│       ├── sai-vent
│       ├── sai-vox
│       ├── sai-wad
│       ├── sai-way
│       ├── sai-wipe
│       └── sai-woe
└── src/
    ├── fab.sol
    ├── fab.t.sol
    ├── mom.sol
    ├── pit.sol
    ├── sai.t.sol
    ├── spell.t.sol
    ├── tap.sol
    ├── top.sol
    ├── tub.sol
    ├── tub.t.sol
    ├── vox.sol
    ├── vox.t.sol
    └── weth9.sol
Condensed preview — 104 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (265K chars).
[
  {
    "path": ".gitattributes",
    "chars": 33,
    "preview": "*.sol linguist-language=Solidity\n"
  },
  {
    "path": ".gitignore",
    "chars": 40,
    "preview": "/out\nload-env*\nload-fab*\naddresses.json\n"
  },
  {
    "path": ".gitmodules",
    "chars": 724,
    "preview": "[submodule \"lib/ds-test\"]\n\tpath = lib/ds-test\n\turl = https://github.com/dapphub/ds-test\n[submodule \"lib/ds-token\"]\n\tpath"
  },
  {
    "path": "COPYING",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "DEVELOPING.md",
    "chars": 13205,
    "preview": "# Sai Developer Documentation\n\nThis is a developer level guide to the Sai source layout and how the\ndifferent objects re"
  },
  {
    "path": "Makefile",
    "chars": 437,
    "preview": "all:; dapp build\ntest:; dapp test\n\nSHELL = bash\ndirs = {bin,libexec}\nprefix ?= /usr/local\n\ndirs:; mkdir -p $(prefix)/$(d"
  },
  {
    "path": "README.md",
    "chars": 12212,
    "preview": "\n\n\n_Please note that this document temporarily refers to sai instead of dai and skr instead of peth. These are just diff"
  },
  {
    "path": "bin/deploy",
    "chars": 2784,
    "preview": "#!/usr/bin/env bash\nset -ex\n\nexport SOLC_FLAGS=${SOLC_FLAGS:-\"--optimize\"}\nexport ETH_GAS=${ETH_GAS:-\"4500000\"}\nexport E"
  },
  {
    "path": "bin/deploy-fab",
    "chars": 1375,
    "preview": "#!/usr/bin/env bash\nset -ex\n\nexport SOLC_FLAGS=${SOLC_FLAGS:-\"--optimize\"}\nexport ETH_GAS=${ETH_GAS:-\"3500000\"}\nexport E"
  },
  {
    "path": "bin/deploy-kovan",
    "chars": 355,
    "preview": "#!/usr/bin/env bash\n\nexport SAI_GEM=0xd0a1e359811322d97991e03f863a0c30c2cf029c\nexport SAI_GOV=0xaaf64bfcc32d0f15873a0216"
  },
  {
    "path": "bin/deploy-pre",
    "chars": 1205,
    "preview": "#!/usr/bin/env bash\nset -ex\n\nexport SOLC_FLAGS=${SOLC_FLAGS:-\"--optimize\"}\nexport ETH_GAS=${ETH_GAS:-\"3500000\"}\nexport E"
  },
  {
    "path": "bin/sai",
    "chars": 69,
    "preview": "#!/usr/bin/env bash\nset -e\nPATH=${0%/*/*}/libexec/sai:$PATH sai \"$@\"\n"
  },
  {
    "path": "libexec/sai/sai",
    "chars": 2769,
    "preview": "#!/usr/bin/env bash\n### sai -- command-line Ethereum RPC client\n### Usage: sai [<options>] <command> [<args>]\n###    or:"
  },
  {
    "path": "libexec/sai/sai---help",
    "chars": 36,
    "preview": "#!/usr/bin/env bash\nset -e\nsai help\n"
  },
  {
    "path": "libexec/sai/sai-air",
    "chars": 136,
    "preview": "#!/usr/bin/env bash\n### sai-air -- get the amount of backing collateral\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"air()\")\nsa"
  },
  {
    "path": "libexec/sai/sai-axe",
    "chars": 127,
    "preview": "#!/usr/bin/env bash\n### sai-axe -- get the liquidation penalty\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"axe()\")\nsai ray -h "
  },
  {
    "path": "libexec/sai/sai-bite",
    "chars": 374,
    "preview": "#!/usr/bin/env bash\n### sai-bite -- initiate liquidation of an undercollateral cup\n### Usage: sai --cup=<id> bite\nset -e"
  },
  {
    "path": "libexec/sai/sai-boom",
    "chars": 345,
    "preview": "#!/usr/bin/env bash\n### sai-boom -- buy some amount of sai to process joy (surplus)\n### Usage: sai boom <amount-in-skr>\n"
  },
  {
    "path": "libexec/sai/sai-bust",
    "chars": 346,
    "preview": "#!/usr/bin/env bash\n### sai-bust -- sell some amount of sai to process woe (bad debt)\n### Usage: sai bust <amount-in-skr"
  },
  {
    "path": "libexec/sai/sai-cage",
    "chars": 531,
    "preview": "#!/usr/bin/env bash\n### sai-cage -- lock the system and initiate settlement\n### Usage: sai cage [<final-price>]\n###   if"
  },
  {
    "path": "libexec/sai/sai-caged",
    "chars": 157,
    "preview": "#!/usr/bin/env bash\n### sai-caged -- get time of cage event (= 0 if system is not caged)\nset -e\necho \"$(seth --to-dec $("
  },
  {
    "path": "libexec/sai/sai-cap",
    "chars": 120,
    "preview": "#!/usr/bin/env bash\n### sai-cap -- get the debt ceiling\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"cap()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-cash",
    "chars": 242,
    "preview": "#!/usr/bin/env bash\n### sai-cash -- cash in sai balance for gems after cage\nset -e\njam=$(token balance \"$(sai sai)\" \"${E"
  },
  {
    "path": "libexec/sai/sai-chi",
    "chars": 127,
    "preview": "#!/usr/bin/env bash\n### sai-chi -- get the internal debt price\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"chi()\")\nsai ray -h "
  },
  {
    "path": "libexec/sai/sai-cup",
    "chars": 259,
    "preview": "#!/usr/bin/env bash\n### sai-cup -- show the cup info\n### Usage: sai --cup=<id> cup\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai cup"
  },
  {
    "path": "libexec/sai/sai-cupi",
    "chars": 157,
    "preview": "#!/usr/bin/env bash\n### sai-cupi -- get the last cup id\nset -e\nid=$(seth call \"${SAI_TUB?}\" \"cupi()\")\nseth --abi-decode "
  },
  {
    "path": "libexec/sai/sai-cups",
    "chars": 642,
    "preview": "#!/usr/bin/env bash\n### sai-cups -- list cups created by you\nset -e\necho >&2 \"Cups created by you...\"\nseth rpc eth_getLo"
  },
  {
    "path": "libexec/sai/sai-din",
    "chars": 127,
    "preview": "#!/usr/bin/env bash\n### sai-din -- get the debt backed by CDPs\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"din()\")\nsai wad -h "
  },
  {
    "path": "libexec/sai/sai-draw",
    "chars": 383,
    "preview": "#!/usr/bin/env bash\n### sai-draw -- issue the specified amount of sai stablecoins\n### Usage: sai --cup=<id> draw <amount"
  },
  {
    "path": "libexec/sai/sai-drip",
    "chars": 122,
    "preview": "#!/usr/bin/env bash\n### sai-drip -- recalculate the internal debt price\nset -e\n(set -x; seth send \"${SAI_TUB?}\" \"drip()\""
  },
  {
    "path": "libexec/sai/sai-exit",
    "chars": 266,
    "preview": "#!/usr/bin/env bash\n### sai-exit -- sell SKR for gems\n### Usage: sai exit <amount-in-skr>\nset -e\n[ $# = 1 ] || sai exit "
  },
  {
    "path": "libexec/sai/sai-fee",
    "chars": 122,
    "preview": "#!/usr/bin/env bash\n### sai-fee -- get the governance fee\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"fee()\")\nsai ray -h \"$ray"
  },
  {
    "path": "libexec/sai/sai-fit",
    "chars": 136,
    "preview": "#!/usr/bin/env bash\n### sai-fit -- get the gem per skr settlement price\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"fit()\")\nsa"
  },
  {
    "path": "libexec/sai/sai-fix",
    "chars": 136,
    "preview": "#!/usr/bin/env bash\n### sai-fix -- get the gem per sai settlement price\nset -e\nray=$(seth call \"${SAI_TOP?}\" \"fix()\")\nsa"
  },
  {
    "path": "libexec/sai/sai-fog",
    "chars": 141,
    "preview": "#!/usr/bin/env bash\n### sai-fog -- get the amount of skr pending liquidation\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"fog()"
  },
  {
    "path": "libexec/sai/sai-free",
    "chars": 377,
    "preview": "#!/usr/bin/env bash\n### sai-free -- remove excess SKR collateral from a cup\n### Usage: sai --cup=<id> free <amount-in-sk"
  },
  {
    "path": "libexec/sai/sai-gem",
    "chars": 158,
    "preview": "#!/usr/bin/env bash\n### sai-gem -- get the collateral token\nset -e\ngem=$(seth call \"${SAI_TUB?}\" 'gem()')\necho \"0x$(seth"
  },
  {
    "path": "libexec/sai/sai-give",
    "chars": 312,
    "preview": "#!/usr/bin/env bash\n### sai-give -- transfer ownership of a cup\n### Usage: sai --cup=<id> give <address>\nset -e\n[ $# = 1"
  },
  {
    "path": "libexec/sai/sai-gov",
    "chars": 151,
    "preview": "#!/usr/bin/env bash\n### sai-gov -- get the gov token\nset -e\ngov=$(seth call \"${SAI_TUB?}\" 'gov()')\necho \"0x$(seth --abi-"
  },
  {
    "path": "libexec/sai/sai-heal",
    "chars": 98,
    "preview": "#!/usr/bin/env bash\n### sai-heal -- cancel debt\nset -e\n(set -x; seth send \"${SAI_TAP?}\" \"heal()\")\n"
  },
  {
    "path": "libexec/sai/sai-help",
    "chars": 1080,
    "preview": "#!/usr/bin/env bash\n### sai-help -- print help about sai(1) or one of its subcommands\n### Usage: sai help [<command>]\n##"
  },
  {
    "path": "libexec/sai/sai-ink",
    "chars": 238,
    "preview": "#!/usr/bin/env bash\n### sai-ink -- get the amount of skr collateral locked in a cup\n### Usage: sai --cup=<id> ink\nset -e"
  },
  {
    "path": "libexec/sai/sai-join",
    "chars": 276,
    "preview": "#!/usr/bin/env bash\n### sai-join -- buy SKR for gems\n### Usage: sai join <amount-in-skr>\nset -e\n[ $# = 1 ] || sai join -"
  },
  {
    "path": "libexec/sai/sai-joy",
    "chars": 129,
    "preview": "#!/usr/bin/env bash\n### sai-joy -- get the amount of surplus sai\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"joy()\")\nsai wad -"
  },
  {
    "path": "libexec/sai/sai-lad",
    "chars": 246,
    "preview": "#!/usr/bin/env bash\n### sai-lad -- get the owner of a cup\n### Usage: sai --cup=<id> lad\nset -e\n[ ! -z \"$SAI_CUP\" ] || sa"
  },
  {
    "path": "libexec/sai/sai-lock",
    "chars": 375,
    "preview": "#!/usr/bin/env bash\n### sai-lock -- post additional SKR collateral to a cup\n### Usage: sai --cup=<id> lock <amount-in-sk"
  },
  {
    "path": "libexec/sai/sai-mat",
    "chars": 125,
    "preview": "#!/usr/bin/env bash\n### sai-mat -- get the liquidation ratio\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"mat()\")\nsai ray -h \"$"
  },
  {
    "path": "libexec/sai/sai-off",
    "chars": 98,
    "preview": "#!/usr/bin/env bash\n### sai-off -- get the cage flag\nset -e\nseth call \"${SAI_TUB?}\" \"off()(bool)\"\n"
  },
  {
    "path": "libexec/sai/sai-open",
    "chars": 1038,
    "preview": "#!/usr/bin/env bash\n### sai-open -- create a new cup (collateralized debt position)\nset -e\necho >&2 \"Opening cup...\"\nexp"
  },
  {
    "path": "libexec/sai/sai-out",
    "chars": 108,
    "preview": "#!/usr/bin/env bash\n### sai-out -- get the post cage exit flag\nset -e\nseth call \"${SAI_TUB?}\" \"out()(bool)\"\n"
  },
  {
    "path": "libexec/sai/sai-par",
    "chars": 239,
    "preview": "#!/usr/bin/env bash\n### sai-par -- get the accrued holder fee (ref per sai)\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()'"
  },
  {
    "path": "libexec/sai/sai-pep",
    "chars": 156,
    "preview": "#!/usr/bin/env bash\n### sai-pep -- get the gov price feed\nset -e\npep=$(seth call \"${SAI_TUB?}\" 'pep()')\necho \"0x$(seth -"
  },
  {
    "path": "libexec/sai/sai-per",
    "chars": 141,
    "preview": "#!/usr/bin/env bash\n### sai-per -- get the current entry price (gem per skr)\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"per()"
  },
  {
    "path": "libexec/sai/sai-pie",
    "chars": 132,
    "preview": "#!/usr/bin/env bash\n### sai-pie -- get the amount of raw collateral\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"pie()\")\nsai wa"
  },
  {
    "path": "libexec/sai/sai-pip",
    "chars": 156,
    "preview": "#!/usr/bin/env bash\n### sai-pip -- get the gem price feed\nset -e\npip=$(seth call \"${SAI_TUB?}\" 'pip()')\necho \"0x$(seth -"
  },
  {
    "path": "libexec/sai/sai-pit",
    "chars": 158,
    "preview": "#!/usr/bin/env bash\n### sai-pit -- get the liquidator vault\nset -e\npit=$(seth call \"${SAI_TUB?}\" 'pit()')\necho \"0x$(seth"
  },
  {
    "path": "libexec/sai/sai-prod",
    "chars": 226,
    "preview": "#!/usr/bin/env bash\n### sai-prod -- recalculate the accrued holder fee (par)\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()"
  },
  {
    "path": "libexec/sai/sai-rap",
    "chars": 223,
    "preview": "#!/usr/bin/env bash\n### sai-rap -- get the amount of governance debt\n### Usage: sai --cup=<id> rap\nset -e\n[ ! -z \"$SAI_C"
  },
  {
    "path": "libexec/sai/sai-ray",
    "chars": 843,
    "preview": "#!/usr/bin/env node\n/// sai-ray -- parse and display a 27-decimal fixed-point number\nvar BigNumber = require(\"bignumber."
  },
  {
    "path": "libexec/sai/sai-rhi",
    "chars": 152,
    "preview": "#!/usr/bin/env bash\n### sai-rhi -- get the internal debt price including governance fee\nset -e\nray=$(seth call \"${SAI_TU"
  },
  {
    "path": "libexec/sai/sai-rho",
    "chars": 161,
    "preview": "#!/usr/bin/env bash\n### sai-rho -- get the time of last drip\nset -e\ntime=$(seth call \"${SAI_TUB?}\" \"rho()\")\ntime_unix=$("
  },
  {
    "path": "libexec/sai/sai-s2s",
    "chars": 144,
    "preview": "#!/usr/bin/env bash\n### sai-s2s -- get the skr per sai rate (for boom and bust)\nset -e\nray=$(seth call \"${SAI_TAP?}\" \"s2"
  },
  {
    "path": "libexec/sai/sai-safe",
    "chars": 248,
    "preview": "#!/usr/bin/env bash\n### sai-safe -- determine if a cup is safe\n### Usage: sai --cup=<id> safe\nset -e\n[ ! -z \"$SAI_CUP\" ]"
  },
  {
    "path": "libexec/sai/sai-sai",
    "chars": 151,
    "preview": "#!/usr/bin/env bash\n### sai-sai -- get the sai token\nset -e\nsai=$(seth call \"${SAI_TUB?}\" 'sai()')\necho \"0x$(seth --abi-"
  },
  {
    "path": "libexec/sai/sai-setAxe",
    "chars": 277,
    "preview": "#!/usr/bin/env bash\n### sai-setAxe -- update the liquidation penalty\n### Usage: sai setAxe <new-axe>\nset -e\n[ $# = 1 ] |"
  },
  {
    "path": "libexec/sai/sai-setCap",
    "chars": 270,
    "preview": "#!/usr/bin/env bash\n### sai-setCap -- update the debt ceiling\n### Usage: sai setCap <new-cap>\nset -e\n[ $# = 1 ] || sai s"
  },
  {
    "path": "libexec/sai/sai-setFee",
    "chars": 271,
    "preview": "#!/usr/bin/env bash\n### sai-setFee -- update the stability fee\n### Usage: sai setFee <new-fee>\nset -e\n[ $# = 1 ] || sai "
  },
  {
    "path": "libexec/sai/sai-setMat",
    "chars": 275,
    "preview": "#!/usr/bin/env bash\n### sai-setMat -- update the liquidation ratio\n### Usage: sai setMat <new-mat>\nset -e\n[ $# = 1 ] || "
  },
  {
    "path": "libexec/sai/sai-setTapGap",
    "chars": 295,
    "preview": "#!/usr/bin/env bash\n### sai-setTapGap -- update the spread on `boom` and `bust`\n### Usage: sai tapGap <new-gap>\nset -e\n["
  },
  {
    "path": "libexec/sai/sai-setTax",
    "chars": 271,
    "preview": "#!/usr/bin/env bash\n### sai-setTax -- update the stability fee\n### Usage: sai setTax <new-tax>\nset -e\n[ $# = 1 ] || sai "
  },
  {
    "path": "libexec/sai/sai-setTubGap",
    "chars": 300,
    "preview": "#!/usr/bin/env bash\n### sai-setTubGap -- update the spread on `join` and `exit`\n### Usage: sai setTubGap <new-gap>\nset -"
  },
  {
    "path": "libexec/sai/sai-setWay",
    "chars": 283,
    "preview": "#!/usr/bin/env bash\n### sai-setWay -- update the holder fee (interest rate)\n### Usage: sai setWay <new-way>\nset -e\n[ $# "
  },
  {
    "path": "libexec/sai/sai-shut",
    "chars": 230,
    "preview": "#!/usr/bin/env bash\n### sai-shut -- close a cup\n### Usage: sai --cup=<id> shut\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai shut --"
  },
  {
    "path": "libexec/sai/sai-sin",
    "chars": 151,
    "preview": "#!/usr/bin/env bash\n### sai-sin -- get the sin token\nset -e\nsin=$(seth call \"${SAI_TUB?}\" 'sin()')\necho \"0x$(seth --abi-"
  },
  {
    "path": "libexec/sai/sai-skr",
    "chars": 151,
    "preview": "#!/usr/bin/env bash\n### sai-skr -- get the skr token\nset -e\nskr=$(seth call \"${SAI_TUB?}\" 'skr()')\necho \"0x$(seth --abi-"
  },
  {
    "path": "libexec/sai/sai-tab",
    "chars": 221,
    "preview": "#!/usr/bin/env bash\n### sai-tab -- get the amount of debt in a cup\n### Usage: sai --cup=<id> tab\nset -e\n[ ! -z \"$SAI_CUP"
  },
  {
    "path": "libexec/sai/sai-tag",
    "chars": 137,
    "preview": "#!/usr/bin/env bash\n### sai-tag -- get the reference price (ref per skr)\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"tag()\")\ns"
  },
  {
    "path": "libexec/sai/sai-tapAsk",
    "chars": 196,
    "preview": "#!/usr/bin/env bash\n### sai-tapAsk -- get the amount of skr in sai for bust\nset -e\n[ $# = 1 ] || sai tapAsk --usage\nwad="
  },
  {
    "path": "libexec/sai/sai-tapBid",
    "chars": 196,
    "preview": "#!/usr/bin/env bash\n### sai-tapBid -- get the amount of skr in sai for boom\nset -e\n[ $# = 1 ] || sai tapBid --usage\nwad="
  },
  {
    "path": "libexec/sai/sai-tapGap",
    "chars": 138,
    "preview": "#!/usr/bin/env bash\n### sai-tapGap -- get the spread on `boom` and `bust`\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"gap()\")\n"
  },
  {
    "path": "libexec/sai/sai-tau",
    "chars": 260,
    "preview": "#!/usr/bin/env bash\n### sai-tau -- get the time of last prod\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\nvox_address=\""
  },
  {
    "path": "libexec/sai/sai-tax",
    "chars": 121,
    "preview": "#!/usr/bin/env bash\n### sai-tax -- get the stability fee\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"tax()\")\nsai ray -h \"$ray\""
  },
  {
    "path": "libexec/sai/sai-tubAsk",
    "chars": 196,
    "preview": "#!/usr/bin/env bash\n### sai-tubAsk -- get the amount of skr in gem for join\nset -e\n[ $# = 1 ] || sai tubAsk --usage\nwad="
  },
  {
    "path": "libexec/sai/sai-tubBid",
    "chars": 196,
    "preview": "#!/usr/bin/env bash\n### sai-tubBid -- get the amount of skr in gem for exit\nset -e\n[ $# = 1 ] || sai tubBid --usage\nwad="
  },
  {
    "path": "libexec/sai/sai-tubGap",
    "chars": 135,
    "preview": "#!/usr/bin/env bash\n### sai-tubGap -- get the spread on `join` and `exit`\nset -e\nwad=$(seth call \"$SAI_TUB\" \"gap()\")\nsai"
  },
  {
    "path": "libexec/sai/sai-vent",
    "chars": 106,
    "preview": "#!/usr/bin/env bash\n### sai-vent -- process a caged tub\nset -e\n(set -x; seth send \"${SAI_TAP?}\" \"vent()\")\n"
  },
  {
    "path": "libexec/sai/sai-vox",
    "chars": 161,
    "preview": "#!/usr/bin/env bash\n### sai-vox -- get the target price engine\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\necho \"0x$(s"
  },
  {
    "path": "libexec/sai/sai-wad",
    "chars": 843,
    "preview": "#!/usr/bin/env node\n/// sai-wad -- parse and display a 18-decimal fixed-point number\nvar BigNumber = require(\"bignumber."
  },
  {
    "path": "libexec/sai/sai-way",
    "chars": 233,
    "preview": "#!/usr/bin/env bash\n### sai-way -- get the holder fee (interest rate)\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\nvox_"
  },
  {
    "path": "libexec/sai/sai-wipe",
    "chars": 381,
    "preview": "#!/usr/bin/env bash\n### sai-wipe -- repay some portion of your existing sai debt\n### Usage: sai --cup=<id> wipe <amount-"
  },
  {
    "path": "libexec/sai/sai-woe",
    "chars": 126,
    "preview": "#!/usr/bin/env bash\n### sai-woe -- get the amount of bad debt\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"woe()\")\nsai wad -h \""
  },
  {
    "path": "src/fab.sol",
    "chars": 6486,
    "preview": "pragma solidity ^0.4.18;\n\nimport \"ds-auth/auth.sol\";\nimport 'ds-token/token.sol';\nimport 'ds-guard/guard.sol';\nimport 'd"
  },
  {
    "path": "src/fab.t.sol",
    "chars": 2644,
    "preview": "pragma solidity ^0.4.18;\n\nimport \"ds-test/test.sol\";\nimport './fab.sol';\n\ncontract BinTest is DSTest {\n    GemFab gemFab"
  },
  {
    "path": "src/mom.sol",
    "chars": 3158,
    "preview": "/// mom.sol -- admin manager\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) 2017  Dani"
  },
  {
    "path": "src/pit.sol",
    "chars": 900,
    "preview": "/// pit.sol -- a simple token burner\n\n// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>\n\n// This program is free "
  },
  {
    "path": "src/sai.t.sol",
    "chars": 82843,
    "preview": "pragma solidity ^0.4.18;\n\nimport \"ds-test/test.sol\";\n\nimport \"ds-math/math.sol\";\n\nimport 'ds-token/token.sol';\nimport 'd"
  },
  {
    "path": "src/spell.t.sol",
    "chars": 964,
    "preview": "// (c) Nikolai Mushegian, 2017\n\n// Testing using a `DSSpell` as the `hat` in a `DSChief` for one-off\n// root calls or ro"
  },
  {
    "path": "src/tap.sol",
    "chars": 3869,
    "preview": "/// tap.sol -- liquidation engine (see also `vow`)\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Co"
  },
  {
    "path": "src/top.sol",
    "chars": 3085,
    "preview": "/// top.sol -- global settlement manager\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C"
  },
  {
    "path": "src/tub.sol",
    "chars": 10537,
    "preview": "/// tub.sol -- simplified CDP engine (baby brother of `vat')\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub."
  },
  {
    "path": "src/tub.t.sol",
    "chars": 4780,
    "preview": "/// tub.t.sol -- Unit tests for tub.sol\n\npragma solidity ^0.4.18;\n\nimport './tub.sol';\nimport './tap.sol';\nimport 'ds-gu"
  },
  {
    "path": "src/vox.sol",
    "chars": 2420,
    "preview": "/// vox.sol -- target price feed\n\n// Copyright (C) 2016, 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) "
  },
  {
    "path": "src/vox.t.sol",
    "chars": 2545,
    "preview": "pragma solidity ^0.4.18;\n\nimport \"ds-test/test.sol\";\nimport \"ds-math/math.sol\";\nimport './vox.sol';\n\ncontract TestWarp i"
  },
  {
    "path": "src/weth9.sol",
    "chars": 37647,
    "preview": "// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it"
  }
]

About this extraction

This page contains the full source code of the makerdao/sai GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 104 files (245.7 KB), approximately 70.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!